Change script variable of object in hierarchy using c#
So, I made this little 2 player 1 keyboard game and i'm currently working on powerups for increasing speed for a certain time etc.
That all works fine, except that both players get the effect because i'm using a Game Manager to spawn the players and declare the rounds etc.
Does any1 know how I can access that object that collides with the power up and increase a variable on a script that both players have but only change the value of 1 player(the one that collides with it)
Answer by YoucefB · Sep 30, 2017 at 12:49 PM
You need to use tags for this (https://docs.unity3d.com/Manual/Tags.html)
Here is an exemple:
// attach this to your player Prefab.
public class player : MonoBehaviour{
int powerAmmount = 0;
int powerToAdd = 10; // when colliding with object this ammount will be added
void OnCollisionEnter (Collision col) // replace it with "void OnCollisionEnter2D(Collision2D col)" for 2D Collisions
{
if (col.gameObject.tag == "PowerUp") { // add "PowerUp" tag to the powerUp gameObject
powerAmmount += powerToAdd;
// destroy the powerUp Object
Destroy (col.gameObject);
}
}
}
Answer by FortisVenaliter · Sep 29, 2017 at 04:44 PM
However you're detecting the collision currently should return a reference to the collided object.
Since you've included no code or detail, that's about as specific of an answer as I can provide.
Your answer
Follow this Question
Related Questions
Display pictures in assets folder in random order 0 Answers
How can I get bearer token from Facebook login Unity3d 1 Answer
c# animation.Play("animation") 0 Answers
Animator consecutive set parameter problem 0 Answers
Reflection NullReferenceException: Object reference not set to an instance of an object 2 Answers