zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

方法 一个 常用 Unity 三种 引用 赋值
2023-09-27 14:25:49 时间

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

参照之前的博文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 () {
		
	}
}