0

I'm trying to create a lives system of five hearts in a game I'm making, so to do that I created a life tracked script:

using System.Collections;
using System.Collections.Generic;
using Microsoft.Unity.VisualStudio.Editor;
using UnityEngine;

public class LifeTracker : MonoBehaviour
{
  public int lives;

  public Image[] hearts;
  public Sprite heartImage;


}

However, when I go to Unity, the inspector will only show the int and Sprite:

This is what I see.

I've tried rewriting and reloading the script, but nothing's worked. I tried changing it to "public Image[] hearts = new Image[5];" but have had no change.

Where am I going wrong? Does Unity not allow arrays in the inspector anymore? I'm new to Unity, but I'm not that new, and everywhere I look it says that this should work. Am I missing something obvious?

2 Answers 2

4

I think you want to reference UnityEngine.UI.Image, but there is a line using Microsoft.Unity.VisualStudio.Editor; among the using directives, so you actually referenced the wrong class: Microsoft.Unity.VisualStudio.Editor.Image.

The solution is:

//using Microsoft.Unity.VisualStudio.Editor;
using UnityEngine.UI;

Tip: The most likely reason for this issue is that Visual Studio will default prompt for unimported types, and you lack attention. You can turn off this feature. Check this question: Stop Visual Studio from adding using statements (Visual Studio 2022 edition)

Sign up to request clarification or add additional context in comments.

Comments

-2

Test it

SerializedProperty hearts;


private void OnEnable()
{
hearts = serializedObject.FindProperty("hearts");
}

private void OnInspectorGUI ()
{
serializedObject.Update();
  EditorGUILayout.PropertyField(hearts, true);
  serializedObject.ApplyModifiedProperties();}

And please check the below link:

Unity Editor Gui Layoit

Alternative solution:

private void OnInspectorGUI ()
{
 serializedObject.Update();

hearts.isExpanded = EditorGUILayout.Foldout(hearts.isExpanded, hearts.name);
if(hearts.isExpanded)
{
    EditorGUI.indentLevel++;

    // The field for item count
    hearts.arraySize = EditorGUILayout.IntField("size", hearts.arraySize);

    // draw item fields
    for(var i = 0; i< hearts.arraySize; i++)
    {
        var item = hearts.GetArrayElementAtIndex(i);
        EditorGUILayout.PropertyField(item, new GUIContent($"Element {i}");
    }

    EditorGUI.indentLevel--;
}
serializedObject.ApplyModifiedProperties();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.