loading prefab = insane result?

Hi,

I’ve done this before but suddenly i get this weird behaviour when i try to load a prefab by code.

I’ve started a new project (and im also working on a mac atm), and i created a small terain and created a prefab sphere. I also added a RigidBody to the prefab sphere.

In my script i have exactly this code:

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
	
	// Use this for initialization
	void Start ()
	{
		GameObject test = (GameObject)Instantiate ( Resources.Load("test") );
		test.transform.position = new Vector3(50.0f, 20.0f, 50.0f);
	}
	
	// Update is called once per frame
	void Update () 
	{

	}
	
}

I added this script to the camera.

When i run the code i expect it to place my sphere (which is called ‘test’) at the given location. Instead, it spawns alot of spheres and this never stops!

What is going on…!!? I just need to load one sphere programmatically…

Result:

erm, im no scripter but it looks like you’re telling it to just spawn a sphere everywhere you look on every frame everytime it runs the script.

Make a condition on which its triggered so it doesnt create them constantly?

Actually, you have the Instantiate command in the Start(), so every time you spawn a new sphere it will run anything in Start() and spawn a new sphere. An endless loop.

Not sure on the different locations, that could be a rotation in the original prefab maybe?

Like zerobounds said, your best off having a test condition on a master GameObject that will spawn a sphere when needed.

Ok thanks, i’ll have another look.

Started a new project and the problem is gone.

I placed the script inside the camera. So even if a spawn a new sphere, the Start() method should never be called more than once. I added a print(“bla”) in the Start() method to see if it got printed more than once. But that never happend…

Well abyway, no idea what the problem was… I’ll just conitnue with this new project.

Actually, my bad, I didn’t read your post correctly.

You say this script is only on the camera?
If that’s the case, the you are correct, it should only spawn 1 sphere.

There must be something attached to the prefab with this script in it for it to continually spawn more spheres.

You didn’t accidentally put the camera in the prefab did you?

OK, cool. Glad it’s sorted :slight_smile: