Hi, im new to Unity and I did the tutorial about the spaceshooter 2d with C#. I really liked this tutorial and Im planning on doing a spaceshooter too and I would like to have some advice about something Im thinking.
In the tutorial, when we press “Space”, we instanciate the prefabProjectile with
if (Input.GetKeyDown(“space”))
{
Vector3 position = new Vector3(transform.position.x, transform.position.y + transform.localScale.y / 2);
→ Instantiate(projectilePrefab, position, Quaternion.identity);
}
My question is : Is it possible to create an instance of my Class Projectile using a regular constructor like this :
Projectile projectile = new Projectile(position, color, typeOfProjectile)
the variable typeOfProjectile is for seting the “Mouvement Function” of my projectile.
I found it very difficult to use oriented object with the Instantiate function.
thank you for your help. I hope my english isnt too bad, im french :()
It is not possible to instantiate a prefab via a constructor, no. Nor is it possible to attach a MonoBehaviour via a constructor.
What you can do is create your instance and then call an initialize method on the new instance afterwards.
The thing is that Instantiate creates an instance of a GameObject structure - components, child GOs, the works and MonoBehaviours need to be attached to GameObjects when created. Regular constructors have no sensible way of doing either.
Ok thanks for the quick answer :). Today, I tried something with my Missile Object. Here is my code.
This code is on my Enemy Script
if (timer >= 5)
{
//On tire un missile avec l’angle
Instantiate(projectilePrefab);
Missile missile = projectilePrefab.GetComponent(“Missile”) as Missile;
missile.init(myTransform.position , angle, 0.05f);
angle += dAngle;
timer = 0;
}
This is my init function in my Missile.cs Class
public void init(Vector3 Positionvalue, float Anglevalue, float Speedvalue)
{
myTransform.position = Positionvalue;
angle = Anglevalue;
speed = Speedvalue;
//Debug.Log("Angle: " + speed.ToString());
}
But the angle and the speed value are always zero, its like my init function is not working and I dont know what to do. The only thing I have in the Start function of my missile class is myTransform = transform by the way;
Can you help me
Thanks for your time
Kucrapok
You’re calling Init() on the prefab, but it’s the newly created clone that you want to be calling it on.
You can access the newly created clone via the return value of Instantiate().
Ok, I think I know what you mean. I tried something like this
Missile missile = Instanciate(projectilePrefab) as Missile
I got a null reference exception.
So I got 2 questions
-
What does the instanciate return ?
-
What do I need to write to make it work like I want
Thank you !
Kucrapok
What’s the type of projectilePrefab?
Its working !
thx for your help