I swear this isnt just another ‘how to access a script from another script’ question.
I have done a search and found plenty of close examples but nothing quite like the problem i am having.
I have a Prefab with a script on it (Script A) and it needs to access a variable from the player script (Script B). The thing is, this variable can change during gameplay. I’ve learned that you cannot get a prefab to access a scene script. So i thought to make my player a prefab to usethe player prefab script. This works, but when the player picks up an upgrade that changes the variable i want. The instance of the player gets the variable increased, not the prefab of the player which my script A is referencing.
I want to keep the script A on my Prefab, because i have a ton of this item to place around the scene. Its a mining game and my Prefab are the blocks that you mine. The variable is the players mining strength, which is upgradeable.
Script A :
public class RockBasic : MonoBehaviour
{
public int rockHealth = 3;
public Sprite damaged1;
public Sprite damaged2;
PlayerMovement playerMovement;
void Update()
{
SpriteUpdate();
}
void SpriteUpdate()
{
if (rockHealth == 2)
{
this.gameObject.GetComponent<SpriteRenderer>().sprite = damaged1;
}
if (rockHealth == 1)
{
this.gameObject.GetComponent<SpriteRenderer>().sprite = damaged2;
}
if (rockHealth <= 0)
{
Destroy(gameObject);
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
int rockDamage = playerMovement.miningStrength;
rockHealth -= rockDamage;
}
}
}
Script B:
public int miningStrength = 1;
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Upgrade"))
{
Destroy(collision.gameObject);
miningStrength += 1;
}
}
Theres a lot more in script B but none of it is relevant. I have only pasted the part that matters here.
What should i do to get this to work? Is there a better way then using a prefab? I currently have it on a tilemap and use the Gameobject brush from the Tile Pallete to paint the rocks around.
I apologise if this quesiton is dumb in a way i’m not seeing. I have only been coding with C# and unity for around 3 weeks, and i’m still learning.
