BounteousLark
BounteousLark

Reputation: 9

How to reference a variable from another script in a prefab? (beginner question)

I have a game where the player speeds up overtime, and shoots projectile bullets. I want the bullets to stay at the same speed relative to the player. So i have to reference the speed variable in the players script.

there is a similar situation i have found on here,

How to reference a GameObject's position in a prefab script in Unity

but in this they are trying to get a component whereas i am trying to get a variable.

So how would one Reference a variable from another script in a prefab?

On the bullet prefab i have tried

public PlayerScript playerReference; and then playerReference.speed;

Which is how i would normally get references but i cant assign the PlayerScript in the unity editor since the bullet is a prefab.

Upvotes: 0

Views: 103

Answers (2)

2Mult
2Mult

Reputation: 25

First, you would need to reference the player GameObject. For example, you could do this by first tagging the player with any tag (in the case below the tag is "Player"), and then putting the following code in your bullet's script:

player = GameObject.FindWithTag("Player");

From there, you can reference the specific variable by using the following code wherever in the bullet script you want to utilize the speed:

bulletSpeed = player.GetComponent<PlayerScript>().speed

Good luck, and hopefully this works!

Upvotes: 0

Fredrik
Fredrik

Reputation: 5108

You will need a reference to the Player in every bullet, in one way or another. Here is one way to do it:

  • When you create your bullet, get the bullet script and assign the Player to it In your PlayerScript:
void Shoot() 
{
    var bullet = Instantiate(bulletPrefab, bla, bla, bla);
    var bulletScript = bullet.GetComponent<YourBulletScript>();

    bulletScript.PlayerScript = this;
}

and then in the YourBulletScript code you'd get the speed as such:

speed = speed + Player.speed;

Psuedocode because you did not supply your own code, if you want it more detailed you need to be more detailed in your question :)

Upvotes: 0

Related Questions