Home > Back-end >  I want an Object to spawn in a specific area in my game after i press the button
I want an Object to spawn in a specific area in my game after i press the button

Time:08-02

my game Item is spawnning behind the spawn button in game i don't know what to do to spawn it in the midddle of the screen:

Potion screen

I made a button just for testing purposes to spawn the potion and here is the code i assigned to it to spawn my item:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HerbSpawner : MonoBehaviour
{
    //Here, we declare variables.
    public GameObject objToSpawn;
    public Transform groupTransform;


    //public means the var is exposed in the inspector, which is super helpful.


    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {


        //let's also spawn on button press:
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit2D hit = Physics2D.GetRayIntersection(Camera.main.ScreenPointToRay(Input.mousePosition));

            if (hit.collider && hit.collider.CompareTag("Bush"))
            {
                SpawnIt();
            }
        }

        void SpawnIt()
    {
        //spawn our coin:
        Instantiate(objToSpawn, transform.position, Quaternion.identity, groupTransform);
    }
}
    }

CodePudding user response:

As you want to instantiate it in the middle of the screen,

void SpawnIt()
{
    Vector2 spawnPos = Camera.main.ViewportToWorldPoint(new Vector2(0.5f, 0.5f));
    Instantiate(objToSpawn, spawnPos, Quaternion.identity, groupTransform);
}

Sidenote:

If you are repeatedly spawning in the middle of the screen, cache the spawn position

Vector2 spawnPos;

void Start()
{
    spawnPos = Camera.main.ViewportToWorldPoint(new Vector2(0.5f, 0.5f));
}

void SpawnIt()
{
    Instantiate(objToSpawn, spawnPos, Quaternion.identity, groupTransform);
}
  • Related