Hey all,
I currently have an issue where I start off with a simple pistol.
Upon pressing “2” an SMG should be instantiated and the previous gun destroyed.
However, while the pistol successfully starts off in the right position and stays there even when switching back to it the SMG is not so obedient. It spawns about 200m away in the x axis and I do not know how to fix it.
The code I use to spawn the guns:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
GameObject startWeapon;
Vector3 startPos;
Quaternion startRot;
GameObject equippedWeaponGO;
void Start ()
{
startWeapon = GameObject.FindGameObjectWithTag("Equipped");
startPos = startWeapon.transform.position;
startRot = startWeapon.transform.rotation;
equippedWeaponGO = startWeapon;
}
void Update ()
{
if(Input.GetKeyDown(KeyCode.Alpha1))
{
EquipWeapon(0);
}
else if(Input.GetKeyDown(KeyCode.Alpha2))
{
EquipWeapon(1);
}
else if(Input.GetKeyDown(KeyCode.Alpha3))
{
EquipWeapon(2);
}
else if(Input.GetKeyDown(KeyCode.Alpha4))
{
EquipWeapon(3);
}
}
void EquipWeapon(int toEquip)
{
if(GameManager.Instance.playersGuns.Count > toEquip)
{
Destroy(equippedWeaponGO);
GameObject newGun = Instantiate(GameManager.Instance.playersGuns[toEquip], startPos, startRot) as GameObject;
newGun.transform.SetParent(Camera.main.transform);
newGun.tag = "Equipped";
equippedWeaponGO = newGun;
}
else
{
Debug.Log("No Weapon in this slot!");
}
}
void OnTriggerEnter(Collider col)
{
Debug.Log(col.gameObject);
if(col.gameObject.tag == "DeathBarrier")
{
Debug.Log("You have collided with " + col.gameObject);
GameManager.Instance.Die();
}
}
}
Here are a couple of pictures, one where the gun is positioned fine and the other is an example of it randomly positioning itself somewhere else.
EDIT:
It works a single time when I compile it without setting the pos and rot when instantiating then back again with setting the pos and rot. Could this be a bug?