I am trying to have a single class that handles multiple powerups types and using enum for the types of power-ups and switching the powers based on enum however when there are multiple power-ups in the scene then the collision only registers only for the last powerup in the scene and gives all the powers associated with the not collision registered when collides with last powerup in scene,
Here is the powerup class and enum:
using UnityEngine;
[System.Serializable]
public class PowerUp
{
public PowersList ListofPowers;
public string NameofPowerup;
public GameObject PowerUpItem;
[Tooltip("Time")]
public float powerOfftime;
public bool isTrigger = true;
[Tooltip("Modifier")]
public float powerInfluencer;
}
public enum PowersList
{
Move, Jump, Shoot,None
}
Here is the Script for managing powerup class :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PowerManager : MonoBehaviour
{
public List<PowerUp> power;
private Collider2D playerCollider;
private Collider2D objCollider;
PlayerController player;
private float Time;
private float powerupInfluencer;
int index;
private void Awake()
{
}
private void Start()
{
InintalizeComponents();
}
private void Update()
{
TriggerPower();
}
private void InintalizeComponents()
{
player = GetComponent<PlayerController>();
playerCollider = player.GetComponent<CapsuleCollider2D>();
foreach (PowerUp u in power)
{
u.NameofPowerup = u.ListofPowers.ToString();
powerupInfluencer = u.powerInfluencer;
if (u.PowerUpItem.GetComponent<BoxCollider2D>() == null) u.PowerUpItem.AddComponent<BoxCollider2D>();
objCollider = u.PowerUpItem.GetComponent<BoxCollider2D>();
u.isTrigger = objCollider.isTrigger;
Time = u.powerOfftime;
}
}
private void TriggerPower()
{
if (!Touching()) return;
if (Touching())
{
StartCoroutine(GivePower());
}
}
private bool Touching()
{
foreach (PowerUp p in power)
{
if (!objCollider) return false;
if (playerCollider.IsTouching(objCollider)) return true;
}
return false;
}
private IEnumerator GivePower()
{
StartPower();
yield return new WaitForSeconds(Time);
EndPower();
}
private void StartPower()
{
foreach (PowerUp p in power)
{
SwitchPower(p.ListofPowers);
Destroy(p.PowerUpItem);
Debug.Log("PowerStarted");
}
}
private void EndPower()
{
SwitchPower(PowersList.None);
Debug.Log("PowerEnded");
}
private void SwitchPower(PowersList list)
{
foreach (PowerUp p in power)
{
switch (list)
{
case PowersList.Move:
player.moveSpeed = powerupInfluencer;
break;
case PowersList.Jump:
player.jumpSpeed = powerupInfluencer;
break;
case PowersList.None:
player.jumpSpeed = 8; player.moveSpeed = 6;
break;
case PowersList.Shoot:
player.deservedAmmo += Mathf.RoundToInt(powerupInfluencer);
break;
default:
player.moveSpeed = 6; player.jumpSpeed = 8;
break;
}
}
}
}
Please help I am searching for an answer about the week, Thanks in advance. and please suggest is there a better way to do this.