I have a parent object (Extras Container) with multiple child objects:
Whenever I press a button, one of the objects is enabled. Only one object can be visible at the same time. Whenever an object is enabled, I can select it and move it around with my mouse.
What I want is whenever I switch between objects, the new object takes the place of the former object (which is currently how it works). But also, when there are NO objects enabled, and I enable an object again, I want it’s position to return to it’s original position where it started.
So, when I switch between “currentObject,” the position stays the same between them. But when no objects are enabled, and I enable the object again through button press, the “currentObject” returns to its “originalPosition.”
Thanks to @unity_ek98vnTRplGj8Q who helped me with this code, which is how things are set up:
public GameObject extrasContainer;
private GameObject currentObject;
private GameObject[] childrenObjects;
public Vector3 originalPos;
public void Start()
{
foreach (Transform t in extrasContainer.GetComponentsInChildren<Transform>(true))
{
if (t.gameObject.activeSelf && t.parent == extrasContainer.transform) currentObject = t.gameObject; //Save whichever one you have activated at the start
t.gameObject.SetActive(true);
}
childrenObjects = new GameObject[extrasContainer.transform.childCount];
foreach (Transform t in extrasContainer.GetComponentsInChildren<Transform>(true))
{
if (t.parent == extrasContainer.transform) childrenObjects[t.GetSiblingIndex()] = t.gameObject;
}
foreach (Transform t in extrasContainer.GetComponentsInChildren<Transform>(true))
{
if (t.gameObject != currentObject)
{
if (t.parent == extrasContainer.transform) t.gameObject.SetActive(false);
}
}
}
//HOOKED UP TO BUTTON
public void ChooseObject(int index)
{
if (index < extrasContainer.transform.childCount)
{
GameObject newObject = childrenObjects[index].gameObject;
if (newObject != currentObject)
{
if (currentObject != null) currentObject.SetActive(false);
newObject.SetActive(true);
currentObject = newObject;
currentText.text = currentObject.name;
}
else
{
currentObject.SetActive(false);
currentObject = null;
}
}
}
I tried using:
currentObject.transform.position = originalPos;
In the else statement before the currentObject is disabled, but it doesn’t work correctly.