Assigning instantiated prefab to a variable

Hi.

I’m trying to instantiate a prefab and assign it to a var, so that I can then use its functions, but I’m unable to.

What I have is a prefab called BulletPrefab with attached script file Bullet.cs containing Bullet class (inherited from MonoBeh).

In my Player class I’ve put this public field

public GameObject BulletPrefab;

and assigned the BulletPrefab to it in the inspector.

Then in Update I use this

		if (Input.GetMouseButtonDown(0))
		{
			Bullet bullet;
			bullet = (Bullet)Instantiate(BulletPrefab, myTransform.position, myTransform.rotation);
			Vector3 dir = Input.mousePosition - myTransform.position;
			bullet.Shoot(dir.normalized);
		}

to shoot the bullet in the direction of mouse cursor on L-click.

When I try to run this I get this error:

InvalidCastException: Cannot cast from source type to destination type.
Player.Update ()   (at Assets\Scripts\Player.cs:24)

Line 24 is the one with Instantiate call.

If I remove the (Bullet) the error changes to

Assets/Scripts/Player.cs(24,25): error CS0266: Cannot implicitly convert type `UnityEngine.Object' to `Bullet'. An explicit conversion exists (are you missing a cast?)

So, questions:
1. How do I do what I want to do so that it works? Am I missing something?
2. Is there a way to pass values to the prefab’s class on Instantiate (constructor style)?

Thats because you cannot cast Object type returned by Instantiate to a script class. You should do this instead:

GameObject bullet;
bullet = (GameObject)Instantiate(BulletPrefab, myTransform.position, myTransform.rotation);

Then, to get the reference to your script:
Bullet scrbullet;
scrbullet = bullet.GetComponent();

As for your second question, no, there is no way to do that. Just make your own function for passing values and call it after instantiating.

Thanks, man. It works now.