- Home /
Instantiate GameObject cloned into wrong position.
I have floating number script that I want to be instantiated every time the sword hits a enemy, the number will display the damage. The issue I have is that every time the prefab object is put in the wrong x and y position. This is a 2D game. An example is that if my hitPoint, where the object will be instantiated, is (78,-36.5,.8) the floating text will be at (0,0,.8). Here is a picture of how the hitPoint is situated, the sword has the collision box and the player holds the sword. This is the first script that takes care of the instantiation of the object,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HurtEnemy : MonoBehaviour {
public int damageToGive;
public GameObject damageBurst; //Blood particle effect
public Transform hitPoint; //Brings in point from game
public GameObject damageNumber; //Used to give the floating number a damage number
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
Debug.Log(hitPoint.position); //For troubleshooting reasons
other.gameObject.GetComponent<EnemyHealthManager>().HurtEnemy(damageToGive); //This is for the blood particle effect
Instantiate(damageBurst, hitPoint.position, hitPoint.rotation); //This is for the blood particle effect
GameObject clone = Instantiate(damageNumber, hitPoint.position, Quaternion.identity) as GameObject; //This is where the issue may be occuring
clone.GetComponent<FloatingNumbers>().damageNumber = damageToGive; //Changes the damage number in another script.
Debug.Log(hitPoint.position);//For troubleshooting reasons
}
}
}
Here is the script that this one calls for the FloatingNumbers,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FloatingNumbers : MonoBehaviour {
public float moveSpeed; //Speed of the floating numbers
public int damageNumber; //Damage that it displays
public Text displayNumber; //The display
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
displayNumber.text = "" + damageNumber; //Turning float into string
transform.position = new Vector3(transform.position.x, transform.position.y + (moveSpeed * Time.deltaTime), transform.position.z); //Making it float
Debug.Log(transform.position); //For troubleshooting
}
}
Here are the Debug.logs that are produced for troubleshooting\
Answer by nwmarkovic · Feb 17, 2018 at 12:20 AM
OK I figured it out, to fix this situations there are two ways, the first is to add
clone.transform.position = hitPoint.position;
after the Debug.Log in the first script and the second way is to rewrite the code for instantiate as,
GameObject clone = Instantiate(damageNumber) as GameObject;
clone.transform.position = hitPoint.position;
clone.transform.rotation = Quaternion.identity;
These are the two ways that solved the problem for me.