Script Language: C #
1. Create two objects in the Unity project: Cube and sphere.
2. Add the cubescript and spherescript for the cube and sphere respectively:
In spherescript, the two define a function dosomething (). The specific code of the script is as follows:
using UnityEngine;using System.Collections;public class SphereScript : MonoBehaviour { public int radius = 5; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void DoSomething(){ Debug.Log("Hello ~"); }}
3. Access the sphere of an object in the cubescript script to change its color to red, and access the dosomething function in the spherescript. The specific code is as follows:
Using unityengine; using system. collections; public class cubescript: monobehaviour {// use this for initialization void start () {spherescript A = NULL; // obtain spherescript script a = gameobject. find ("sphere "). getcomponent <spherescript> (); debug. log ("spherescript's a =" +. radius); debug. log ("spherescript's function Domething:"); // call the function a of the spherescript. dosomething ();} // update is called once per frame void Update () {gameobject target = NULL; // access sphere to reference object target = gameobject. find ("sphere"); // Changes the color of the sphere to red target. renderer. material. color = color. red ;}}
4. Running effect: