how to reference assets with variable

I have an object that spwans other objects. I am referencing with the variable myprefab. I try to look for the sprite I want to reference in my asset folder, there is nothing in my asset folder. I try to drag the sprite directly onto the variable and it didn’t work. Why is that?

 public Rigidbody2D myprefab;
    public Transform myObj;
    int y =0;

void FixedUpdate()
    {
        if(Input.GetKeyDown(KeyCode.Mouse0)){
            y+=1;
            Rigidbody2D Square1;
            Square1 = Instantiate(myprefab, new Vector3(myObj.position.x,y,0), Quaternion.identity);
        }
    }

9869304--1422525--upload_2024-6-2_16-34-4.png

9869304--1422522--upload_2024-6-2_16-24-55.png

This is because Sprite is entered into a variable of RigidBody2D format.
It would be a good idea to change myprefab to sprite format or add a new variable.

I don’t quite understand what you mean, can you type out the code and explain a bit more detailed?

It’s not a code thing it’s a setup thing.

Your field is of type Rigidbody2D. A sprite isn’t a rigidbody. You need to ensure that you’re dragging either a rigidbody2d component, or a game object that has a ridigbody2d component on it. Maybe you need to set up a prefab first?

1 Like

I am able to assign the sprite in the field, but nothing gets instantiated when I am clicking.
I tried adding as Rigidbody2D to the end of the instiate statement, but I got typemismatch.

public Sprite myprefab;

void FixedUpdate()
    {
        if(Input.GetKeyDown(KeyCode.Mouse0)){
            y+=1;
            Sprite Square1;
            Square1 = Instantiate(myprefab, new Vector3(myObj.position.x,y,0), Quaternion.identity);
        }
    }

A sprite is just an asset. It only lives in your assets.

The only thing that lives in a scene are game objects and their components.

Like I already said, you need to set up a prefab to instantiate. One with a sprite renderer component most likely.

You probably need to do some more basic Unity learning.