I am quite confused as to how GetComponent works and I had a question about how to access a certain function of a script or a variable.
I have a c# script that when i press one, it will access a cannon, which has a bullet attached to it, and i want to access the bullets script.
so something like:
Cannon → Bullet → Bullet’s Script → variable x = 10 OR void xIsTen() gets activated
In C#, you will need to cast the component over, since GetComponent returns a different data type. All you need to do is cast it over. In my example below, I have all of the movement for a multiplayer game stored in a different class (called PlayerInfo). I create a default movement class for all players, and then pull in the component.
So, if I had two scripts, one named PlayerInfo.cs and another named Movement.cs, I could add the following code in Movement.cs to use functions and variables from PlayerInfo.cs
playerInfo = GetComponent(typeof(PlayerInfo)) as PlayerInfo;
If you instantiate the bullet prefab, you will have something like
GameObject bullet = GameObject.Instantiate(bulletPrefab, ...);
The bullet will have the script “CannonOneBullet” attached. So you can write
CannonOneBullet cannonOneBullet = bullet.GetComponent<CannonOneBullet>();
cannonOneBullet.fSpeed = 20.0f;