6
\$\begingroup\$

The script below is added to an empty game object WeaponGroup, which can be populated using the editor. I have made a new game object WeaponGroups which should have a script SetupWeaponGroupsScript. How can I transfer the properties below so that each WeaponGroup (SetupWeaponGroupsScript will have an array of WeaponGroup objects) is setup in a way similar to what is done below, so that I make the SetupWeaponsScript properties hidden to the inspector and populate them through SetupWeaponGroupsScript?

public class SetupWeaponsScript {

// Here's our tuple combining a weapon prefab and a direction.
[System.Serializable]
public struct DirectedWeapon {
    public WeaponScript weapon;
    public WeaponScript.Direction direction;
}

// The prefabs array is now this tuple type.
public DirectedWeapon[] weaponPrefabs;
public WeaponScript[] weapons;

void Start ()
{  
    weapons = new WeaponScript[weaponPrefabs.Length];

    for (int i = 0; i < weaponPrefabs.Length; i++)
    {
        // Using typed Instantiate to save a GetComponent call.
        weapons[i] = Instantiate<WeaponScript>(weaponPrefabs[i].weapon);
        weapons[i].weaponDir = weaponPrefabs[i].direction;
    }      
}  
}

In other words I'd like to have the following hierarchy in the editor:

enter image description here

\$\endgroup\$
3
\$\begingroup\$

Use ScriptableObject. Create a script called WeaponGroups and put this inside:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class WeaponGroup{
    public Weapon[] weapons;
}

[System.Serializable]
public enum WeaponType{
    SWORD, GUN, BOW
}

[System.Serializable]
public enum WeaponDirection{
    LEFT, RIGHT, UP, DOWN
}

[System.Serializable]
public class Weapon{
    public WeaponType type;
    public WeaponDirection direction;
    public int damage;
}


[CreateAssetMenu(fileName = "WeaponGroups", menuName = "Custom/WeaponGroups")]
public class WeaponGroups : ScriptableObject {
    public WeaponGroup[] groups;
}

Now do:

enter image description here

and here go you:

enter image description here

You can use your ScriptableObject wherever you want. Just drop it somewhere :)

\$\endgroup\$
  • \$\begingroup\$ Your WeaponGroups (and possibly the Weapons themselves) could probably stand to be structs here. That'll save a pointer indirection when iterating through the array of them. \$\endgroup\$ – DMGregory Jun 16 '17 at 13:03
  • \$\begingroup\$ That's a point. I wrote that in case someone learns C# before C and have no idea what a struct is :) I'll change it. Thanks! \$\endgroup\$ – Jacob Jun 16 '17 at 15:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.