I followed their advice and I am instantiating a core player prefab for functionality only and then attaching the visual prefab. So at runtime, my hierarchy shows Player > boyPrefab 01(Clone) > … when the player is instantiated.
My goal is to have it to where when I press a numeric key 1-5, the player’s weapon will switch to whatever element is imbued in that key press. What I currently have been trying is adding all five weapons in advice to the prefabs, disabling them, and then toggling the active state depending on which button is pressed, as shown here:
I am not sure if I am going the correct way about doing this because I am unable to access the path to the weapon because the Prefab > root > … > weapon_r is not shown until runtime. Is there a way to access this path in a script or in the inspector so I can toggle the active states there or am I asking the wrong questions?
You just need to give yourself something that allows you to look them up at runtime. Such as a component. Then it’s just a case of GetComponentInChildren at the right time.
I’m trying to implement this and I’m confused because I’ve never used this before. I am adding a certain component to CharacterSpawner and it will let me look up the weapon? So am I putting the weapon path?
Sorry for continuously asking,
So would it be:
-Add component (script) to weapon that identifies it as that specific weapon
-Create an array in CharacterSpawner that holds the components
-Create a function that goes through the array elements and toggles the active states depending on key press
A general component like this?: public class WeaponComponent : MonoBehaviour { public string Element; }
I dragged it to each weapon and clarified in the Inspector text input each element. I then save these changes as the new prefab and add this function to CharacterSpawner:
private WeaponComponent[] playerWeapons;
public void InitializePlayerWeapons(GameObject player)
{
// Get all weapons that have a WeaponComponent
playerWeapons = player.GetComponentsInChildren<WeaponComponent>(true);
if (playerWeapons.Length == 0)
{
Debug.LogError("No weapons found with WeaponComponent!");
return;
}
Debug.Log($"Found {playerWeapons.Length} weapons");
// everything is inactive at the start
foreach (var weapon in playerWeapons)
weapon.gameObject.SetActive(false);
// activate default
playerWeapons[0].gameObject.SetActive(true);
}``