如何控制Unity中的其他对象?
How to control the other object in Unity?
我正在使用 C# for 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];
}
}
}
请帮忙!
谢谢大家
你的rend对象是在start方法中设置的。我认为您需要像这样获取其他游戏对象:
if (other.gameObject.CompareTag ( "Pick Up"))
{
var changeColorObject = other.GetComponent<Renderer>();
changeColorObject.sharedMaterial = material [1];
}
您需要使用GetComponent
on the other variable to access the Renderer
then you can access its 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];
}
}
我正在使用 C# for 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];
}
}
}
请帮忙! 谢谢大家
你的rend对象是在start方法中设置的。我认为您需要像这样获取其他游戏对象:
if (other.gameObject.CompareTag ( "Pick Up"))
{
var changeColorObject = other.GetComponent<Renderer>();
changeColorObject.sharedMaterial = material [1];
}
您需要使用GetComponent
on the other variable to access the Renderer
then you can access its 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];
}
}