Cant figure out how to make a pickup that swaps one game object for another.
So Ive hit a brick wall. I am trying to make a pickup item that is connected to a scriptable object and swaps my players gun holder for a prefab Game Object. The below code succesfully swaps the sprite of the gun_holder player object but I have no idea what code to use for an entire prefab, I was thinking GameObject.Find("gun_holder") = weapon but the collision2D doesn't like that. Any suggestions much appreciated. My hope for the final function is that it swaps weapons a la Castlevania subweapons while retaining the players ammo within the throw away pickup but I am trying to solve one problem at a time and I am new to Unity and C#. Here is my pickup script, the curretWeapon and Shoot(){ are called by a player controller that works fine:
public class WeaponPickup : MonoBehaviour
{
public Weapon weapon;
private void OnTriggerEnter2D(Collider2D target)
{
if(target.tag == "Player")
//if player Colides with this tag (player) do the following
{
target.GetComponent<playerController>().currentWeapon = weapon;
//in the Player controller set the current weapon to weapon
target.transform.GetChild(2).GetChild(0).GetComponent<SpriteRenderer>().sprite = weapon.weaponSprite;
//in the player object find child 2.0 sprite renderer's sprite replace current weapon sprite with this
Destroy(gameObject); //Destroys picked up object
}
}
}
and here is the ScriptableObject Code that lets me create Weapon Assets (These both work btw, I dont know how to adapt them to swap entire prefabs):
[CreateAssetMenu(fileName = "WeaponManager", menuName = "Weapon")]
//creaate asset menu for the Weapon asset
public class Weapon : ScriptableObject {
public Sprite weaponSprite;
//select which sprite to use (I want this to be a prefab GameObject)
public GameObject bulletPrefab;
// What bullet does it shoot (this could be part of the prefab)
public float fireRate = 1f;
//Firerate (see above)
public int damage = 20;
// how much damage it does (might be better to leave this hear)
public void Shoot(){
//Shoot function is called in the player controller (works)
GameObject bullet = Instantiate(bulletPrefab, GameObject.Find("FirePoint").transform.position, Quaternion.identity);
}
}
// Code in the player controler for reference
//if(Input.GetMouseButton(0))
// {
// if(Time.time >= nextTimeOfFire){
// currentWeapon.Shoot();
// nextTimeOfFire = Time.time + 1 / currentWeapon.fireRate;