I am attempting to instantiate my player character controller to prevent duplication on Don’tDestroyOnLoad, this is something I cannot do without unfortunately due to the way we have designed the maps.
So to prevent duplication, we want to instantiate the character ONLY if one doesn’t already exist in the scene we are loading, so it would most likely only do it once per new game started, but I think personally that this would be the best way to go.
Couldn’t you just create an if-statement and search the scene to see if a game object with that name or tag already exists? Like something as simple as this:
@GNGification
Sorry, I didn’t specify more.
I am doing this is JS, but I think it is:
#pragma strict
var ObjectToInstantiate : GameObject;
var LocationToPlace : Vector3;
function Start () {
if (GameObject.Find("ObjectToInstantiate"))
{
//if it exists
}
else
{
}
}
function Update () {
}
My problem is working out how to go from there, how to instantiate using a Vector given as a variable, we can’t find anything online that works.
@Kiwasi
I am having quite a bit of trouble working out exactly what a Singleton is, with the code I found, they don’t seem to do anything at all, they seem quite useless, although it may just be what I found, but I think the way I mentioned would be the easiest way for us to do it.
@GNGification
I am talking about setting the Vector3 in the inspector…
So having:
var LocationToPlace : Vector3;
Would give me the ability to set the 3 vectors (X, Y, Z) in the inspector window with the script, just underneath the box for the ObjectToInstantiate GameObject.
For those visiting in 2020+, here’s how I solved this (Yes, singletons are probably better…but I got confused by them).
It’s a GameManager script that spawns the player. If one already exists, destroy the extra one. You can see the entire Unity github repo here. To test, open the B2 scene in the “RoomSwitching” folder and run.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public GameObject player;
void Awake()
{
this.InstantiateController();
}
private void InstantiateController()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(this);
}
else if (this != Instance)
{
Debug.Log("Destroying extra GM");
Destroy(this.gameObject);
}
}
void Start()
{
Debug.Log("Started");
Debug.Log("Player has not spawned. I'll make one for you.");
Instantiate(player, new Vector2(-4, 4), Quaternion.identity);
}
}