I have a game object and I'm generating a component for that object by
var arcGISMapViewComponent = gameObject.AddComponent<ArcGISMapViewComponent>();
under the Void Start()
However, I have another class that is
public void ReadStringInput(string s)
I also need to show there the existence of arcGISMapViewComponent but since it's not generated yet in the beginning I'm getting an error which is
'arcGISMapViewComponent' could not be found how can I solve this?
You can use Awake() {} to make sure some code (component creation in your case) is called before other Start code. If your different class is not a MonoBehaviour then you should create an event and Invoke it notifying that component was created and from your different class subscribe on that event.
Related
So I was looking into implementing the new Unity input system into my game by reworking my code in my PlayerController script and got stuck pretty early on.
Here is the code that causes issues:
private PlayerInput playerInputController;
private void Awake()
{
playerInputController = new PlayerInput();
}
A green scribbly line appears under the 'Awake()' bit.
The code itself actually works, but it causes a lof of other issues, which makes a bunch of error messages appear saying:
NullReferenceException: Object reference not set to an instance of an object
The error messages all lead to places where I've used lines of code like this one in other scripts, to get variables and methods from my PlayerController script:
if (PlayerController.instance.isGroundedPhys)
Lastly, here's my singleton script, since it's likely relevant, as it's connected to my PlayerController script and allows it to be accessible from other scripts:
using UnityEngine;
public class Singleton<Instance> : MonoBehaviour where Instance : Singleton<Instance>
{
public static Instance instance;
public virtual void Awake()
{
if (!instance)
{
instance = this as Instance;
}
else
{
Destroy(gameObject);
}
}
}
This bit is at the top of my PlayerController script to make it accessible from other scripts:
public class PlayerController : Singleton<PlayerController>
{
I've been looking around and can't find anybody talking about similar issues. I think it's related to my singleton script, but I can't figure it out. :[
[Edit]:
I just found out it also gives this warning in the Unity console:
warning CS0114: 'PlayerController.Awake()' hides inherited member 'Singleton<PlayerController>.Awake()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
PlayerInput is a MonoBehaviour!
No seriously, this is "Not Allowed" and you should actually give you an according warning in the console.
A MonoBehaviour "can"/should only exist attached to an according GameObject and always be created by the underlying c++ framework. It's a c# thing that Unity can't fully prevent you from using new to create one.
The only valid way of creating an instance of a MonoBehaviour are
Instantiate a prefab that has the component attached
use AddComponent on an existing GameObject
use the constructor of GameObject and pass in the according component type(s)
Or you probably rather want to use e.g. GetComponent or FindObjectOfType in order to get a reference to an already existing instance of PlayerInput.
And then the other warning means you implemented
public void Awake()
{
// ...
}
or similar in your PlayerController class. The warning already tells you exactly what to rather do:
// Use "override" in order to not hide the already existing implementation
// of "Awake" in the base class
public override void Awake()
{
// Make sure the base class behavior is executed
// this will initialize the Singleton thing
base.Awake();
// ... your additional behavior here
}
I've seen a few places where Unity has the ability to "link" or otherwise require component dependencies that are added (at edit-time) and cannot be removed until the dependent component itself is removed.
Is there a way to use this behavior from custom scripts?
I know that you can create components at runtime using ObjectFactory, but it's expensive and doesn't solve the problem of being able to tweak parameters on the dependency components manually.
Yes - the [RequireComponent(typeof(SomeDependencyComponent))] attribute does exactly this.
For example:
[RequireComponent(typeof(AudioSync))]
public class BehaviorPlayer : MonoBehaviour
{
private AudioSync audioSync;
public void Start() {
audioSync = GetComponent<AudioSync>();
}
}
This automatically creates an AudioSync component (in this case, a custom script in my project) that is guaranteed to be present
at runtime, barring any programmatic removals.
It also shows up as an editor component on the game object that can be manually tweaked:
Further, if I try to remove the required AudioSync component, Unity spits out an error:
I have this unity event
[Serializable]
public class UnityEventString : UnityEvent<string>
{
}
Which gets used in this MonoBehaviour
public class EventListenerString : MonoBehaviour, IEventListener<string>
{
//some more code
public EventString Event;
public UnityEventString Response;
//Some more code
}
Problem is, it doesn't show this method in inspector as dynamic.
public void Show(string key)
{
_Show(Animator.StringToHash(key));
}
public void Hide(string key)
{
_Hide(Animator.StringToHash(key));
}
I used to use this pattern for my other events too, and they worked fine until today.
Currently, there are the right methods in the inspector, from earlier this week when i programmed. But today everything stopped working for that.
It also stopped working on a plain test object with a test MonoBehaviour with just one method.
But it still works with that one here
What happened here?
I think unity 2019.2.5 is bugged, going down to 2019.2.4 fixed this for me, all dynamic events came back.
You're attaching a function to run when the event is fired, that function is on a class, the class is a script attached to a gameobject, unity serializes this hooked method as follows GameObject Instance ID -> Script ID -> Method Name -> Parameters.
Now if you move your script to another game object, the serialization system doesn't find said script on the old game object anymore. so the deserialization breaks on the second step, and so does your hooked method.
Hope that makes sense.
I am trying to use the event system in Unity (the C# way), but I am having problems to implement it.
Most of the examples, show one class, where you define the handler; then you write in the same class, the function that match the signature of the handler, and you write the events as static
public class EventExample : MonoBehaviour
{
public delegate void ExampleEventHandler();
public static event ExampleEventHandler OneDayPassed;
public static void NextTurn()
{
// do stuff then send event
if (OneDayPassed != null)
OneDayPassed();
}
}
Then in another class, you subscribe to the events, creating a function that actually do something
public class EntityWatcher: MonoBehaviour
{
void Start()
{
EventExample.OneDayPassed += this.PrepareNextDay;
}
public void PrepareNextDay()
{
// Do other stuff that happen after the day is done
}
}
So far no problems, but I am not sure how do I design this, so any GameObject of a particular type, will subscribe to this event. For example, if you have a staff category of GO, that is working 8 to 6, and you instantiate them at runtime; should I subscribe in the main class of this category, or should I create a script that I attach to the Game Object prefab, that subscribe to the event?
The objective is that all the staff members that should do a 8 to 6 shift at the sport center, know when the "day is done" event fire up, but I don't want to subscribe every single prefab that I instantiate.
From my understanding, I should attach a script with the needed code on the prefab, but I can't find a practical example that show if that is in fact the way to do it.
You must use UnityEvent.
public UnityEvent whoa;
It is dead easy.
Make a script BigScript.cs
using UnityEngine;
using System.Collections;
using UnityEngine.Events;
public class BigScript:MonoBehaviour
{
[Header("Here's a cool event! Drag anything here!")]
public UnityEvent whoa;
}
Put it on a game object. Now look at it in the Inspector.
You will see the "whoa" event.
Simply drag your other scripts to there, to make something happen, on those other scripts, when "whoa" happens.
It's that simple. To call the event in BigScript, it is just
[Header("Here's a cool event! Drag anything here!")]
public UnityEvent whoa;
private void YourFunction()
{
whoa.Invoke();
}
In rare cases you may need to add a listener via code rather than simply dragging it in the Editor. This is trivial:
whoa.AddListener(ScreenMaybeChanged);
(Normally you should never have to do that. Simply drag to connect. I only mention this for completeness.)
That's all there is to it.
Be aware of out of date example code regarding this topic on the internet.
The above shows how to connect simple functions that have no argument.
If you do need an argument:
Here is an example where the function has ONE FLOAT argument:
Simply add THIS CODE at the top of the file:
[System.Serializable] public class _UnityEventFloat:UnityEvent<float> {}
then proceed as normal. It's that easy.
// ...
using UnityEngine.Events;
// add this magic line of code up top...
[System.Serializable] public class _UnityEventFloat:UnityEvent<float> {}
public class SomeThingHappens : MonoBehaviour
{
// now proceed as usual:
public _UnityEventFloat changedLength;
void ProcessValues(float v)
{
// ...
changedLength.Invoke(1.4455f);
}
}
When you drag from your other function to the Editor slot on this function:
Be certain to use the section - "Dynamic float".
(Confusingly your function will also be listed in the "Static Parameters" section! That is a huge gotchya in Unity!)
Don't worry too much about the number of subscribers if you are only talking about a few dozens. Yes, once you get into the hundreds or thousands it might be a good idea to optimize this, but even then. First rule of optimization: don't optimize.
So: just have every instance subscribe to the event and be done with it.
I'm currently working on an inventory system in Unity3D, and came upon a weird problem. I have created non-MonoBehaviour classes for my inventory system (in case that matters), so that I have an Inventory class which holds a list of Slot objects, which in turn holds a list of Item objects.
Then I added a component script to my "HudInventoryPanel", called "HudInventoryController", which looks like this:
using UnityEngine;
using System.Collections;
public class HudSlotController : MonoBehaviour {
private InventoryController ic;
// Use this for initialization
void Start () {
ic = GetComponent<InventoryController>();
}
// Update is called once per frame
void Update () {
}
}
However, inside the Start() method, the InventoryController (part of my Player) hasn't been created yet, and it seems to me like the gameobjects are created in alphabetical order...?
How should I deal with this problem?
You can specify script execution order in the project settings (Edit -> Project settings -> Script execution order), so use that to make sure your scripts are executed in the correct order. In addition to that, you can use the Awake() method as all Awakes are executed before any Start() method. Hope a combination of these helps you!
I solved this by creating an intermediate variable in my InventoryController script, plus creating a "manual" getter; https://gist.github.com/toreau/f7110f0eb266c3c12f1b
Not sure why I have to do it this way, though.