- Home /
how i instantiate a object make a prefabs at runtime i dont have to save in folder any thing..
I have to convert the single player to multiplayer game so in multiplayer to have player object to spawn to the other devices but i have Ladder and snake game in this don't have the player prefabs because the player is generated while playing the game so how can grab the player run time and instantiate to the other screens. the hierarchy is like this holding the player object is like this...
Answer by UnityCoach · Jul 08, 2017 at 03:57 PM
Prefabs are GameObjects, simply stored as assets.
If you want to instantiate a GameObject that exists in the scene, you have to find it (by name, by tag, by component) and then Instantiate it like you do with a Prefab reference.
Player player = FindObjectOfType<Player>(); // finding the player by component
GameObject player2 = (GameObject)Instantiate (player.gameObject); // instantiate a new copy
GameObject player = GameObject.FindGameObjectWithTag ("Player"); // finding the player by tag
GameObject player2 = (GameObject)Instantiate (player); // instantiate a new copy
GameObject player = GameObject.Find ("Player"); // finding the player by name
GameObject player2 = (GameObject)Instantiate (player); // instantiate a new copy
Answer by epicpython · Jul 16, 2017 at 07:42 PM
@annonymushubh You can't make prefabs at runtime. Prefabs must be stored in a folder, before runtime.
If you want to keep data (such as data about the player) while switching scenes, store it in an object, and put:
public void Awake() { DontDestroyOnLoad(this); }
Here is an example from some of my code for Immune System TD. I load a new scene for each level, but I want to keep the information about which level the player is on, after I move to the new scene.
using UnityEngine; using System.Collections; using System.Collections.Generic;
public class retaindata : MonoBehaviour {
public int LevelNum = 1;//the current level the player is playing
public int getLevelNum()
{
return LevelNum;
}
public void increaseLevelNum()
{
LevelNum += 1;
}
public void resetLevelNum()
{
LevelNum = 1;//reset to level one
}
public void Awake()
{
DontDestroyOnLoad(this);
}
}