- Home /
How to make an object invisible before it is triggered to show?
Hi,
I am working on a 2D mini game.
When the character (player) walks into an invisible trigger, a game object will be shown (and that will be destroyed with Space Bar).
The reason of setting a trigger for each game object is to avoid 1. The player seeing all the game objects too early 2. All the objects being destroyed when the player pushes the space bar for the first time.
My Script for the invisible trigger is successful, however, the game object doesn't go invisible even when the "Sprite Renderer" box under the Inspector has been unchecked- once I start playing the game, it's checked.
I have added a separate under the game object to disable the sprite renderer, however, with that, the object doesn't show.
Thanks in advance!
trigger for the game object to show: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class GameObjShow : MonoBehaviour
{
public GameObject customImage;
private SpriteRenderer rend;
// Start is called before the first frame update
void Start()
{
customImage.SetActive(false);
rend = customImage.GetComponent<SpriteRenderer>();
rend.enabled = false;
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player");
{
customImage.SetActive(true);
Debug.Log("On trigger enter 2D");
rend.enabled = true;
}
}
// Update is called once per frame
void Update()
{
}
}
sprite renderer disabled for the game object:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpriteReaction : MonoBehaviour
{
SpriteRenderer rend;
// Start is called before the first frame update
void Start()
{
rend = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
this.rend.enabled = false;
}
}
Thanks!
Answer by GSGregory · May 08, 2021 at 12:03 AM
I think the issue is that in the OnTriggerEnter2D you call rend, but do not set it. It looks like an issue of scope. I believe this should work, or declare rend = inside of the onTriggerEnter as well private SpriteRenderer rend = customImage.GetComponent<SpriteRenderer>();
Thank you so much for your advice, I have added it under onTriggerEnter2D, and replaced all "SpriteRenderer" in both scripts, and in the inspector of the gameObject I have unchecked the box next to the item name, now I achieved the desired command!
Answer by FrozenTrident · May 09, 2021 at 04:27 AM
I think that you just need to uncheck the object in the inspector and then when you need it you can activate it again with "yourGameObject.SetActive(true);"
Your answer
Follow this Question
Related Questions
Find Tilemap Player is Currently At 0 Answers
Spawn an object with additional parameter 1 Answer
Unity 3D: How to make the gameobject speed increase continuously on tapping quickly? 1 Answer
Script wont let me drag and drop GameObject Of UI Menu into it? 1 Answer
Destroy script turns objects into ghosts 2 Answers