Is it possible to show static fields in the Unity Editor? - c#

I wrote little script yesterday but it isn't working. (Serialize fields isn't showing in unity and few errors eg. I can't use reference to non-static member (serialize Field)). Can You help me please.
Eg.
using UnityEngine;
public class sExample : MonoBehaviour
{
[SerializeField] public static GameObject gameObj;
public void serializeUse()
{
//Do something with gameObj
}
}
public class serializeEx : NetworkBehaviour
{
public void Update()
{
If (!isLocalPlayer)
{
sExample.serializeUse()
}
}
}
Thanks alot

That should work.
I think that you can't use static, when you want to expose something to the Editor.
using UnityEngine;
[Serializable]
public class sExample : MonoBehaviour
{
[SerializeField] public GameObject gameObj;
public void serializeUse()
{
//Do something with gameObj
}
}
public class serializeEx : NetworkBehaviour
{
public void Update()
{
If (!isLocalPlayer)
{
sExample.serializeUse()
}
}
}
Edit:
Statics seem to work for JavaScript as mentioned in this post.
To make this work you'll have to switch to the debug view in the inspector.
Like in the image shown below:
Edit2:
The explanation what the Serializeable does is taken from the unity documentation.
The Serializable attribute lets you embed a class with sub properties
in the inspector.
You can use this to display variables in the inspector similar to how
a Vector3 shows up in the inspector. The name and a triangle to expand
its properties. To do this you need create a class that derives from
System.Object and give it the Serializable attribute. In JavaScript
the Serializable attribute is implicit and not necessary.
using UnityEngine;
[System.Serializable]
class Test : System.Object
{
public int p = 5;
public Color c = Color.white;
}

Related

Serialize a custom class in a custom inspector in Unity

I need to serialize a class in a custom inspector (using visually the Editor) like as doing in a Monobehaviour script like this:
[System.Serializable]
public class CustomClass
{
int myInt
}
public class OtherClass : MonoBehaviour
{
[SerializeField] CustomClass customClass;
}
which gives this result:
result wanted and given using the code above, where DamageEffect = CustomClass and Damage = myInt
In my custom editor, I'd like something like this:
[CustomEditor(typeof(CardObject))]
class AnotherClassEditor : Editor
{
public override void OnInspectorGUI()
{
[SerializeField] CustomClass customclass;
}
}
but, as expected, it points out an error.
I also tried with EditorGUILayout.ObjectField() but I haven't been able to, I'm not so experienced so please try to keep the answers simple.
Actually, I need this serialization to happen only when an enum is equal to a certain value, the overall script is something like this:
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
[CreateAssetMenu(fileName = "Card", menuName = "CardObject")]
public class CardObject : ScriptableObject
{
public List<CardEffectType> effectsTypes;
//other...
[HideInInspector] public List<CardEffect> effects;
//other...
}
#if UNITY_EDITOR
[CustomEditor(typeof(CardObject))]
class CardObjectEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
CardObject cardObject = (CardObject)target;
foreach(CardEffectType effectType in cardObject.effectsTypes)
{
switch (effectType)
{
case CardEffectType.DamageEffect:
{
//!!!
}
}
}
}
}
#endif
public enum CardEffectType
{
DamageEffect, //other...
}
I found some workarounds but the result is not as when a class is serialized in a Monobehaviour.
When you just want to show something like how Unity would, you can use EditorGUILayout.PropertyField(), but it asks for a SerializedProperty, what you need to get from the SerializedObject, not from the actual target. Something like this:
[CustomEditor(typeof(MyType))]
public class MyTypeEditor : Editor
{
private SerializedProperty _variableIWantToShow;
private void OnEnable()
{
_variableIWantToShow = serializedObject.FindProperty("<name-of-the-variable>");
}
public override void OnInspectorGUI()
{
// ...
if (ShowVariable) EditorGUILayout.PropertyField(_variableIWantToShow);
// ...
}
}
You can manage collections (array, list, etc.) as SerializedProperty, but it adds some complexity.
https://docs.unity3d.com/ScriptReference/SerializedProperty.html
https://answers.unity.com/questions/682932/using-generic-list-with-serializedproperty-inspect.html
Just make your int myInt public, or add [SerializeField] attribute to it - inspector is only designed to work with serialisable fields (public fields are serialised by default in unity editor), currently your myInt is private hence only visible from within
As mentioned in an answer by h4i, proper way to display objects in the editor is using SerializedProperty, casting 'target' seems like a good idea at start but is only useful if you want to call methods on the object, it will fail in several other cases.
What you may want to consider is declaring a PropertyDrawer while Editors service a single monobehaviour type, a PropertyDrawer handles displaying every instance of a serializable class, and will be used every time a default editor uses a PropertyField internally. This will probably match your use case better

cannot access non static method "GetComponent" in static context, despite me not declaring the class as static

I am currently working on making a class accessible from other scripts. Below is what I have coded.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(BoxCollider2D))]
// Start is called before the first frame update
public class _move
{
private float _sizex;
private float _sizey;
public _move(float sizx, float sizy....etc)
{
_sizex = sizx;
_sizey = sizy;
}
public void regularmove(float sizex, float sizey...etc)
{
GameObject _player;
_player = GameObject.GetComponent<GameObject>();
BoxCollider2D bc2d;
bc2d = _player.GetComponent <BoxCollider2D>();
bc2d.offset = new Vector2(locationx + 1, locationy);
}
}
however, when I try to compile it, it gives me an error.
cannot access non-static method"GetComponent"
on this line of code
_player = GameObject.GetComponent<GameObject>();
I do not know why this is happening because I have not declared the class as static, and do not really know the properties of GetComponent that well. Can someone tell me what is happening and how I can solve this?
Also, when I change
GameObject _player;
to
public GameObject player;
the scripts below suddenly cease to work, giving me errors like
cannot resolve symbol _player
what exactly is happening here?
Thanks in advance!
Whatever script creating the instance of the _move class (This is bad naming btw, it should be Move) should also pass its gameObject to the constructor.
// attributes here are not valid if your class is not a MonoBehaviour
public class Move
{
GameObject m_object;
public Move(GameObject obj, ...)
{
m_object = obj;
}
}
if your class is meant to be a MonoBehaviour component, then it has a GameObject member already and you can use the attributes:
[RequireComponent(typeof(BoxCollider2D),typeof(Rigidbody2D))]
// Start is called before the first frame update
public class Move : MonoBehaviour
{
void Start()
{
Debug.Log(gameObject.name);
}
}

Calling an Object from another Script

This might be a super simple question, but for some reason I can't get it to work:
I have two scripts, both attached to the same GameObject.
One script has a dictionary:
public class RPG_Implementierung : MonoBehaviour
{
public Dictionary<string, string> StoryText = new Dictionary<string, string>();
void Start()
{
StoryText.Add("1", "This is the first Entry");
}
}
The other script wants to call that Dictionary. The method SendMessageToChat` is defined in this script and works well as long as it's not referencing the other script.
The first thing I tried didn't work, I get the Error:
CS0120 An object reference is required for the non-static field, method, or property
public class GameManager : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Y))
{
SendMessageToChat(RPG_Implementierung.StoryText["1"]);
}
}
}
I
this also doesn't work, it gives me the Error
CS0119 'RPG_Implementierung' is a type, which is not valid in the given context
public class GameManager : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Y))
{
SendMessageToChat(GetComponent(RPG_Implementierung).StoryText["1"]);
}
}
}
Can someone please tell me what I did wrong? In standard C# all I would have to do is to set the other class to public and then I can reference it and access it's objects, why doesn't this work in Unity?
To reference another component on a GameObject, you will need to grab that reference either by serializing the field in the inspector (Making it public or using the attribute [SerializeField].
I am not sure how many places you want to eventually call the method you are trying to invoke, but if it is from a bunch of different places, you might want to consider the Singleton pattern.
To quickly fix your current issue, on your GameManager.cs, do one of these two things:
public class GameManager : MonoBehaviour
{
[SerializeField] private RPG_Implementierung rpgImplement = null;
// OR
public RPG_Implementierung rpgImplement;
void Update()
{
if (Input.GetKeyDown(KeyCode.Y))
{
SendMessageToChat(rpgImplement.StoryText["1"]);
}
}
}
Edit: If you want to use the GetComponent in the Update here is how you would call it. I would advise against this as calling a GetComponent in an Update can be quite costly for performance if called frequently. It is better to store the reference to later use.
public class GameManager : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Y))
{
SendMessageToChat(GetComponent<RPG_Implementierung>().StoryText["1"]);
}
}
}

Mimicking custom function

I have defined some custom functions in the following script and attached with my gameobject. I want to declare my function OnReticleEnter() to mimick OnPointerEnter(). Is it possible? I want this because I want to access my function OnReticleEnter() in the inspector so that I can define multiple actions like EventTrigger's Point Enter, Exit etc.
Is it possible to make the function OnReticleEnter() to behave as OnPointerEnter() programmatically?
using UnityEngine;
using System.Collections;
public class MyObject : MonoBehaviour
{
// Custom reticle events
public GameObject gOBJ;
public void OnReticleEnter()
{
gOBJ.SetActive(true);
}
public void OnReticleExit()
{
gOBJ.SetActive(false);
}
public void OnReticleHover()
{
gOBJ.SetActive(true);
}
}
You need to inherit the interfaces for the pointerEnter and PointerExit events in your class to be able to implement them. Your code might look something like this :
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
public class MyObject : MonoBehaviour,IPointerEnterHandler, IPointerExitHandler
{
// Custom reticle events
public GameObject gOBJ;
public void OnPointerEnter(PointerEventData eventData){
gOBJ.SetActive(true);
}
public void OnPointerExit(PointerEventData eventData){
gOBJ.SetActive(false);
}
}

Access a non-MonoBehaviour script from another script (Unity)

I'm working on a Unity project and i would like to access a non MonoBehaviour script from another script.
I can't use GetComponent cause the script isn't MonoBehabiour, is there a solution ?
Here is some code to help you understand :
public class SomeClass {
public static float coolVar = 1.0f;
private string someVar; // EDIT : I need to access this var too and AnotherClass.someVar won't work obviously
public class AnotherClass {
// i want to be able to access coolVar and change her value
// i know i can do SomeClass.coolVar but i was looking for another way close to a GetComponent approach
My SomeClass class is full of static var i need to edit, i didn't implemented those variables and i can't modify them (i know it's bad practices).
Maybe the reflection is the best way :
typeof(SomeClasse).GetField(name).SetValue(null, value);
you only need to include the script with the not MonoBehaviour class inside the Assets path of the project and you will be able to use it inside other behaviour class.
Take care of use only .NET 2.0 specifications in the external class and if u have used a namespace on it add the using in the behaviour script.
#External class
namespace DefNamespace
{
public class ModelList
{
private static List<GameObject> models;
private ModelList ()
{
}
public static List<GameObject> Models{
get{
if(models == null) models= new List<GameObject>();
return models;
}set{
models=value;
}
}
}
}
And then in a MonoBehaviour or another class:
#Behaviour
using DefNamespace;
public class DefBehaviour : MonoBehaviour
{
Start(){
GameObject go=ModelList.Models[0];
}
}

Categories

Resources