toggling between prefabs
Hi I'm trying to switch between prefabs using a toggle switch. I've set up already five balls turning on and off at the click of a toggle. The trick (and or problem) is having the newly selected ball appear on screen at the same place as the previous ball. Previously working in Unity 4.3.x I had available to me a method from EventSystems called lastSelectedGameObject, which I thought that would help me identify what the previous ball was and place the new ball at with Transform.position. The code that I have written for each of the balls in the Start() method is as follows:
public void Start(){
// Unlocking AirBall
if (sumBalls == 3) {
aToggle.interactable = true;
aBall.SetActive (true);
// Treasure Unlocking animation
}
if (aBall.activeSelf) {
aBall.GetComponent<Renderer>().enabled = true;
lastBall = EventSystem.current.lastSelectedGameObject;
lastBallPos = new Vector3 (lastBall.transform.position.x, lastBall.transform.position.y, lastBall.transform.position.z);
aBall.transform.position = lastBallPos;
}
else {
aBall.SetActive(false);
aBall.GetComponent<Renderer>().enabled = false;
}
}
However, when I've upgraded to Unity 5.3.2, there's a warning in the console about that method being obsolete. My next question regarding this same code is under the "Unlocking AirBall" comment. In this small code, the variable sumBalls is in the code a static int variable because what I was trying to do is calculate the number of 'hit' (also a static variable) from other classes like this:
private static int sumBalls;
public void Awake (){
aBall = GameObject.FindWithTag ("AirBall");
lastBall = new GameObject ();
aBall.SetActive (false);
aToggle = aBall.GetComponent<Toggle> ();
aToggle.interactable = false;
sumBalls = WaterBall.hit + FireBall.hit + LandBall.hit + BowlingBall.hit;
Debug.Log ("Number of hits (AirBall): " + sumBalls.ToString ());
}
I just hope that I'm doing it the right way.
Answer by Owen-Reynolds · Feb 08, 2016 at 05:51 PM
Is that Start code for a newly Instantiate ball? If so, here's the normal way:
When you Instantiate an object, keep the pointer to it and use that to set it up. You can read more about how to find another object's script, etc. But some examples:
GameObject gg = Instantiate(newBallPF);
// move it there yourself:
gg.transform.position = ...
// or tell it's script about where it came from:
gg.GetComponent<BallScript>().oldBall = myOldBall;
gg.GetComponent<BallScript>().ballNum = currentBallNum;
But, are you making more and more balls? If you have 5 balls total, it seems easier just to have them all, and hide and move them as needed.
Your answer
Follow this Question
Related Questions
Referencing components of multiple game objects within an array 0 Answers
Create 2 seperate instances of the same prefab,create 2 Separate instances of the same prefab 0 Answers
What are some best practices for static variables in multiplayer? 0 Answers
Object reference not set to an instance of an object 0 Answers