Trying to set the parent of an instantiated object to another instantiated object
I know how crazy this sounds, but is it even possible? I have a instantiated object called wordClone which I want to set parent to another instantiated object called wordObj. To explain further I will include my code:
enemyClone = Instantiate(enemyPrefab, screenPosition, Quaternion.identity);
enemyClone.transform.SetParent(GameObject.Find("WordManager").GetComponent<WordSpawner>().wordObj.transform);
So for this to work, wordObj which is in the WordSpawner script must be public, but then Unity expects me to create a reference to it in the inspector as it is public, which I can't do as it doesn't exist yet. While this still compiles, it doesn't create the parent since there is no reference. Any ideas how I could do this, perhaps without making wordObj public?
Answer by Papnix · Mar 25, 2018 at 09:20 AM
Hello,
I'm not sure to understand what you exactly want but when you need to access an attribute of a class you generally make it private and create a getter function to access it outside the class. In general, programmers never use public attribute as it's more clean to control the access by get/set function.
in yout case, you can make.
public class WordSpawner : Monobehavior
{
private GameObject wordObj;
void Start()
{
// Initialize your wordObj here
}
Transform GetWordObj()
{
return wordObj;
}
}
I hope it's what you wanted.
Your answer
Follow this Question
Related Questions
Toogle Parent to Camera Function - Google Cardboard 0 Answers
Raycast doesn't hit instantiated object within same frame of instantiation. 0 Answers
When I scale parent, it scales child, how to stop? 0 Answers
Is the public class object in scripts only a reference of the game object's component? 1 Answer
Parenting a GameObject with script not working (C#) 0 Answers