Problem triggering voids in other scripts

I’m trying to make an item respawn when the player respawns, but it keeps coming up with NullReferenceException and preventing my player from respawning.

The first script :


private HealthItem potion;

public IEnumerator RespawnPlayer()
    {
        yield return new WaitForSeconds(5f);
        StartCoroutine(potion.Respawn());
        this.gameObject.GetComponent<BoxCollider2D>().enabled = true;
        animator.SetTrigger("ResetAnim");
        rb.gravityScale = 0;
        rb.linearVelocityY = 0;
        yield return new WaitForSeconds(0.3f);
        currentHealth = maxHealth;
        HealthUI.UpdateHealth(currentHealth);
        rb.gravityScale = 1;
        rb.position = respawn.position;
        camcontrols.enabled = true;
        rb.constraints = RigidbodyConstraints2D.FreezeRotation;
        yield return new WaitForSeconds(0.001f);
        camcontrols.Damping = new Vector3(1, 1, 0);
    }

The script I’m trying to call:

public class HealthItem : MonoBehaviour
{
    public IEnumerator Respawn()
    {
        yield return new WaitForSeconds(5f);
        Debug.Log("If you're seeing this, the respawn logic works!");
    }
 }

If anyone has a solution for this please let me know.

What line is the Null reference occurring on? It could be that your potion object isn’t being set correctly. From what you posted I don’t see where its being set at least.

The problem occurs on the StartCoroutine line.

Gotcha, I’d double check that the potion is correctly being set then, maybe add this
Debug.Log(potion)
If it comes back null you know it’s not set.

I’m basically trying to get the first script to call multiple HealthItem scripts at the same time.

Ok, but you still might want to check if those HealthItem objects are set up correctly. Since you’re getting a null ref, I assume they’re not.

How are you establishing a reference to the potion?

A non-serialized private HealthItem potion; field is going to be null by default. You need to actually establish a reference in some way, otherwise you’re trying to access nothing.

This is different to what your code is currently trying to do. It would only start the Respawn coroutine on the one potion you have reference (or not referenced in this case).

You would need to be referencing a collection of objects (such as with a List), or broadcast an event that all potion objects are listening to.

Starting coroutines located in other objects is bad practice, with the exception of static coroutine methods (preferably in static classes) for reusability.

You should relay this by adding a Respawn method in the potion script which then starts the coroutine. Also try to label coroutines consistently ie by suffixing them with coroutine and mark them private by default, to avoid any mistakes. Coroutines should be used sparingly, and managed only by the containing class.

I listed them, but now it says “‘List’ does not contain a definition for ‘RespawnItem’ and no accessible extension method ‘RespawnItem’ accepting a first argument of type ‘List’ could be found (are you missing a using directive or an assembly reference?)”. I’m trying to trigger a void in all of the HealthItem scripts but it apparently doesn’t exist.

The List<T>() class certainly does not contain something like that. Go look in the documentation!

Do you intend to extract a single item from that list and invoke RespawnItem on it??

Either way, these are all just typing mistakes you’re making.

You can fix your own typing mistakes. Here’s how:

Remember: NOBODY here memorizes error codes. That’s not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

The complete error message contains everything you need to know to fix the error yourself.

The important parts of the error message are:

  • the description of the error itself (google this; you are NEVER the first one!)
  • the file it occurred in (critical!)
  • the line number and character position (the two numbers in parentheses)
  • also possibly useful is the stack trace (all the lines of text in the lower console window)

Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly? Are you structuring the syntax correctly? Look for examples!

All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don’t have to stop your progress and fiddle around with the forum.

For future reference, you never need to post for a NullReferenceException. Here’s why:

The answer is always the same… ALWAYS!

How to fix a NullReferenceException error

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that

NullReference is the single most common error while programming. Fixing it is always the same.

Some notes on how to fix a NullReferenceException error in Unity3D:

http://plbm.com/?p=221

As mentioned:
“Do you intend to extract a single item from that list and invoke RespawnItem on it??”
This is most likely the issue that gave you this error at least. I’ve made the same error before, you have something like

myEnemies; // a list of enemies, each has a script with a function like attack()

I try to call

myEnemies.attack(); // doesn't work, myEnemies is the full list
myEnemies[4].attack(); // works, this is one instance in the list