The member XXX cannot be used as a method or delegate - c#

I have done copied this of a tutorial online, but when I compile it shows 2 errors as below:
Non-invocable member 'Feature.choices' cannot be used like a method
and
The member `Feature.choices' cannot be used as method or delegate
The last "choices" in the script has a red squiggly line. Any idea that might be wrong?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[ExecuteInEditMode]
public class FeatureManager : MonoBehaviour {
public List<Feature> features;
public int currFeature;
void OnEnable()
{
LoadFeatures();
}
void OnDisable()
{
SaveFeatures();
}
void LoadFeatures()
{
features = new List<Feature>();
features.Add(new Feature(("hair"), transform.FindChild("hair").GetComponent<SpriteRenderer>()));
}
void SaveFeatures()
{
}
}
[System.Serializable]
public class Feature
{
public string ID;
public int currIndex;
public Sprite[] choices;
public SpriteRenderer renderer;
public Feature(string id, SpriteRenderer rend)
{
ID = id;
renderer = rend;
UpdateFeature();
}
public void UpdateFeature()
{
choices = Resources.LoadAll<Sprite>("Character/" + ID);
if (choices == null || renderer == null)
return;
if (currIndex < 0)
currIndex = choices.Length - 1;
if (currIndex >= choices.Length)
currIndex = 0;
renderer.sprite = choices(currIndex);
}
}

Change this
renderer.sprite = choices(currIndex);
to this:
renderer.sprite = choices[currIndex]; // use square brackets not parenthesis

Related

How to fix inventory error in unity 2021.3.13f1

EDITED MORE SCRIPTS SHOWN!
I'm making an inventory system from This YouTube Video and I can't seem to get it to work.
the error1:
Assets\Scripts\InventoryScripts\InventorySystem.cs(31,33): error CS1579: foreach statement cannot operate on variables of type 'InventorySlot' because 'InventorySlot' does not contain a public instance or extension definition for 'GetEnumerator'
The error2:
Assets\Scripts\InventoryScripts\InventorySystem.cs(55,19): error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List' to 'InventorySlot'
And my code:
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Events;
[System.Serializable]
public class InventorySystem
{
[SerializeField] private List<InventorySlot> inventorySlots;
public int InventorySize => InventorySlots.Count;
public List<InventorySlot> InventorySlots => inventorySlots;
public UnityAction<InventorySlot> OnInventorySlotChanged;
public InventorySystem(int size)
{
inventorySlots = new List<InventorySlot>(size);
for(int i = 0; i < size; i++)
{
inventorySlots.Add(new InventorySlot());
}
}
public bool AddToInventory(InventoryItemData itemToAdd, int amountToAdd)
{
if(ContainsItem(itemToAdd, out InventorySlot invSlot))
{
foreach(var slot in invSlot)
{
if(slot.RoomLeftInStack(amountToAdd))
{
slot.AddToStack(amountToAdd);
OnInventorySlotChanged?.Invoke(invSlot);
return true;
}
}
}
if(HasFreeSlot(out InventorySlot freeSlot))
{
freeSlot.UpdateInvSlot(itemToAdd, amountToAdd);
OnInventorySlotChanged?.Invoke(freeSlot);
return true;
}
return false;
}
public bool ContainsItem(InventoryItemData itemToAdd, out InventorySlot invSlot)
{
invSlot = InventorySlots.Where(i => i.ItemData == itemToAdd).ToList();
return invSlot == null ? false : true;
}
public bool HasFreeSlot(out InventorySlot freeSlot)
{
freeSlot = InventorySlots.FirstOrDefault(i => i.ItemData == null);
return freeSlot == null ? false : true;
}
}
Holder script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
[System.Serializable]
public class InventoryHolder : MonoBehaviour
{
[SerializeField] private int inventorySize;
[SerializeField] protected InventorySystem inventorySystem;
public InventorySystem InventorySystem => inventorySystem;
public static UnityAction<InventorySystem> OnDynamicInventoryDisplayRequested;
private void Awake()
{
inventorySystem = new InventorySystem(inventorySize);
}
}
Slot Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class InventorySlot
{
[SerializeField] private InventoryItemData itemData;
[SerializeField] private int stackSize;
public InventoryItemData ItemData => itemData;
public int StackSize => stackSize;
public InventorySlot(InventoryItemData source, int amount)
{
itemData = source;
stackSize = amount;
}
public InventorySlot()
{
ClearSlot();
}
public bool RoomLeftInStack(int amountToAdd, out int amountRemaining)
{
amountRemaining = ItemData.maxStackSize - stackSize;
return RoomLeftInStack(amountToAdd);
}
public bool RoomLeftInStack(int amountToAdd)
{
if(stackSize + amountToAdd <= itemData.maxStackSize) return true;
else return false;
}
public void ClearSlot()
{
itemData = null;
stackSize = -1;
}
public void UpdateInvSlot(InventoryItemData data, int amount)
{
itemData = data;
stackSize = amount;
}
public void AddToStack(int amount)
{
stackSize += amount;
}
public void RemoveFromStack(int amount)
{
stackSize -= amount;
}
}
I'm just trying to remove these errors so I can test it.
The Where method of the List class returns a List rather than a single InventorySlot object.
You can rewrite the function 'ContainsItem' like this:
public bool ContainsItem(InventoryItemData itemToAdd, out InventorySlot invSlot)
{
invSlot = InventorySlots.FirstOrDefault(i => i.ItemData == itemToAdd);
return invSlot == null ? false : true;
}

cannot convert from 'System.Collections.Generic.Queue<System.Collections.Generic.KeyValuePair<PotionCraft.PotionRecipe.Ingredient, uint>>'

I have this error when i try to complile this C# code on my Unity:
Assets\Scripts\Cauldron.cs(50,57): error CS1503: Argument 1: cannot convert from 'System.Collections.Generic.Queue<System.Collections.Generic.KeyValuePair<PotionCraft.PotionRecipe.Ingredient, uint>>' to 'System.Collections.Generic.Queue<System.Collections.Generic.KeyValuePair<Ingredient, uint>>'
This is the code
using System.Collections.Generic;
using UnityEngine;
namespace PotionCraft.Components
{
public interface IBrewingCauldron
{
public void AddIngredient(PotionRecipe.Ingredient ingredient);
public GameObject BrewPotion();
}
[RequireComponent(typeof(SphereCollider))]
[RequireComponent(typeof(Rigidbody))]
public class Cauldron : MonoBehaviour, IBrewingCauldron
{
public Dictionary<PotionRecipe.Ingredient, uint> Ingredients { get; private set; } = new();
[SerializeField] private SphereCollider cauldronCollider;
private readonly PotionBrewer _potionBrewer = new();
private uint _numberOfIngredients;
private void Awake()
{
cauldronCollider ??= GetComponent<SphereCollider>();
// Set the collider as trigger to interact with ingredients GameObject
cauldronCollider.isTrigger = true;
}
public void AddIngredient(PotionRecipe.Ingredient ingredient)
{
// Keep track of the number of ingredients added
_numberOfIngredients++;
if (!Ingredients.ContainsKey(ingredient))
{
Ingredients[ingredient] = 1;
}
else
{
Ingredients[ingredient]++;
}
}
public GameObject BrewPotion()
{
var ingredientQueue = new Queue<KeyValuePair<PotionRecipe.Ingredient, uint>>(Ingredients);
var potionObject = _potionBrewer.MakePotion(ingredientQueue, _numberOfIngredients);
if (potionObject is not null)
{
Debug.Log($"We made a {potionObject.name} !");
potionObject.transform.position = transform.position;
}
else
{
Debug.Log("We failed to make any potion !!!");
}
Ingredients = new Dictionary<PotionRecipe.Ingredient, uint>();
_numberOfIngredients = 0;
return potionObject;
}
}
}
Edit: This is another code might be related to the problem
using UnityEngine;
namespace PotionCraft.Components
{
public class Ingredients : MonoBehaviour
{
[SerializeField] private GameObject cauldronGameObject;
[SerializeField] private PotionRecipe.Ingredient ingredient;
private SphereCollider _cauldronCollider;
private IBrewingCauldron _cauldron;
private void Awake()
{
if (cauldronGameObject is not null)
{
_cauldron = cauldronGameObject.GetComponent<IBrewingCauldron>();
if (_cauldron is not null) return;
}
var ingredientObject = gameObject;
ingredientObject.name += " [IN ERROR]";
ingredientObject.SetActive(false);
throw new MissingComponentException($"{ingredientObject.name} is missing the cauldron gameobject");
}
private void Start()
{
_cauldronCollider = cauldronGameObject.GetComponent<SphereCollider>();
gameObject.name = ingredient.ToString();
}
private void OnTriggerEnter(Collider other)
{
if (other != _cauldronCollider) return;
_cauldron.AddIngredient(ingredient);
Destroy(gameObject);
}
}
}
So what am I doing wrong here?
The PotionBrewer.MakePotion method accepts an argument of type Queue<KeyValuePair<Ingredient, uint>>.
You are trying to pass it an argument of type Queue<KeyValuePair<PotionCraft.PotionRecipe.Ingredient, uint>> instead.
If PotionBrewer.MakePotion is supposed to accept an argument of the latter type, you might need to add this using alias to your PotionBrewer class:
using Ingredient = PotionCraft.PotionRecipe.Ingredient;

Unity Editor Scripting: How to create a custom Popup to select a especific class

I would like to create a custom inspector with a dropdown menu. I want to do this to select between multiple classes that inherit from a base interface.
So I've created a script that overrides the default editor for the class CreatureSO that extends ScriptableObject. I know that there are two ways to access the properties of the class Creature with the target variable and with serializedObject. I want to use the serializedObject method because of
the features that it includes.
My current code:
CreatureSO.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Creature", menuName = "Custom/Creature/Instance")]
public class CreatureSO : ScriptableObject
{
public Sprite sprite;
public Vector3 position;
public Vector2 size;
public CreatureStats stats;
//[HideInInspector]
[SerializeReference] public IEngine engine; //this is the property
}
IEngine.cs
using System;
using UnityEngine;
using UnityEngine.InputSystem;
public interface IEngine
{
}
PlayerEngine.cs
using System;
using UnityEngine;
using UnityEngine.InputSystem;
[System.Serializable]
public class PlayerEngine: IEngine
{
private Creature _creature;
private Keyboard keyboard;
private bool inputCtrl;
public void Start(Creature creature)
{
keyboard = Keyboard.current;
_creature = creature;
}
private void FixedUpdate()
{
//Movement
_creature.isMovingX = keyboard.aKey.isPressed ^ keyboard.dKey.isPressed;
_creature.inputX = !_creature.isMovingX ? 0 : keyboard.aKey.isPressed ? -1 : 1;
_creature.isWalking = _creature.isMovingX && _creature.isGrounded && !inputCtrl;
_creature.isRunning = _creature.isMovingX && _creature.isGrounded && inputCtrl;
_creature.isDashing = keyboard.sKey.isPressed;
_creature.direction = _creature.inputX != 0 ? (int)_creature.inputX : _creature.direction;
//wall;
_creature.isWalled = _creature.controller.collisionInfo.left || _creature.controller.collisionInfo.right;
_creature.isFullWalled = _creature.controller.collisionInfo.fullLeft || _creature.controller.collisionInfo.fullRight;
//Jump
_creature.isJumping = keyboard.spaceKey.isPressed;
//attack
_creature.isAttacking = false;
//if (_creature.stats.canAttack)
{
_creature.isAttacking = keyboard.wKey.isPressed;
// _creature.stats.canAttack = false;
}
if (!keyboard.wKey.isPressed)
//_creature.stats.canAttack = true;
//running
inputCtrl = keyboard.leftCtrlKey.isPressed;
//vapor
//_creature.stats.hasVapor = _creature.stats.vaporCount > 0;
//Habilities
//dashHab.FixedUpdate(this);
}
}
EnemyEngine
public class EnemyEngine: IEngine
{
private Creature _creature;
public void Init(Creature creature)
{
_creature = creature;
}
public void Update()
{
//Currently this engine does nothing
//In the future it will detect his surroundings and command some actions to the Creature.
//for example: (pseudocode)
// if( ! Raycast( front ) ) {
//
// Creature.move.forward();
//}
}
}
CreatureSO.cs
using UnityEngine;
using UnityEditor;
enum EngineType { Player, Enemy };
[CustomEditor(typeof(CreatureSO))]
public class CreatureSOEditor : Editor
{
EngineType engineType;
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
serializedObject.Update();
SerializedProperty engine = serializedObject.FindProperty("engine");
engineType = (EngineType)EditorGUILayout.EnumPopup("Engine", engineType);
engine.objectReferenceValue = SelectEngine();
serializedObject.ApplyModifiedProperties();
}
public IEngine SelectEngine()
{
switch(engineType)
{
case EngineType.Player:
PlayerEngine playerEngine = new PlayerEngine();
return playerEngine;
default:
return null;
}
}
}
Creature.cs
using System;
using System.Collections.Generic;
using UnityEngine;
public class Creature: MonoBehaviour
{
public CreatureSO instance;
public IHability[] _actions;
public IEngine engine;
//public ItemPickup itemToPick;
//public GameState gameState;
//public Inventory inventory;
[HideInInspector] private GameObject _actionsGO;
[HideInInspector] private CreatureStats stats;
[HideInInspector] public BoxCollider2D boxCollider;
[HideInInspector] public Controller2D controller;
[HideInInspector] public Animator animator;
[HideInInspector] public GameObject spriteObject;
[HideInInspector] public SpriteRenderer spriteRenderer;
public Collider2D attackCollider;
public Collider2D bodyCollider;
public Vector2 velocity;
public int direction;
public float inputX;
public bool isMovingX;
public bool isWalking;
public bool isRunning;
public bool isJumping;
public bool isAttacking;
public bool isGrounded;
public bool isWalled;
public bool isFullWalled;
public bool isDashing;
public bool canPickup;
private ContactFilter2D contactFilter;
public void Start()
{
boxCollider = gameObject.AddComponent<BoxCollider2D>();
boxCollider.size = instance.size;
controller = Controller2D.Attach(gameObject, boxCollider);
spriteObject = new GameObject();
spriteObject.transform.parent = gameObject.transform;
spriteObject.transform.localPosition = new Vector3();
spriteObject.transform.localScale = new Vector3(instance.size.x/10, instance.size.y/10);
spriteRenderer = spriteObject.AddComponent(typeof(SpriteRenderer)) as SpriteRenderer;
spriteRenderer.sprite = instance.sprite;
spriteRenderer.size = instance.size;
animator = gameObject.AddComponent(typeof(Animator)) as Animator;
stats = instance.stats;
_actionsGO = new GameObject("Actions");
_actionsGO.transform.SetParent(this.transform);
ScriptableObject[] actionStats = stats.actionStats;
_actions = new IHability[actionStats.Length];
IHability currentAction;
for (int i =0; i < actionStats.Length; i++)
{
switch (actionStats[i])
{
case WalkingStats stats:
currentAction = _actionsGO.AddComponent<WalkingHab>();
((WalkingHab)currentAction).Init(this, (WalkingStats)actionStats[i]);
break;
case FallingStats stats:
currentAction = _actionsGO.AddComponent<FallingHab>();
((FallingHab)currentAction).Init(this, (FallingStats)actionStats[i]);
break;
case JumpingStats stats:
currentAction = _actionsGO.AddComponent<JumpHab>();
((JumpHab)currentAction).Init(this, (JumpingStats)actionStats[i]);
break;
case AirMovingStats stats:
currentAction = _actionsGO.AddComponent<AirMovingHab>();
((AirMovingHab)currentAction).Init(this, (AirMovingStats)actionStats[i]);
break;
case DashingStats stats:
currentAction = _actionsGO.AddComponent<DashingHab>();
((DashingHab)currentAction).Init(this, (DashingStats)actionStats[i]);
break;
case GrabbingStats stats:
currentAction = _actionsGO.AddComponent<GrabbingHab>();
((GrabbingHab)currentAction).Init(this, (GrabbingStats)actionStats[i]);
break;
case JumpDiagonalStats stats:
currentAction = _actionsGO.AddComponent<JumpDiagonalHab>();
((JumpDiagonalHab)currentAction).Init(this, (JumpDiagonalStats)actionStats[i]);
break;
case AttackStats stats:
currentAction = _actionsGO.AddComponent<AttackHab>();
((AttackHab)currentAction).Init(this, (AttackStats)actionStats[i]);
break;
default:
return;
}
_actions[i] = currentAction;
}
direction = 1;
//this.health = stats.maxHealth;
contactFilter = new ContactFilter2D();
contactFilter.useLayerMask = true;
//contactFilter.layerMask = stats.attackLayerMask;
}
public void Update()
{
}
public void FixedUpdate()
{
isGrounded = controller.collisionInfo.below;
if (isGrounded || controller.collisionInfo.above) velocity.y = Mathf.Sign(velocity.y) * 0.1f;
for (int i = 0; i < _actions.Length; i++)
{
if (!_actions[i].CanExecute()) continue;
_actions[i].Execute();
}
if (this.direction != Mathf.Sign(this.transform.localScale.x))
{
this.transform.localScale = Vector3.Scale(this.transform.localScale, new Vector3(-1, 1, 1));
}
this.transform.Translate(this.controller.Move(velocity * Time.deltaTime));
velocity.x = 0;
}
//public abstract void pickupAction(ItemPickup item);
public void setVelocityX(float velocityX)
{
this.velocity.x = velocityX;
}
public void setVelocityY(float velocityY)
{
this.velocity.y = velocityY;
}
public void addVelocityY(float velocityY)
{
this.velocity.y += velocityY;
}
public void addVelocityX(float velocityX)
{
//if (velocity.x < stats.speedXMax)
this.velocity.x += velocityX;
}
public void attack()
{
List<Collider2D> enemies = new List<Collider2D>();
Physics2D.OverlapCollider(this.attackCollider, contactFilter, enemies);
foreach (Collider2D enemy in enemies)
{
//Enemy a = enemy.gameObject.GetComponent<Enemy>();
//a.damage(10);
}
}
}
What I'm trying to achieve with these classes is to create a generic object Creature that I can easily define with one scriptableObject. So when I press the play button all GameObjects with a Creature component will use some CreatureSO from a list. The engine is the brain of the Creature and defines what the Creature will do. I want the Creatures to have different behaviors and that's why I need different engines.
This is my code so far. My problem is that I can't correctly cast any IEngine object to the serializedProperty.
Unity shows the following error:
Assets\3_Game\Core\ScriptableObjects\Editor\CreatureSOEditor.cs(18,39): error CS0266:
Cannot implicitly convert type 'IEngine' to 'UnityEngine.Object'.
An explicit conversion exists (are you missing a cast?)
using (object) cast also gives an error. Any suggestion??
Also if there are any resources for learning editor scripting? not the unity learn platform.
Thanks.
This is not (yet) a complete answer since we would need to know what exactly PlayerEngine and EnemyEngine look like.
With the current information though, in
engine.objectReferenceValue = SelectEngine();
SerializedProperty.objectReferenceValue as the name suggests expects a reference of type UnityEngine.Object the mother class of e.g. GameObject, Component, ScriptableObject and basically every built-in asset type.
It is not to be confused with System.Object which the alias object stands for in c#!
None of your classes implementing IEngine does inherit from UnityEngine.Object either.
And anyway in general an interface does not inherit from either one.
And even if it would, you most probably wouldn't want to create a new instance each and every time the Inspector serialization is done.
For giving possible solutions to this issue we would need to know more about what exactly the differences between your IEngine implementations are.

CustomEditor Unity: chosing enums at once + showing array

I'm trying to do a thing on Unity and got caught up;
This may be a bit complex, but see if you can help me:
What I got and what I want (image)
This is the script I got now
public class ClasseTest : MonoBehaviour{
public enum TiposDeMissoes
{
TipoMatarGente,
TipoPegarItem,
};
public TiposDeMissoes TiposMissoes;
[Serializable]
public class MatarGente
{
public int IDmissao;
public GameObject[] ObjetosAtivarPraMissao;
public GameObject[] Checkpoints;
public GameObject[] InimigosPraMatar;
}
[Serializable]
public class PegarItem
{
public int IDmissao;
public GameObject[] ObjetosAtivarPraMissao;
public GameObject[] Checkpoints;
public GameObject[] ItemsEntregar;
}
[Serializable]
public class Missoes
{
public TiposDeMissoes TiposMissoes;
public PegarItem[] PegarItem;
public MatarGente[] MatarGente;
}
public Missoes[] MissoesJogasso;
}
I only what to show the class PegarItem if PegarItem was chosen in the enum.
There's only PegarItem and MatarGente right now, but there will be more classes.
I did some research and find out Im supposed to use the OnInspectorGUI if I want to be that specific (if there's other way round, pls tell me)
I got 0 experience on CustomEditor so what I got so far is
[CustomEditor(typeof(ClasseTest))]
public class TestCustomInspector : Editor
{
public int numMissoes;
public override void OnInspectorGUI()
{
ClasseTest script = (ClasseTest)target;
numMissoes = EditorGUILayout.IntField("Numero de Missoes", numMissoes);
EditorGUILayout.LabelField("Editante");
var serializedObject = new SerializedObject(target);
var property = serializedObject.FindProperty("MissoesJogasso");
serializedObject.Update();
EditorGUILayout.PropertyField(property, true);
serializedObject.ApplyModifiedProperties();
for (int i = 0; i < numMissoes; i++)
{
script.TiposMissoes = (ClasseTest.TiposDeMissoes)EditorGUILayout.EnumPopup("TIPO DE MISSAO", script.TiposMissoes);
if (script.TiposMissoes == ClasseTest.TiposDeMissoes.TipoMatarGente)
{
script.TiposMissoes = (ClasseTest.TiposDeMissoes)EditorGUILayout.EnumPopup("Matar Gentes", script.TiposMissoes);
}
if (script.TiposMissoes == ClasseTest.TiposDeMissoes.TipoPegarItem)
{
script.TiposMissoes = (ClasseTest.TiposDeMissoes)EditorGUILayout.EnumPopup("Pegar Item", script.TiposMissoes);
}
}
}
}
And that means, in the editor:
If I change the value of one enum, all the others copy it (image)
And That's exactly what I do not want.
And y'all, keep in mind when the editor chooses MatarGente or PegarItem I'd like to show all those possible variables that these classes hold. That includes arrays with non-specific lengths.
And also, if there's 2 'MatarGente' I'd like to be able to fill those arrays with different objects and retrieve that information later to use it somewhere else.
Tried to understand what you were doing. Your mistake was not modifying the array elements and few other issues.
This is your new ClasseTest:
using System;
using UnityEngine;
using System.Collections.Generic;
public class ClasseTest : MonoBehaviour
{
public enum TiposDeMissoes
{
TipoMatarGente,
TipoPegarItem,
}
[Serializable]
public class MatarGente
{
public int IDmissao;
public GameObject[] ObjetosAtivarPraMissao;
public GameObject[] Checkpoints;
public GameObject[] InimigosPraMatar;
}
[Serializable]
public class PegarItem
{
public int IDmissao;
public GameObject[] ObjetosAtivarPraMissao;
public GameObject[] Checkpoints;
public GameObject[] ItemsEntregar;
}
[Serializable]
public class Missoes
{
public TiposDeMissoes TiposMissoes;
public PegarItem[] PegarItem;
public MatarGente[] MatarGente;
}
public List<Missoes> MissoesJogasso;
public int NumMissoes;
}
This is your new TestCustomInspector class:
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
[CustomEditor(typeof(ClasseTest))]
public class TestCustomInspector : Editor
{
public override void OnInspectorGUI()
{
ClasseTest script = (ClasseTest)target;
script.NumMissoes = EditorGUILayout.IntField("Numero de Missoes", script.NumMissoes);
// Ensure it cannot go into negative numbers.
if (script.NumMissoes < 0) script.NumMissoes = 0;
// Create the list if it does not exist.
if(script.MissoesJogasso == null) script.MissoesJogasso = new List<ClasseTest.Missoes>();
// numMissoes being greater than the current count means we need to extend the list.
if (script.NumMissoes > script.MissoesJogasso.Count)
{
for (int i = 0; i < script.NumMissoes; i++)
{
script.MissoesJogasso.Add(new ClasseTest.Missoes());
}
}
// numMissoes being less than the current count means we need to decrease the list.
else if(script.NumMissoes < script.MissoesJogasso.Count)
{
int difference = script.MissoesJogasso.Count - script.NumMissoes;
// Remove the last element difference number of times.
for (int i = 0; i < difference; i++)
{
script.MissoesJogasso.RemoveAt(script.MissoesJogasso.Count - 1);
}
}
var serializedTarget = new SerializedObject(target);
for (int i = 0; i < script.MissoesJogasso.Count; i++)
{
var missoes = script.MissoesJogasso[i];
switch(missoes.TiposMissoes)
{
case ClasseTest.TiposDeMissoes.TipoMatarGente:
missoes.TiposMissoes = (ClasseTest.TiposDeMissoes)EditorGUILayout.EnumPopup("Matar Gentes", missoes.TiposMissoes);
DrawProperty(serializedTarget, string.Format("MissoesJogasso.Array.data[{0}].MatarGente", i));
break;
case ClasseTest.TiposDeMissoes.TipoPegarItem:
missoes.TiposMissoes = (ClasseTest.TiposDeMissoes)EditorGUILayout.EnumPopup("Pegar Item", missoes.TiposMissoes);
DrawProperty(serializedTarget, string.Format("MissoesJogasso.Array.data[{0}].PegarItem", i));
break;
}
}
}
private void DrawProperty(SerializedObject serializedObject, string propertyName)
{
var property = serializedObject.FindProperty(propertyName);
serializedObject.Update();
EditorGUILayout.PropertyField(property, true);
serializedObject.ApplyModifiedProperties();
}
}
In Unity:
Hope this works.

How do i fix Out of Range message i get in Unity

I have this code and I keep getting the error message
Argument is out of range
I have been following this tutorial and I have been following it exactly. I went back and checked everything but I am still getting the message.
Here is my code:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DialogSystem : MonoBehaviour {
public static DialogSystem Instance { get; set; }
public GameObject dialogPanel;
public string npcname;
public List<string> dialoglines = new List<string> ();
Button continueButton;
Text dialogText, nameText;
int dialogIndex;
// Use this for initialization
void Awake () {
continueButton = dialogPanel.transform.Find
("Continue").GetComponent<Button> ();
continueButton.onClick.AddListener (delegate { ContinueDialog(); });
dialogText = dialogPanel.transform.Find("Text").GetComponent<Text>();
nameText =
dialogPanel.transform.Find("Name").GetChild(0).GetComponent<Text>();
dialogPanel.SetActive(false);
if (Instance != null && Instance != this) {
Destroy (gameObject);
}
else
{
Instance = this;
}
}
public void addNewDialog(string[] lines, string npcname)
{
dialogIndex = 0;
dialoglines = new List<string>(lines.Length);
dialoglines.AddRange (lines);
this.npcname = npcname;
Debug.Log (dialoglines.Count);
CreatDialog ();
}
public void CreatDialog()
{
dialogText.text = dialoglines [dialogIndex];
nameText.text = npcname;
dialogPanel.SetActive (true);
}
public void ContinueDialog()
{
if (dialogIndex < dialoglines.Count - 1) {
dialogIndex++;
dialogText.text = dialoglines [dialogIndex];
}
else
{
dialogPanel.SetActive (false);
}
}
I have no idea and I am getting pretty far into my work and I am a new developer and I am struggling to figure this out on my own. Any help is appreciated.

Categories