- Home /
How to properly instantiate GameObject from a factory class that is not in the scene?
How to properly instantiate GameObject by calling factory class that is not in the scene?
public class BulletFactory {
static private BulletFactory ref_this;
public enum E_BULLET_TYPE { LINEAR, GRANADE }
static public BulletFactory Get() {
return (ref_this != null) ? ref_this : ref_this = new BulletFactory();
}
public void Create(E_BULLET_TYPE type, GameObject prefab, Vector3 pos, Vector2 velocity, int dir)
{
GameObject bullet = MonoBehaviour.Instantiate(prefab, pos, Quaternion.identity);
if (type == E_BULLET_TYPE.LINEAR) {
bullet.GetComponent<LinearBullet>().velocity = velocity;
bullet.GetComponent<LinearBullet>().SetBulletDirection(dir);
}
else if (type == E_BULLET_TYPE.GRANADE) {
bullet.GetComponent<GranadeBullet>().velocity = velocity;
bullet.GetComponent<GranadeBullet>().SetBulletDirection(dir);
}
}
}
This factory class is instantiating object which prefab it got through function parameters. When BulletFactory.Create() is called from some class that is in the scene(Monobehaviour class) everything works as expected. Only problem I have with this is that it gives me warning in console :
The referenced script on this Behaviour (Game Object '<null>') is missing!
UnityEngine.Object:Instantiate(GameObject, Vector3, Quaternion)
The referenced script on this Behaviour (Game Object 'longBullet') is missing!
UnityEngine.Object:Instantiate(GameObject, Vector3, Quaternion)
When doubleclicked warning references to this line:
GameObject bullet = MonoBehaviour.Instantiate(prefab, pos, Quaternion.identity);
Is this the proper way of doing this and should I just ignore this warning?
Have you tried adding the [RuntimeInitializeOnLoad$$anonymous$$ethod] attribute? That might silence the warning.
I think you might be making things a bit more complicated than things need to be. why not $$anonymous$$eep your bulletfactory as a normal monobehavior script. Then simply make your Create function static? I'm not sure but the error looks like something you get when the name of your script in the inpector doesnt match the name of the class in your script. or if you somehow have this attached to a game object without being monobehavior?
First of all I changed Create() function to be static and I'm not making instance oof bullet factory class which makes more sense so thanks for that advice. However warning is still there and when double clicked it points to "GameObject bullet = $$anonymous$$onoBehaviour.Instantiate(prefab, pos, Quaternion.identity);" so I guess is something to do with Instantiating game object from class that is not inheriting $$anonymous$$onobehavior and is not in the scene. Thanks for help, man :).
Answer by xxmariofer · Jan 31, 2019 at 10:41 PM
hello, can you test using Object.Instantiate rather than Monobehaviour.Instantiate? it didnt give me any warnings.
Nope, just tried it, same thing. What version of unity do you use?