How to set instantiated game object as child on collision in C#
Hi, I'm new to Unity and to programming languages, so I assume this has a simple answer I haven't figured out. I'm making a 2D game where you stack objects on a racket, and if the colliders' relative position is too far than the instance of the object is destroyed, and if it is within bounds, then it sticks to the racket. The only way that I've been able to link their movement properly is though setting the object as a child of the racket.
There's no problem with this, until I try to make it an instance of the object prefab. When I do the object prefab script claims it can not set parent of a prefab to prevent data corruption. I want the racket script to InvokeRepeating(instantiationmethod, time, time), but when the object script calls prefabInstance.transform.parent = racket.transform; it comes with the same error, or says prefabInstance is not set to an instance of the object,
Relevant code: On PrefabScript: public void OnCollisionEnter2D(Collision2D c) { Rigidbody2D rb = GetComponent(); rb.velocity = new Vector2(0, 0) * speed; clone.transform.parent = racket.transform; }
On RacketScript: void Start() { InvokeRepeating("AddClone", 0, 2); }
'public void AddClone() { float p = Random.Range(-65, 65); Vector2 random = new Vector2(p, 15); GameObject clone = Instantiate(Resources.Load("Coin"), random, Quaternion.identity) as GameObject; }'
Your answer
Follow this Question
Related Questions
[Solved] Destroy instantiated prefabs with a same tag, one by one, from last instantiated to first ? 2 Answers
instantiate a cloned prefab in another scene 0 Answers
Instantiation help 0 Answers
Game Manager can't decide what the instance of the object is despite just making an instance of it 1 Answer