- Home /
Non-static member Unity3d error
Hi,I am developing an FPS for the OUYA with FPS Kit 2.0. I have a problem I got an error when I linked an HealthBar Script from the internet linked with a playerhealth script from FPS Kit. I've tried to search on google there many answers but only code based. So can anyone help me. I am a noob on C#.
Error Assets/HealthBar.cs(39,31): error CS0120: An object reference is required to access non-static member `PlayerDamage.currentHp'
HealthBar.cs using UnityEngine; using System.Collections;
public class HealthBar : MonoBehaviour
{
public GUIStyle progress_empty;
public GUIStyle progress_full;
//current progress
public float barDisplay;
Vector2 pos = new Vector2(10,50);
Vector2 size = new Vector2(250,50);
public Texture2D emptyTex;
public Texture2D fullTex;
void OnGUI()
{
//draw the background:
GUI.BeginGroup(new Rect(pos.x, pos.y, size.x, size.y), emptyTex, progress_empty);
GUI.Box(new Rect(pos.x, pos.y, size.x, size.y), fullTex, progress_full);
//draw the filled-in part:
GUI.BeginGroup(new Rect(0, 0, size.x * barDisplay, size.y));
GUI.Box(new Rect(0, 0, size.x, size.y), fullTex, progress_full);
GUI.EndGroup();
GUI.EndGroup();
}
void Update()
{
//the player's health
barDisplay = PlayerDamage.currentHp/PlayerDamage.Hp;
}
}
PlayerDamage.cs //This script is used to controll player health
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlayerDamage : Photon.MonoBehaviour {
public GUISkin guiSKin;
//Player health
public float hp = 100;
public GameObject ragdoll;
public Texture2D bloodyScreen;
public Texture2D hitMarkTexture;
//Hitboxes and damage properties for each
[System.Serializable]
public class HitBoxes {
public Collider box /*{ get; set; } */;
public float damage /*{ get; set; }*/;
public HitBoxes(Collider box1, float damage1){
box = box1;
damage = damage1;
}
}
public List<HitBoxes> hitBoxes = new List<HitBoxes>();
[HideInInspector]
public float currentHp;
Quaternion camRot;
Quaternion camDefaultRotation;
//Fade hit mark
float fadeValue;
//Fade bloody screen
float fadeValueB;
[HideInInspector]
public bool disableDamage = false;
bool weKilled;
RoomMultiplayerMenu rmm;
void Awake(){
currentHp = hp;
if(!photonView.isMine){
for(int i = 0; i < hitBoxes.Count;i++){
hitBoxes[i].box.gameObject.AddComponent<HitBox>();
hitBoxes[i].box.gameObject.GetComponent<HitBox>().maxDamage = hitBoxes[i].damage;
hitBoxes[i].box.gameObject.GetComponent<HitBox>().playerDamage = this;
hitBoxes[i].box.isTrigger = false;
}
}else{
camDefaultRotation = Camera.main.transform.localRotation;
for(int a = 0; a < hitBoxes.Count;a++){
//We dont need our hit boxes, destroy them
Destroy (hitBoxes[a].box.collider);
}
hitBoxes.Clear();
}
rmm = GameObject.FindWithTag("Network").GetComponent<RoomMultiplayerMenu>();
}
void Update(){
fadeValue = Mathf.Lerp(fadeValue, 0, Time.deltaTime*2);
fadeValueB = Mathf.Lerp(fadeValueB, 0, Time.deltaTime*2);
//Do camera shake effect
if(Camera.main)
Camera.main.transform.localRotation = Quaternion.Slerp(Camera.main.transform.localRotation, camRot, Time.deltaTime * 15);
}
//This is a dmaage our remote player received from Hit Boxes
public void TotalDamage(float damage){
if(disableDamage)
return;
fadeValue = 2;
photonView.RPC("DoDamage", PhotonTargets.All, damage, PhotonNetwork.player);
}
[RPC]
//This is damage sent fro remote player instance to our local
void DoDamage(float damage, PhotonPlayer player){
if(weKilled)
return;
if(currentHp > 0 && photonView.isMine){
this.StopAllCoroutines();
StartCoroutine(doCameraShake());
}
fadeValueB = 2;
currentHp -= damage;
//We got killed
if(currentHp < 0){
//Deactivate all child meshes
for(int i = 0; i < transform.childCount; i++){
transform.GetChild(i).gameObject.SetActive(false);
}
//Spawn ragdoll
GameObject temp;
temp = Instantiate(ragdoll, transform.position, transform.rotation) as GameObject;
if(!photonView.isMine){
temp.SendMessage("clearCamera");
if(PhotonNetwork.player == player){
//Send death notification message to script WhoKilledWho.cs
GameObject.FindWithTag("Network").SendMessage("AddKillNotification", gameObject.name, SendMessageOptions.DontRequireReceiver);
//Add 1 kill for our player
int totalKIlls = (int)PhotonNetwork.player.customProperties["Kills"];
totalKIlls ++;
Hashtable setPlayerKills = new Hashtable() {{"Kills", totalKIlls}};
PhotonNetwork.player.SetCustomProperties(setPlayerKills);
//Add team score
int teamScore = new int();
if((string)PhotonNetwork.player.customProperties["TeamName"] == rmm.team_1.teamName){
teamScore = (int)PhotonNetwork.room.customProperties["Team1Score"];
teamScore ++;
Hashtable setTeam1Score = new Hashtable() {{"Team1Score", teamScore}};
PhotonNetwork.room.SetCustomProperties(setTeam1Score);
}
if((string)PhotonNetwork.player.customProperties["TeamName"] == rmm.team_2.teamName){
teamScore = (int)PhotonNetwork.room.customProperties["Team2Score"];
teamScore ++;
Hashtable setTeam2Score = new Hashtable() {{"Team2Score", teamScore}};
PhotonNetwork.room.SetCustomProperties(setTeam2Score);
}
}
}else{
//print ("We got killed");
temp.SendMessage("RespawnAfter");
//We was killed, add 1 to deaths
int totalDeaths = (int)PhotonNetwork.player.customProperties["Deaths"];
totalDeaths ++;
Hashtable setPlayerDeaths = new Hashtable() {{"Deaths", totalDeaths}};
PhotonNetwork.player.SetCustomProperties(setPlayerDeaths);
//Destroy our player
StartCoroutine(DestroyPlayer(0.2f));
}
currentHp = 0;
weKilled = true;
}
}
IEnumerator DestroyPlayer(float delay){
yield return new WaitForSeconds(delay);
PhotonNetwork.Destroy(gameObject);
}
//Destroy player if we change teams
void SwapTeams(){
photonView.RPC("DoSwapTeams", PhotonTargets.All);
}
[RPC]
void DoSwapTeams(){
GameObject temp;
temp = Instantiate(ragdoll, transform.position, transform.rotation) as GameObject;
if(photonView.isMine){
temp.SendMessage("RespawnAfter");
StartCoroutine(DestroyPlayer(0));
}else{
temp.SendMessage("clearCamera");
}
}
void OnGUI(){
//Display HP for our player only
if(photonView.isMine){
GUI.skin = guiSKin;
GUI.color = new Color(1,1,1,0.9f);
GUI.depth = 10;
GUI.color = new Color(1,1,1,fadeValueB);
GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), bloodyScreen, ScaleMode.StretchToFill );
GUI.color = new Color(1,1,1,0.9f);
//Display player hp
GUI.Box (new Rect (Screen.width - 220,Screen.height - 55,100,45), "HP | " + (int)currentHp);
}else{
GUI.color = new Color(1,1,1, fadeValue);
GUI.DrawTexture(new Rect(Screen.width/2 - 13, Screen.height/2 - 13, 26, 26), hitMarkTexture, ScaleMode.StretchToFill );
}
}
IEnumerator doCameraShake(){
//Change shake amount here (Currently its 10)
camRot = Quaternion.Euler (Random.Range(-10, 10), Random.Range(-10, 10), 0);
yield return new WaitForSeconds(0.1f);
camRot = camDefaultRotation;
}
}
Answer by clunk47 · Jul 26, 2013 at 01:57 PM
You're trying to call a non static variable as if it were static. Use GetComponent to get what you need instead. Keep all your code the way it is except for the barDisplay declaration in HealthBar.cs.
barDisplay = GetComponent<PlayerDamage>().currentHp/GetComponent<PlayerDamage>().hp;
Answer by TK5005 · Jul 25, 2013 at 02:44 PM
A static variable is the same for all instances of a single class. You can access it without creating a new instance of the class that has it (such as what your doing by saying PlayerDamage.currenthp.) The problem is that the currenthp variable in PlayerDamage is not static so you must create a new PlayerDamage class or change currenthp to static (depending on how your code is organized and what is optimal). At the top of your HealthBar class, try creating an instance of the PlayerDamage class and set it equal to the PlayerDamage object you are using in your game. You should then be able to access that variable.
an example of this would be this.
public class PlayerDamage : Photon.$$anonymous$$onoBehaviour {
//preceding members
public static PlayerDamage inst;
//other members, and methods
void Awake(){
// other code in Awake if used
if(inst == null){ inst = thing; }
// other code in Awake if used
}
// other methods
}
I chose Awake as this would allow for other classes to grab the instance in Start(). I know that this is a public instance, and that there are other implementations that utilize a private instance, and getters, but this example is provided for clarity.
Thank you for you answer! I get the part currentHp is not static but how i make the object static, must i do something lik public static or so (sorry iam really noob in it)?
If you create an instance of PlayerDamage you shouldn't have to make anything static. Just like gardian06 wrote, you should just have to make an instance of PlayerDamage and set it equal to the PlayerDamage object your character is using.
I made a mistake when writing the code sample, and did not actually use the static declaration. I have corrected that, and it should now work. (this is what I get from scratch writing, and not copying)
as a side note to access it from another script all you need to do is
PlayerDamage.inst.$$anonymous$$ethodCallX(argList);
or
PlayerDamage.inst.$$anonymous$$emberVariable;
Your answer
Follow this Question
Related Questions
Show GUI only when looking at an object? 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Health not working! 1 Answer
Health and Damage [C#] 2 Answers