Hello, my name is David and i'm a bit of problem using GetComponent for C# I'm converting to C# from UnityScript and it's a bit confusing when i get to using GetComponent in C#. Can someone fix this script. Im kinda sure it would work but it keeps getting an error Code (csharp): if(other.gameObject.tag=="Player"){ scriptHealth health; health = healthObject.GetComponent<scriptHealth>(); health.pHealth-=1; Instantiate(bloodObject,transform.position,transform.rotation); print ("touchedplayer"); Destroy(gameObject); } what i want is, when the gameObject touchs the player, it will instantiate a prefab, and then substract health from the playerscript But it wont subtract the health. healthObject is a transform in which the script is located in pHealth is the int inside the script that i want to subtract from. EDIT; Edited.
Well do you have a reference to the healthObject inside the code. Or is it just a object child of the player? because i think you need to use Code (csharp): health = other.GetComponent<scriptHealth>();
My health script is located in a health prefab because it has it's own texture and looks. I want if the enemy to touches the player it will subtract health from the health script In The health prefab If I use Other wouldnt it subtract from the player script? My player script doesnt have a health variable
Well first off you mention this And that more sounded from your players health. But you cannot subtract health from a prefab in script. So you must be explaining it wrong. First when you have a object of the prefab in the game you can change it. So maybe it the instantiate object you are talking about that you create on impact. And if the "prefab" you mention is in the Instantiate in you do. Then you have to get the object of the newly created object. Code (csharp): GameObject NewObject; NewObject = Instantiate(bloodObject,transform.position,transform.rotation) as GameObject; scriptHealth health; health = NewObject.GetComponent<scriptHealth>(); health.pHealth-=1; I think you can even save some code by using Code (csharp): scriptHealth health health = Instantiate(bloodObject,transform.position,transform.rotation) as scriptHealth; health.pHealth-=1;