Home > other >  Assign sprite to sprite renderer from another class
Assign sprite to sprite renderer from another class

Time:07-12

I am attempting to assign one sprite from a Class A (Dress.cs) to a sprite renderer of a Class B (Body.cs). All what I have is:

NullReferenceException: Object reference not set to an instance of an object Dress.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/Scripts/Dress Scripts/Dress.cs:25)

Here is the code: Body.cs

using System.Collections.Generic;
using UnityEngine;

public class Body : MonoBehaviour
{
    private SpriteRenderer bodyRenderer;

    private void Awake()
    {
        bodyRenderer = GetComponent<SpriteRenderer>();
    }

    public SpriteRenderer GetBodyRenderer
    {
        get { return bodyRenderer; }
        set { bodyRenderer = value; }
    }

    public void SetBodySprite(Sprite inputSprite)
    {
        bodyRenderer.sprite = inputSprite;
    }
}

And Dress.cs

using System.Collections.Generic;
using UnityEngine;

public class Dress : MonoBehaviour
{

    private CircleCollider2D dressCollider;
    private SpriteRenderer dressRenderer;

    private Body body;

    private void Awake()
    {
        body = GetComponent<Body>();
        dressRenderer = GetComponent<SpriteRenderer>();
        dressCollider = GetComponent<CircleCollider2D>();
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Player"))
        {

            if (body.GetBodyRenderer != null)
            {
                SetDressToBody();
            }
        }
    }

    private void SetDressToBody()
    {
        body.SetBodySprite(dressRenderer.sprite);
    }

}

CodePudding user response:

Given that the scripts Body and Dress are attached to different gameobjects, you can't get the Body component in your Dress.cs using the line:

body = GetComponent<Body>();

The above line can only get the reference to the component Body when the script Body.cs is attached to the same gameobject to which the script Dress.cs is attached.

To get the reference to Body component, declare it as a public variable in Dress.cs

public Body body;

Save the files and open Unity. In the inspector of the gameobject to which the script Dress.cs is attached, check for the field Body. Drag the gameobject containing the script Body.cs to the slot in the inspector

CodePudding user response:

if you click on error IDE will show exact line that caused error. I suppose it was

if (body.GetBodyRenderer != null)

because your body is null

  • Related