0

I want to run metod in the class from another class and both of them atached to different obj

Two classes. the first is:

public class NewScore: MonoBehaviour {
public void updateScoreBy( int intr) {
    Debug.Log("intr+4"+intr+4);
}
}

and the second is:

public class NewPlus: MonoBehaviour {
    public NewScore newscore;
public void OnTriggerEnter2D(Collider2D obj) {
    newscore.updateScoreBy(+1);
}
}

When I run my code I recive an arror "NullReferenceException: Object reference not set to an instance of an object" and it points on newscore.updateScoreBy(+1); How can I fix it?

3 Answers 3

1

You need to initialize public NewScore newscore;: drag drop the object that contains that script on that variable in the Inspector panel

Sign up to request clarification or add additional context in comments.

2 Comments

It doesn't drop on the place in inspector.
if you have one gameobject with NewScore and another with NewPlus you should be able to drag one object to another, on Inspector.
0

depending on what you want to do you could make the function static like:

public static void updateScoreBy(int intr)
{
    Debug.Log("intr+4"+intr+4);
}

and call it with:

NewScore.updateScoreBy(1);

Comments

0

You didn't initialize newscore.

Change your NewPlus class like this so it will initialize newscore on construction.

public class NewPlus: MonoBehaviour {
  public NewScore newscore;
  public NewPlus(){
    newscore=NewScore();
  }
  public void OnTriggerEnter2D(Collider2D obj) {
    newscore.updateScoreBy(+1);
  }
}

2 Comments

have you tried to do the same? doest'n work- shows an error on your fix
I don't know all the classes you are using. Does NewScore have a constructor with no arguments? If not, you are the one to know how to initialize it. I'm just telling you that you should initialize it in your constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.