- Home /
The question is answered, right answer was accepted
An object reference is required to accsess a non-static member 'Lives.loselife()'
code for loose collider
using UnityEngine; using System.Collections;
public class LoseCollider : MonoBehaviour{
private Lives lives;
void Start(){
lives = GameObject.FindObjectOfType<Lives>();
}
void OnTriggerEnter2D(Collider2D trigger){
Lives.loseLife();
}
}
Code for Lives
using UnityEngine; using System.Collections;
public class Lives : MonoBehaviour {
public Sprite[] liveSprites;
private int lives;
private int liveIndex;
private LevelManager LevelManager;
void start() {
LevelManager = GameObject.FindObjectOfType<LevelManager>();
lives = 3;
}
public void loseLife() {
lives--;
assignSprite();
}
void assignSprite() {
liveIndex = lives-1;
this.GetComponent<SpriteRenderer>().sprite=liveSprites[liveIndex];
}
}
FAQ :
Some reasons for getting a post rejected:
Badly formated question: code needs to be formatted using the 101/010 button, break your post up into several parts so it's understandable what you are asking, and make sure there is a question in your post
Posting about a specific compiling error or NullReferenceException: there is a myriad of these questions with answers already, have a look at those posts to get hints on what could possibly be your issue. Also, take a look at the Unity's support website, many errors and how to solve them are described here
Not sure what happened to your other question but try changing start() to Start() . I believe case matters in regards to Unity's Object functions. start() isn't being called by Unity because it is a different script than Start(). That would explain why you got 4 prints rather than 6 prints. Other than that, remember my previous answer regarding accessing a -1 index.
Answer by MattG54321 · Jul 27, 2017 at 12:58 PM
Change Lives.loseLife();
to lives.loseLife();
.
WARNING: Technical explanation below that you don't really need to worry about if you're just beginning.
Why? Lives
(capitalized) refers to your Lives class. lives
(lowercase) refers to an instance of your Lives class that's named lives
.
When you call Lives.loseLife();
, you're trying to call loseLife()
from the class itself. Since it's public void loseLife()
and not public static void loseLife()
, it doesn't belong to the class itself. It belongs to instances of the class.
I hope that makes sense! Check out the Unity - Statics tutorial for more information.
Thanks so much thanks for the explanation too @$$anonymous$$attG54321
Don't forget to mark his answer if it helped you solve the problem.
Happy to help! As @ThePunisher said, please mark the question as answered so others know!
Follow this Question
Related Questions
Can't access a javascript static variable from c# script 1 Answer
C# Going Static or Going OOP 3 Answers
Calling non-static from static function C# 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers