Reputation: 21
I am using c# for Unity, I have two objects (the current one which is the one that has the script file, and the other one that I want to change its material), this is my code :
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];
}
}
}
Please help! Thank you all
Upvotes: 0
Views: 239
Reputation: 125255
You need to use 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];
}
}
Upvotes: 1
Reputation: 27944
Your rend object is set in the start method. I think you need to get the other gameObject like:
if (other.gameObject.CompareTag ( "Pick Up"))
{
var changeColorObject = other.GetComponent<Renderer>();
changeColorObject.sharedMaterial = material [1];
}
Upvotes: 1