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)?