Wrong position (always 0,0,0) when Instantiate prefab.
So i am trying to make simple PingPong 2D, the ball is instantiate when you click "Fire1" and I want to make trail effect with spawnings another balls that are animated to fade out and i want same position as instantiate ball but it is spawning all the time at (0,0,0). I chceked transform.position by Debug.Log and it's good, and show the current position that's why i have no clue what to do :/
The code :
public class TrailBall : MonoBehaviour
{
public GameObject ballPrefabTrail;
public float spawnDuration = 1f;
private float spawnDurationCountdown = 0f;
void Update()
{
if (spawnDurationCountdown <= 0)
{
GameObject instance = Instantiate(ballPrefabTrail, transform.position, transform.rotation) as GameObject;
Debug.Log(transform.position);
Destroy(instance, 3f);
spawnDurationCountdown = spawnDuration;
}
else
{
spawnDurationCountdown -= Time.deltaTime;
}
}
}
Seems like maybe the issue is somewhere else in your code. Do you have any scripts attached to the ballPrefabTrail?
ballPrefabTrail is only a sprite with Animation, but this script is attached to the main ball prefab and the script looks like this : public class SpawnBall : $$anonymous$$onoBehaviour { public Transform ballPointRight; public Transform ballPointLeft;
private Transform ballPointPosition;
public GameObject ballPrefab;
public static GameObject cloneBall;
public static bool canWeSpawn = true;
// Update is called once per frame
void Update()
{
if(Input.GetButtonDown("Fire1") && canWeSpawn == true)
{
if (Ball.addPointRight == true)
{
ballPointPosition = ballPointRight;
Ball.addPointRight = false;
}
else
{
ballPointPosition = ballPointLeft;
}
cloneBall = Instantiate(ballPrefab, ballPointPosition.position, ballPointRight.rotation) as GameObject;
canWeSpawn = false;
}
}
}
As you can see the ball is also instantiate and maybe the fact that I get the clone to cloneBall is something wrong, but the thing is when i checking transform.position in console it's good and don't know why it's spawning at 0,0,0
Answer by BartekWilk · Mar 16, 2020 at 06:24 PM
@Martines_01 First try to set position of the instantiated ball to 0 and then (after instantiation) set instantiated ball position to position of main ball:
// (...)
GameObject instance = Instantiate(ballPrefab, Vector2.zero, transform.rotation) as GameObject;
// Now set position of new ball
instance.transform.position = transform.position;
//(...)
I think that this code will work.