I want to Instantiate a prefab within a class that is not attached to the GameObject. The class inherits from an abstract class. I have been scratching my head on this one. So, how does one instantiate a prefab using C#?
Thanks CSDG
I want to Instantiate a prefab within a class that is not attached to the GameObject. The class inherits from an abstract class. I have been scratching my head on this one. So, how does one instantiate a prefab using C#?
Thanks CSDG
It seems your real problem is that you need the prefab reference in your script, right? You need some kind of manager script (a component based singleton would be the best) that is attached to a GameObject in the scene so you can assign the prefab to a public variable.
public class PrefabManager : MonoBehaviour
{
private static PrefabManager m_Instance = null;
public static PrefabManager Instance
{
get
{
if (m_Instance == null)
m_Instance = (PrefabManager)FindObjectOfType(typeof(PrefabManager));
return m_Instance;
}
}
public Transform Projectile;
}
In your class you can do:
public class MyCustomClass
{
void DoSomething()
{
UnityEngine.Object.Instantiate(PrefabManager.Instance.Projectile);
}
}
Another way would be to place your prefab in a Resources folder. Then you can use Resources.Load() to get the prefab reference.
Its works thanks… What I did in order to get the script, I used the following for testing the reference:
Transform obj = PrefabManager.Instance.Projectile;
// Script Missile.cs
Instantiate(obj.GetComponent("Missile"), transform.position, Quaternion.identity);
Thanks CSDG
By the way, You forgot to place the class name in front of the variable Instance.
http://unity3d.com/support/documentation/ScriptReference/Object.Instantiate.html Click the dropdown to change it to C# from Javascript