2016-11-08 72 views
0

我使用C#团结,我有两个对象(目前1这是具有脚本文件中的一个,而且我想改变它的材料的另一个),这是我的代码:如何控制Unity中的其他对象?

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

请帮忙! 谢谢大家

回答

1

您的rend对象在start方法中设置。我认为你需要得到其他游戏对象,如:

if (other.gameObject.CompareTag ("Pick Up")) 
{ 
    var changeColorObject = other.GetComponent<Renderer>(); 
    changeColorObject.sharedMaterial = material [1]; 
} 
+0

谢谢先生:) –

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]; 
    } 
} 
+1

非常感谢! –

相关问题