TheRedosan
TheRedosan

Reputation: 79

How to change the material on a trigger?

I'm doing the Uniy tutorial called "Roll-a-ball" trying to make some changes. Now in trying to change the material of the boxes for 0.5 seconds before being removing when you collect them, but I'm a little lost with this.

My idea was to do it in the OnTriggerEnter method that removes the boxes when you collect them, in the script of the sphere that the player controls.

This is my method. Here I remove the box and increase the score:

private void OnTriggerEnter(Collider other) {
    Destroy(other.gameObject);
    puntos += 1;
    IncrementarPuntos();
}

Any idea how I can do this?

Upvotes: 0

Views: 1543

Answers (1)

Unlocked
Unlocked

Reputation: 648

Get the Renderer component on the object, and then set the renderer's material. Something like:

public Material collectMaterial; // This will allow you to change the material in the inspector

private void OnTriggerEnter(Collider other) {
    other.GetComponent<Renderer>().material = collectMaterial;
    puntos += 1;
    IncrementarPuntos();
    Destroy(other.gameObject, 0.5f); // Destroy after 0.5 seconds.
}

Something to watch out for is if the player tries to collect it multiple times before it's been destroyed. To fix that, you may want to destroy the script with Destroy(this) at the end, though there are other ways of disabling pickup it if you still need another part of the script.

Upvotes: 1

Related Questions