- Home /
Instantiating an Object doesn't use the given position.
Hi, I'm trying to Instantiate a prefab at a randomly generated position, but it always appears at the position the prefab had, when I originally created it. I already looked for similar questions, but I coulnd't find any... Anyways, here is my current code:
 using UnityEngine;
 using System.Collections;
 
 public class AppleManage : MonoBehaviour {
 
     public GameObject Apple;
 
     void Start ()
     {
         InvokeRepeating ("Spawn", 3f, 3f);
     }
 
     void Spawn () 
     {
         int s = Random.Range (1, 4);
 
         if (s == 1)
         {
             Vector3 position = new Vector3(Random.Range(-4.5F, 4.5F), Random.Range(-4.5F, 4.5F), 5.5F);
              Instantiate(Apple, position, Quaternion.identity); 
         }
 
         if (s == 2)
         {
             Vector3 position = new Vector3(5.5F, Random.Range(-4.5F, 4.5F), Random.Range(-4.5F, 4.5F));
             Instantiate(Apple, position, Quaternion.identity); 
         }
 
         if (s == 3)
         {
             Vector3 position = new Vector3(Random.Range (-4.5F, 4.5F), 5.5F, Random.Range(-4.5F, 4.5F));
             Instantiate(Apple, position, Quaternion.identity); 
         }
     }
 }
I don't have unity in front of me so I can't test this, but if all else fails set the position of the object after it gets spawned, so:
 GameObject go = Instantiate(Apple, position, Quaternion.identity) as GameObject; go.transform.position = position; 
Thanks for your answer, but that doesn't seem to solve my problem either. Just to clarify what I did: I once created this Gameobject Apple at a specific location just to see how it looks inside my game.Then I created a prefab from it. But now whenever I try to instantiate this prefab, the original location is used and I don't know what to do...
Use Debug.Log to show what position is and s, also use @CorruptedTNC suggestion to use GameObject go = then use Debug.Log to show go.transform.postion as well.
Answer by Ryunis · Dec 21, 2014 at 02:43 PM
Ok, looks like I'm simply an idiot. I had an animation attached to the prefab, which reset the position everytime. (I thought animation was local...) Thx anyway.
upvote for having the guts to post your error ins$$anonymous$$d of deleting your question.
Your answer
 
 
             