Question by
varunvp · Apr 06, 2016 at 11:56 AM ·
instantiatescene-loadingscene-changefindgameobjectwithtag
How do I instantiate a GameObject in a newly loaded scene from script?
Hey guys, My game has a load screen where the player is able to select the vehicle and the weapons. When he is done, he presses the load button which directs him to the new scene. In this scene I have to Instantiate the vehicle which the player selected in the previous scene. I am not able to do this. The vehicle does not instantiate, and the GameObject where it has to be instantiated by the GameManager Script. Could you tell me what I'm doing wrong?
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using Vexe.Runtime.Types;
using Vexe.FastSave;
using System.IO;
public class GameManager : BaseBehaviour {
public PlayerProfile playerProf;
public bool isNewLevel;
static GameManager instance;
GameObject[] gameObjects;
void Start()
{
if(instance!=null)
GameObject.Destroy(gameObject);
else
{
GameObject.DontDestroyOnLoad(gameObject);
instance = this;
}
}
// Use this for initialization
[Show] void Run ()
{
isNewLevel = true;
if(isNewLevel)
{
playerProf = PlayerProfile.Load(Application.persistentDataPath + "/player.xml");
// Scene nextScene;
do
{
SceneManager.LoadScene("Scenes/TestingScenes/"+playerProf.currentLevel);
}
while(SceneManager.GetActiveScene().isLoaded != true);
var ship = Resources.Load("Vehicles/" + playerProf.currentShip) as GameObject;
var ship2 = Instantiate(ship) as GameObject;
Debug.Log(ship2.transform.position); //Somehow this gets printed, but I don't see it anywhere in the scene
// if(SceneManager.GetActiveScene().isLoaded)
// ship.transform.position = GameObject.Find("Respawn").transform.position;
Debug.Log(ship2.name);
Debug.Log(GameObject.FindGameObjectWithTag("Respawn")); //Shows null, but I have this object in the new scene
var weaponsHolder = ship.transform.Find("Weapons");
var i = 0;
foreach(Transform t in weaponsHolder)
{
var weapon = Resources.Load("/Weapons/" + playerProf.currentWeapons[i++].ToString()) as GameObject;
weapon.transform.SetParent(t, false);
weapon.transform.position = t.position;
}
}
else
{
playerProf = PlayerProfile.Load(Application.persistentDataPath + "/player.xml");
SceneManager.LoadScene(playerProf.currentLevel);
Load.HierarchyFromFile(Application.dataPath + "/Saved Data/Saved Vehicle.gd" + playerProf.currentShip, new GameObject("ROOT"));
Load.HierarchyFromFile(Application.dataPath + "/Saved Data/Saved Objective.gd", new GameObject("ROOT"));
}
}
}
I am assuming that the scene isn't fully loaded, that's why it's not able to find these.
Thanks! @tanoshimi Can you help? You have answered my questions previously many times
Comment