Instantiate object in world C#

I have been looking all over the Unity Forums and Unity Answers for the last two days trying to figure this out. I am trying to spawn a prefab, called cube1, into the world on the start of the scene. Thus far, I have not gotten it to work. My script is very simple.

using UnityEngine;
using System.Collections;

public class RandomPlacement : MonoBehaviour {

	public GameObject myCube;
	public Vector3 spawnSpot = new Vector3(0,2,0);
	
	void Start() {
		GameObject cubeSpawn = (GameObject)Instantiate(myCube, new Vector3(0,2,0), transform.rotation);
	}
	
	void Update() {
	}
}

I have dragged the prefab onto the “Default References” section for “My Cube” in the inspector on my script. I have also tried using

GameObject cubeSpawn = (GameObject)Instantiate(Resources.Load(“Cube1”));

but that has not worked either. Can someone please help? Do I need to have the script and prefab in the same directory? (Under project, the script is in “Scripts” and the prefab is in “Resources”).

I think the problem is that you’re trying to instantiate the cube from itself in a scene where it does not yet exist.

If there isn’t a GameObject already in the scene to which you can attach this script, nothing will be run. Start() runs when the object becomes active, but you need to have something there to call it.

Try this instead:

  1. place an empty gameobject in the scene
  2. attach your script to it

That should allow it to be called.

using UnityEngine;
using System.Collections;

public class onLoad : MonoBehaviour {

public GameObject Character;
public Vector3 spawnLocation = new Vector3(0,2,0);

// Use this for initialization
void Start () {
	GameObject SpawnLocation = (GameObject)Instantiate(Character,spawnLocation,Quaternion.identity);
}

// Update is called once per frame
void Update () {

}

}

Try changing this line:

GameObject cubeSpawn = (GameObject)Instantiate(myCube, new Vector3(0,2,0), transform.rotation);

for:

GameObject cubeSpawn = Instantiate(myCube, spawnSpot, Quaternion.identity);

or simply if you don’t want to modify it anymore:

Instantiate(myCube, spawnSpot, Quaternion.identity);