Reference to any last gameobject unity

Viewed 91

if I click on the object A, the child of Object A appears. If I touch on the object B, the child of Object B appears but the child of last clicked (Object A or C or D etc...) disappears at same time too.

There is a way to reference to last any touched/clicked/collided gameobject ? I saw that before we could use EventSystem.SetSelectedGameObject but I don't know if it is obsolete or not ?

1 Answers

First add tags to object A, B and all the other objects, so your future code knows which one is which.

Second, we add this code:

void Start()
{
if(PlayerPrefs.HasKey("LastObj")
PlayerPrefs.DeleteKey("LastObj");
if(PlayerPrefs.HasKey("TimesPressed")
PlayerPrefs.DeleteKey("TimePressed");
}

public void buttpress(){
PlayerPrefs.SetInt("TimePressed", PlayerPrefs.GetInt("TimePressed")+1);

if(PlayerPrefs.GetInt("TimePressed")==1)
{
//Your first time code here
}else
this.transform.GetChild(0).gameObject.SetActive(true);

if(   GameObject.FindGameObjectWithTag(PlayerPrefs.GetString("LastObj")) != null)
GameObject.FindGameObjectWithTag(PlayerPrefs.GetString("LastObj")).gameObject.SetActive(false);

PlayerPrefs.SetString("LastObj",this.gameObject.tag);

}

I am writing from phone and hopefully I made no mistakes. Write this code and add it to your objects. And do so that when clicked, this function is called.

What I did there is this:

  1. it activates the first object.
  2. gets tag that has been saved in a Playerprefs and deactivate it.
  3. save current Object's tag in Playerprefs.
Related