Elvis
Elvis

Reputation: 117

Object doesn't appear using Sprite Renderer when triggered

I'm making a Mario replica in unity for my homework, and I'm trying to make the "Invisible" block, it starts off invisible, then when hit, it turns visible. I'm trying to use SpriteRenderer.enable to make it work, it works for turning it off in the start, but not when trying to make it visible.

I've tried to create a separate script for this particular block, but results are the same. All the tags are set correctly, I've tried using Debug.log to see if I enter the "if" where the sprite should be enabled, but the result is negative.

This is the start method turning off the sprite renderer for the particular block (it works):

private void Start()
{
    //rendObject = this.gameObject.GetComponent<SpriteRenderer>();
    if (gameObject.tag == "Invisible")
    {
        gameObject.GetComponent<SpriteRenderer>().enabled = false;
    }
}

This is all the blocks script:

private void OnCollisionEnter2D(Collision2D collision)
{
    if (timesToBeHit > 0)
    {
        if (collision.gameObject.tag == "Player" && IsPlayerBelow(collision.gameObject))
        {
            if (gameObject.tag == "Invisible")
            {
                gameObject.GetComponent<SpriteRenderer>().enabled = true;
            }
            collision.gameObject.GetComponent<PlayerController>().isJumping = false; //Mario can't jump higher
            Instantiate(prefabToAppear, transform.parent.transform.position, Quaternion.identity); //instantiate other obj
            timesToBeHit--;
            anim.SetTrigger("GotHit"); //hit animation   
        }
    }

    if (timesToBeHit == 0)
    {
        anim.SetBool("EmptyBlock", true); //change sprite in animator
    }
}

Upvotes: 1

Views: 720

Answers (2)

Nikola G.
Nikola G.

Reputation: 335

We've found a solution in chat, but for all people who may run or have run on this kind of problem will need to check for the next things:

  • Must have 2 Colliders of any type, 1 per gameObject.
  • At least 1 Rigidbogy.
  • Appropriately Collider setup.
  • Appropriate Tags.
  • Appropriate Layer Collision Matrix.

The code below will work.

public SpriteRenderer render;

void Start()
{
    render.enabled = false;
}

private void OnCollisionEnter2D(Collision2D other)
{
    if (other.gameObject.tag == "Player")
    {
        render.enabled = true;
    }
}

Upvotes: 1

Elvis
Elvis

Reputation: 117

public class InvisibleBlock : MonoBehaviour
{
    public SpriteRenderer rendObject;

    private void Start()
    {

        if (gameObject.tag == "Invisible")
        {
            rendObject.enabled = false;
        }
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            rendObject.enabled = true;
        }
    }
}

Separate script, sprite is attached in inspector, same results.

Upvotes: 0

Related Questions