unity常用的例項化一個GameObject的三種方法
阿新 • • 發佈:2019-02-15
1, 直接拖物件賦值。
public GameObject cube;
2, Find函式
public GameObject cube;
public void ChangeColor2Red()
{
print ("Change cube color to red");
cube = GameObject.Find ("Cube");
cube.GetComponent<MeshRenderer> ().material.color = Color.red;
}
參照之前的博文cube = GameObject.FindWithTag ("Cube");//這兒是Tag值 cube = GameObject.FindGameObjectWithTag ("Cube");
3, 不一樣的拖動賦值。
例項化moveCube
ChangeColor.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChangeColor : MonoBehaviour { public Move moveCube; // Use this for initialization void Start () { moveCube.ChangeColor2Red (); } // Update is called once per frame void Update () { } }
Move.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Move : MonoBehaviour { private GameObject cube; public void ChangeColor2Red() { print ("Change cube color to red"); cube = GameObject.Find ("Cube"); cube.GetComponent<MeshRenderer> ().material.color = Color.red; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }