如何控制Unity中的其他对象?

时间:2016-11-08 17:37:35

标签: c# unity3d unity5

我在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];
    }
}
}

请帮忙! 谢谢大家

2 个答案:

答案 0 :(得分:1)

你的rend对象是在start方法中设置的。我认为你需要得到另一个游戏对象:

multi=true

答案 1 :(得分: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];
    }
}