The weirdest thing is happening and after an hour of debugging I’ve given up and decided to ask here.
I am spawning an object fireball to my game world like so:
Instantiate(fireBall, new Vector3(fireBallSpawn.position.x, fireBallSpawn.position.y, fireBallSpawn.position.z), transform.rotation);
fireBallSpawn is a transform that I assigned in the inspector. It is an empty game object that is offset by (0, 1.7, 1) from the player (one unit in front of his face basically). Then a different script takes over and moves the spawned ball forward.
fireBall is a simple prefab of a red sphere
Even before getting to this second script, the ball tends to move to a minus position on the z axis. There is no code in between spawning and moving it, thus the error/bug must be somewhere at instantiation.
The thing is that is only happens sometimes! It’s driving me nuts. If I keep instantiating over and over it will sometimes be in the proper location, and sometimes under the floor.
What am I doing wrong?
Debugging screenshot of a situation where the placement is wrong:
(The 0.0 -3.5 1.0 is the location of my fireBallSpawn. How is this possible?!)
This is the instantiating code that you see in the picture as well:
using UnityEngine;
using System.Collections;
public class PlayerAttack : MonoBehaviour
{
PlayerSelection PS;
public GameObject fireBall;
public Transform fireBallSpawn;
float nextFire = 0f;
public float cooldownTime = 0.5f;
void Start()
{
PS = GetComponent<PlayerSelection>();
}
void Update()
{
if(Input.GetKey (KeyCode.E))
{
//if target present and we may fire (again)
if(PS.selectedGO != null && Time.time > nextFire)
{
nextFire = Time.time + cooldownTime;
Instantiate(fireBall,
new Vector3(fireBallSpawn.position.x, fireBallSpawn.position.y, fireBallSpawn.position.z),
transform.rotation);
}
}
}
}
EDIT: NOW IT IS WORKING. I changed the code to this:
Vector3 spawnPos = new Vector3(fireBallSpawn.transform.position.x,
fireBallSpawn.transform.position.y,
fireBallSpawn.transform.position.z );
Instantiate(fireBallPrefab, spawnPos, transform.rotation)
I am completely lost as to WHY it works and if anyone knows please clarify or tell me what I don’t understand, because to me this is the exact same as before only more lines.