如何在Unity中控制其他对象
本文关键字:控制 其他 对象 Unity | 更新日期: 2023-09-27 18:16:54
我在Unity中使用c#,我有两个对象(当前的一个是有脚本文件的,另一个是我想改变它的材料),这是我的代码:
public class PlayerController : MonoBehaviour {
public Material[] material;
Renderer rend;
public float speed;
private Rigidbody rb;
void Start ()
{
rend = GetComponent<Renderer>();
rend.enabled = true;
rend.sharedMaterial = material [0];
rb = GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag ( "Pick Up"))
{ // Here is the problem, it will change the color of the current object not the other one
rend.sharedMaterial = material [1];
}
}
}
请帮忙!谢谢大家
您的趋势对象是在start方法中设置的。我认为你需要得到其他gameObject,比如:
if (other.gameObject.CompareTag ( "Pick Up"))
{
var changeColorObject = other.GetComponent<Renderer>();
changeColorObject.sharedMaterial = material [1];
}
您需要在另一个变量上使用GetComponent
来访问Renderer
,然后您可以访问它的sharedMaterial
。
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pick Up"))
{
//Get Renderer or Mesh Renderer
Renderer otherRenderer = other.GetComponent<Renderer>();
otherRenderer.sharedMaterial = material[1];
}
}