Unity C# 游戏间物体间的访问

脚本语言:C#

 

1、在Unity工程中新建两个物体:Cube和Sphere

Unity C# 游戏间物体间的访问

2、分别为Cube和Sphere添加脚本CubeScript和SphereScript:

在SphereScript这两个定义一个函数DoSomething(),脚本具体代码如下:

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、在CubeScript脚本中实现对物体Sphere的访问,使它的颜色变为红色,和脚本SphereScript中DoSomething函数的访问,具体代码如下:

using UnityEngine;

using System.Collections;



public class CubeScript : MonoBehaviour {



    // Use this for initialization

    void Start () {



        SphereScript a = null;

        // 获取SphereScript脚本

        a = GameObject.Find("Sphere").GetComponent<SphereScript>();

        Debug.Log ("SphereScript's a = " + a.radius);

        Debug.Log("SphereScript's function Domething :");

        //调用SphereScript脚本的函数

        a.DoSomething ();

    }

    

    // Update is called once per frame

    void Update () {

        GameObject target = null;

        //访问Sphere引用物体

        target = GameObject.Find ("Sphere");

        //使球体颜色变为红色

        target.renderer.material.color = Color.red;

    }

}

 

4、运行效果:

Unity C# 游戏间物体间的访问

Unity C# 游戏间物体间的访问

 

你可能感兴趣的:(unity)