OnTriggerStay2D Change Sprite

Hi all, I am trying to get an object to change sprites if the player is touching the object and pressing the “J” key. I have a an object called “Tree”, which has 3 child objects, “treetop01”, “treelower01” and “collider”, which has a BoxCollider2D trigger attached to it, as well as a script named “GatherResource”. Im trying to get the “treetop01” object to go invisible and the “treelower01” object to change image after the player is touching the box collider using an OnTriggerStay2D in my “GatherResource” script thats attatched to the “collider” object, but I can’t figure out how to change the image of the other objects. If anyone knows what I can do to change this please let me know, and if I’m not making sense or not being specific enough about anything please let me know so I can elaborate.

This is the tree object in the hierarchy:

This is the “collider” object’s inspector:

This is the “GatherResource” script:

using UnityEngine;
using System.Collections;

public class GatherResource : MonoBehaviour {

    void OnTriggerStay2D(Collider2D other)
    {
        if (Input.GetKeyDown("j"))
            Debug.Log("J key was pressed");

    }
      
}

If there is any other information I need to provide just let me know. Thanks in advance!

You don’t need to attach the GatherResource.cs script to your collider. You can attach it to your “tree” gameObject and OnTrigger functions will still be called.

How I would handle this is by first moving the GatherResource script to the “tree” gameObject just because it makes it easier to work with. After this you would want to edit the script to store references of the “treetop01” and “treelower01” SpriteRenderers. Then simply disable “treetop1” and change the “treelower01” sprite.

treetop1.enabled = false;
treelower01.sprite = someSprite;

Thanks for the reply. It makes sense to just put the script on the tree object lol, but how can I store refrences of the treetop01 and treelower01 sprite renderers?

In your GatherResource.cs script:

public SpriteRenderer treetop01;
public SpriteRenderer treelower01;

Assign them in the inspector and you’ll be able to reference them throughout your script when you want to change sprite image or go invisible.