1, 直接拖对象赋值。

public GameObject cube;

unity常用的引用赋值一个GameObject的三种方法_unity

 

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");

参照之前的博文find函数找物体的方法

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 () {
		
	}
}

unity常用的引用赋值一个GameObject的三种方法_unity_02

unity常用的引用赋值一个GameObject的三种方法_FindWithTag_03