instantiate at position

Hello everyone!!!
sorry for a question…how do you spawn an enemy in the position it was before???

I’ll explain… I have an enemy that I insert into the level by taking it from the prefabs… and I place it in several points… now…
if I have placed 3… one in point x one in point y one in point z… when I kill the enemy of the respective point I would like it to appear in the point it belongs to…
I created a gameobject where in the script of the enemy… when he dies I set a variable to 1… in the object script i say if that variable and 1 it creates that enemy and resets the variable to zero…but…
wherever i place the enemy…when it appears and always in the same place… Do you have any suggestions??? thank you in advance

Instantiate has an overload with Vector3 Position:
Unity - Scripting API: Object.Instantiate (unity3d.com)
Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);

1 Like

sorry but i can’t decipher your code…
Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);
Object Instantiate== what would that be?? the name of the object that I put in the inspector to create???
(Object original, my enemy’s script is called zombie… (Zombie original, so what should I write???

Instantiate(greenMageSpawn, new Vector3(transform.position.x, transform.position.y, transform.position.z), Quaternion.identity);
I still get nothing… so an enemy I kill will always appear in the same place… How do I make magic happen?

i think this is good… and a good explanation… so… i am in trouble… so o complex
8777206--1191499--patr.png
look this is my enemy
all closed in 1 gameobject… “position is new for spawn”
Greenmagepatrol… i need to let enemy go left and right thi enemy shoot a magic ball i close in ball holder
green mage is a enemy sprite…
so… now i try to put position where i want he spawn but not working
this is a code i have used…
Instantiate(greenMageSpawn, GetComponent().spawn.position, GetComponent().spawn.rotation);
but when spawn he give me a null reference error… object refernce not set to an istance of an object…
why?? i have assigned all…in prefab is all ok… in game too… but no spawn…
i have tried to make a command from various script… file patrol too… is the same

The answer never changes man, just fix your errors. There’s no negotiating around this. This is the most common error and the answer is ALWAYS the same. ALWAYS!!

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

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

If you’re struggling with step #1, DO NOT go to step #2. Instead, do this:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

1 Like

kurt i think you never read… when uoy found null reference… run to copy and paste :slight_smile:

It does not change anything. If you have a null ref, you need to figure out what causes it and solve it. That never, ever changes.

1 Like

I don’t have null references in this case… forgive me I’m creating a new object… what should it give null??? the enemy itself works well, it doesn’t give errors… when it dies I have to create another one… in the inspector and everything is fine…

However, @Kurt-Dekker was right. Null is null, you need to determine where you refer to the null reference in your code. You also didn’t include the full script, just assumed Instantiate didn’t work, not that you made a mistake somewhere.

The compiler throws an error, there’s no magic to it, you just have to investigate what and where.

1 Like

yes kurt is telling the truth i have not the slightest doubt… I dare not contradict anyone as I am too new to counter any answer… and that I can’t really figure out where it could be I’m still not able to find nulls… I only find them when I don’t drag objects into the inspector… one thing I noticed though is that when I kill the enemy… greenmage disappears but among the objects on the left… the bullets and the patrol persist… now what I mean… even if it were… I’m creating a new object… what does the null have to do with it???

Consider this scenario:

  • At the beginning of the game you have some prefab objects.

  • Check that you are not referencing them anywhere, if you dragged them as an object in another script to use it is an error.

  • The object after destruction, as the name suggests, disappears and leaves null in the functions where it is processed.

  • It’s possible that you’re referencing the object in another function after it’s been destroyed.

  • A sequence of functions may refer to something that no longer exists.

Edit: Stupid thing, make sure you dragged the prefab from the files folder and not from the hierarchy in the inspector.

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

public class GreenMage : MonoBehaviour
{
  
    [Header("IFrame")]
    [SerializeField] private float iFramesDuration;
    [SerializeField] private int nuberOfFlashes;
    private SpriteRenderer spriteRend;

    [Header("Prize")]
    [SerializeField] public GameObject dollar;
    [SerializeField] public GameObject peach;
    [SerializeField] public GameObject silverCoin;
    [SerializeField] public GameObject goldCoin;
    [SerializeField] public GameObject greenEmerald;
    [SerializeField] public GameObject greenDiamond;
    [SerializeField] public GameObject purpleEmerald;
    [SerializeField] public GameObject purpleDiamond;
    [SerializeField] public GameObject redEmerald;
    [SerializeField] public GameObject redDiamond;
    [SerializeField] public GameObject star;
    [SerializeField] public GameObject goldDiamond;

    [Header("Enemy")]
    [SerializeField] public GameObject snail;
    [SerializeField] public GameObject greenMage;
   


    private float timer;

    [Header("Attack Parameters")]
    [SerializeField] private float attackCooldown;
    [SerializeField] private float range;
    [SerializeField] private int dmg;
    [SerializeField] private int enemyHp;

    [Header("Range Attack")]
    [SerializeField] private Transform shootPoint;
    [SerializeField] private GameObject[] mageBall;

    [Header("Collider Parameters")]
    [SerializeField] private float colliderDistance;
    [SerializeField] private CapsuleCollider2D boxCollider;

    [Header("Player Layer")]
    [SerializeField] private LayerMask playerLayer;
    private float cooldownTimer = Mathf.Infinity;

    private Animator anim;
    private GreenMagePatrol enemyPatrol;
   
  
    public GameObject explosion;


    private float spawnPrize;
   
    public Slider enemyHealthBar;
   
    public int greenMageReborn; //for spwan
    public Transform spawn;
  
    private void Awake()
    {

        anim = GetComponent<Animator>();
        enemyPatrol = GetComponentInParent<GreenMagePatrol>();
       
        
        spriteRend = GetComponent<SpriteRenderer>();
        
    }

    private void Update()
    {
        cooldownTimer += Time.deltaTime;

      
        if (PlayerInSight())
        {
            if (cooldownTimer >= attackCooldown)
            {
                cooldownTimer = 0;
                anim.SetTrigger("Attack");
            }
        }

        if (enemyPatrol != null)
            enemyPatrol.enabled = !PlayerInSight();

    }
    private void Start()
    {
        greenMageReborn = 0; //reset spawn to 0
    }
    private void RangeAttack()
    {
        cooldownTimer = 0;
        mageBall[FindMageBall()].transform.position = shootPoint.position;
        mageBall[FindMageBall()].GetComponent<MageBullet>().ActivateProjectile();

    }
    private int FindMageBall()
    {
        for (int i = 0; i < mageBall.Length; i++)
        {
            if (!mageBall[i].activeInHierarchy)
                return i;
        }
        return 0;
    }
    private bool PlayerInSight()
    {
        RaycastHit2D hit =
            Physics2D.BoxCast(boxCollider.bounds.center + transform.right * range * transform.localScale.x * colliderDistance,
            new Vector3(boxCollider.bounds.size.x * range, boxCollider.bounds.size.y, boxCollider.bounds.size.z),
            0, Vector2.left, 0, playerLayer);

        return hit.collider != null;
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireCube(boxCollider.bounds.center + transform.right * range * transform.localScale.x * colliderDistance,
           new Vector3(boxCollider.bounds.size.x * range, boxCollider.bounds.size.y, boxCollider.bounds.size.z));
    }



    private IEnumerator IFramesDuration()
    {
        for (int i = 0; i < nuberOfFlashes; i++)
        {
            spriteRend.color = new Color(1, 0, 0, 0.5f);
            yield return new WaitForSeconds(iFramesDuration / (nuberOfFlashes * 2));
            spriteRend.color = Color.white;
            yield return new WaitForSeconds(iFramesDuration / (nuberOfFlashes * 2));
        }
    }

    void Explosion()
    {
        Instantiate(explosion, transform.position, transform.rotation);
    }
  
    public void TakeDamge(int damageAmount)
    {
        enemyHp -= damageAmount;

        enemyHealthBar.value = enemyHp;
     


        if (enemyHp > 0)
        {
            StartCoroutine(IFramesDuration());//IFRAME
        }
        else if (enemyHp <= 0)
        {
           
            anim.SetTrigger("Death");
            boxCollider.enabled = false;

            AudioManager.instance.Play("SnailDead");
           
                   
           
            if (GetComponentInParent<GreenMagePatrol>() != null)
                GetComponentInParent<GreenMagePatrol>().enabled = false;
           
            if (GetComponent<GreenMage>() != null)
                GetComponent<GreenMage>().enabled = false;
        
            StatsPlayer.greenMageKilled++;//aumento le kill
            StatsPlayer.Enemy3--;//diminuisco il nemico per completare il livello
            StatsPlayer.greenMageReborn = 1;// in other script if is == 1 instantiate 
           
            PlayerPrefs.SetInt("GreenMage", StatsPlayer.greenMageKilled);//salvo la kill
           
           
      
            Destroy(gameObject, this.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).length);

    
            Explosion();
            int spawnPrize = UnityEngine.Random.Range(1, 101);

            greenMageReborn = 1;
           
            if (spawnPrize <= 60)
            {
                SpawnPrize1();
            }
            if (spawnPrize >= 61 && spawnPrize <= 80)
            {
                SpawnPrize2();
            }
            if (spawnPrize >= 81 && spawnPrize <= 90)
            {
                SpawnPrize3();
            }
            if (spawnPrize >= 91 && spawnPrize <= 95)
            {
                SpawnPrize4();
            }
            if (spawnPrize >= 96 && spawnPrize <= 99)
            {
                SpawnPrize5();
            }
            if (spawnPrize == 100)
            {
                SpawnPrize6();
            }

          
        }
    }
    void SpawnPrize1()
    {
        Instantiate(dollar, transform.position, transform.rotation);
        Instantiate(dollar, transform.position, transform.rotation);
        Instantiate(silverCoin, transform.position, transform.rotation);
        Instantiate(silverCoin, transform.position, transform.rotation);
        Instantiate(silverCoin, transform.position, transform.rotation);
    }
    void SpawnPrize2()
    {
        Instantiate(dollar, transform.position, transform.rotation);
        Instantiate(dollar, transform.position, transform.rotation);
        Instantiate(silverCoin, transform.position, transform.rotation);
        Instantiate(silverCoin, transform.position, transform.rotation);
        Instantiate(goldCoin, transform.position, transform.rotation);
        Instantiate(goldCoin, transform.position, transform.rotation);
        Instantiate(goldCoin, transform.position, transform.rotation);
    }
    void SpawnPrize3()
    {
        Instantiate(dollar, transform.position, transform.rotation);
        Instantiate(dollar, transform.position, transform.rotation);
        Instantiate(dollar, transform.position, transform.rotation);
        Instantiate(goldCoin, transform.position, transform.rotation);
        Instantiate(goldCoin, transform.position, transform.rotation);
        Instantiate(goldCoin, transform.position, transform.rotation);
        Instantiate(greenEmerald, transform.position, transform.rotation);
        Instantiate(peach, transform.position, transform.rotation);
    }
    void SpawnPrize4()
    {
        Instantiate(dollar, transform.position, transform.rotation);
        Instantiate(dollar, transform.position, transform.rotation);
        Instantiate(dollar, transform.position, transform.rotation);
        Instantiate(greenEmerald, transform.position, transform.rotation);
        Instantiate(greenEmerald, transform.position, transform.rotation);
        Instantiate(purpleEmerald, transform.position, transform.rotation);
    }
    void SpawnPrize5()
    {
        Instantiate(dollar, transform.position, transform.rotation);
        Instantiate(dollar, transform.position, transform.rotation);
        Instantiate(dollar, transform.position, transform.rotation);
        Instantiate(purpleEmerald, transform.position, transform.rotation);
        Instantiate(purpleEmerald, transform.position, transform.rotation);
        Instantiate(redEmerald, transform.position, transform.rotation);
        Instantiate(peach, transform.position, transform.rotation);
        Instantiate(goldDiamond, transform.position, transform.rotation);
        Instantiate(snail, transform.position, transform.rotation);
        SnailSpawn.snailInGame++;
    }
    void SpawnPrize6()
    {
        Instantiate(dollar, transform.position, transform.rotation);
        Instantiate(dollar, transform.position, transform.rotation);
        Instantiate(dollar, transform.position, transform.rotation);
        Instantiate(greenEmerald, transform.position, transform.rotation);
        Instantiate(purpleEmerald, transform.position, transform.rotation);
        Instantiate(redEmerald, transform.position, transform.rotation);
        Instantiate(goldDiamond, transform.position, transform.rotation);
        Instantiate(goldDiamond, transform.position, transform.rotation);
        Instantiate(goldDiamond, transform.position, transform.rotation);
        Instantiate(greenMage, transform.position, transform.rotation);
        SpawnGreenMage.greenMageInGame++;
    }

  
}

this is a code where i spawn
if (greenMageReborn == 1)
{
Invoke(“RespawnGreenMage”, 3);
greenMageReborn = 0;

void RespawnGreenMage()
{
Instantiate(greenMageSpawn, GetComponent().spawn.position, GetComponent().spawn.rotation);
SpawnGreenMage.greenMageInGame++;

}

here i have in ispector a green mage to spawn

yes from the prefab I drag the enemies I’m interested in starting the game … otherwise how should I do ?? it’s wrong?

So now verify if you dragged greenMageSpawn from the file directory or from the hierarchy of objects in the scene.

from the directory prefabs

but sorry… how do you usually do it??? create the right object?? then if it has to be prefabs you drag it into the folder… then you delete it from the hierarchy… and then you’re going to insert it in the levels you are interested in… and in the copies you are interested in… 1 5 10… or I err???

Yes, you are creating a prefab as you described. Only if you want to instantiate a prefab you need to have a reference to it (to a file).

A beginner might mistakenly just drag something from the hierarchy into a field for a GameObject value, based on which it will instantiate. Only this item needs to be dragged from the file location.

Otherwise, if you destroy an object from the hierarchy, you will get null. Because you were referring to a copy of a prefab, something already initialized.

what do you mean by reference??? when i destroy the enemy it randomly drops rewards as you can see… and it works… for reference I have created a gameobject where I control the progress of the game scores things collected etc etc … and I created the reference there… by dragging the green mage to be created from the prefab into the inspector… are you referring to this???