How can I change sprites when player enters Collider??????

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:
91403-screenshot-2017-04-05-204934.png

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 can either parse the hierarchy to find the child object by name and get its SpriteRenderer component, or simply add a SpriteRenderer reference and assign it manually.

public class GatherResource : MonoBehaviour
{
    public SpriteRenderer treeLower;
    public Sprite treeLowerGathered;
    
    void OnTriggerStay2D (Collider2D other)
    {
        if (other.tag == "Player" && Input.GetKeyDown("j"))
        {
            Debug.Log("J key was pressed");
            treeLower.sprite = treeLowerGathered;
        }
    }
 }

You can do it multiple ways.

  • Get a reference of objects which you need to modify in GatherResource script.

OR

  • Make a script for tree (parent) and have all references in that script including reference to GatherResource object. Have event Action in GatherResources and add listener into parent script and handle that to modify.

    using UnityEngine;
    using System.Collections;

    public class GatherResource : MonoBehaviour {

    public event Action OnKeyPressed;
    void OnTriggerStay2D(Collider2D other)
    {
    if (Input.GetKeyDown(“j”))
    {
    OnKeyPressed();
    Debug.Log(“J key was pressed”);
    }
    }
    }

and on Parent Object class say Tree.cs

public GameObject TreeTop;
public SpriteRenderer TreeLower;
public GatherResource ColliderScript;

void Awake()
{
          ColliderScript.OnKeyPressed += Gather;
}

void Gather()
{
}