Options to storing data in a prefab - unity3d

After realizing that you can't really use UnityEvents in Scriptable Objects (they don't read global variable values correctly). I had to move to another solution for where to store my Dialogs.
The best solution I could find was to just store them in the corresponding NPC-prefab. This is really convenient. However this leaves a bad taste in my mouth, it just feels wrong to store data in a prefab like this. Is it a bad practice?
For example if I were to refactor something in the DialogObject, everything would be lost.
Since I can't seem to successfully store UnityEvents anywhere (can't serialize them as Json and as mentioned Scriptable Objects don't seem to handle them well) I feel like this is the only solution if I want to be able to use the Editor to create Dialogs.
Just checking here first, is this stupid? is there another way?
I am trying to save a List of this:
[System.Serializable]
public class DialogObject {
public List<PageData> conversations = new List<PageData>();
public UnityEvent postEvent; //Invoked on last page of Dialog
}

I would say yes, prefabs are meant to be a template to create new items of a type. You are trying to save data states.
Even though you cannot serialize the UnityEvent, you could serialize its content.
If you assign via inspector, you can use https://docs.unity3d.com/ScriptReference/Events.UnityEventBase.GetPersistentMethodName.html
But then you would not have problem of storage if you know from the start where it goes.
Second solution is when you assign the method to the UnityEvent, store it.
void AddListener (UnityAction ev)
{
MethodInfo mi = ev.Method;
// Use mi
postEvent.AddListener(ev);
}
With the mi reference, you have the name of the method, its type, the object it belongs to and anything you need.

Related

How to make copy of array's elements in the dart

Getting wired issue like main array has been changed if changed value of another array. I think issue is about copying same address, not sure but just thinking of it. I have tried from last 3 hours but unable to get rid from it.
Look at below illustration to get better idea.
List<page> _pageList;
List<page> _orderList = [];
_pageList = _apiResponse.result as List<page>;
_orderList.add(_pageList[0].element);
_orderList[0].title = "XYZ"
//--> Here if I change the `_orderList[0].title` then it also change the `title` inside "_pageList"
How can we prevent the changes in main array?
I got same issue in my one of the project. What I have done is, use json to encode and decode object that help you to make copy of the object so that will not be affected to the main List.
After 3rd line of your code, make changes like below
Elements copyObject = Elements.fromJson(_pageList[0].element.toJson());
// First of all you have to convert your object to the Map and and map to original object like above
_orderList.add(copyObject);
Hope that will help you.
You can use a getter function to create a copy of your list and use that instead of
altering your actual list.
example:
List<Page> get orderList{
return [..._orderList];
}
Lists in Dart store references for complex types, so this is intended behaviour.
From your code:
_orderList.add(_pageList[0].element);
_orderList[0] and _pageList[0].element point to the same reference (if they are non-primitive).
There is no general copy() or clone() method in dart, as far as i know. So you need to copy the object yourself, if you want a separate instance. (see this question)

MRTK Add ManipulationHandler in C#

I'm attempting to dynamically add Manipulation Events to a ManipulationHandler that is being added to child objects of a parent. The parent object will be what the user is inspecting, but the user will be able to grab parts off of the parent and inspect them more closely. (i.e. you can look at an engine (parent object), but if you want to inspect the pistons (child objects) you can grab them and look at them)
Instead of having to go into every child object and manually add it in Unity I'd like to be able to add the parent object and just procedurally add the ManipulationHandler and ManipulationEvents on start or awake.
So far I have the following code for adding the ManipulationHandler script, but to add the ManipulationEvent I'm not sure how to set up the pointers so I can use the script and function I want from the source:
gameObject.AddComponent<ManipulationHandler>();
ManipulationHandler handler = gameObject.GetComponent<ManipulationHandler>();
ManipulationEvent newevent = new ManipulationEvent();
ManipulationEventData eventdata = new ManipulationEventData();
eventdata.ManipulationSource = gameObject;
The program works when I grab the objects, but I'd like to add manipulation events when I grab them so I can display additional data.
I see there's a getter and setter for Pointer in ManipulationEventData, but I'm not sure how to instantiate IMixedRealityPointer and how to get it to work. I'm also not sure if that's the object I actually need to accomplish what I'd like to accomplish.
I apologize in advance if I've missed something obvious. I'm new to MRTK.
Thanks!
The ManipulationHandler has four callback events among them OnManipulationStarted and OnManipulationEnded you can simply add listeners to. (see UnityEvent.AddListener)
Unless I understood your question wrong you don't have to instantiate any IMixedRealityPointer. You don't create the event data yourself but rather the ManipulationHandler feeds these events with the current event data including the interacting pointer information. The ManipulationHandler uses OnPointerDown and OnPointerDragged and OnPointerUp via the IMixedRealityPointerHandler interface in order to manage the interacting pointers and invokes the according events where needed.
Instead of using AddComponent followed by GetComponent directly store and use the return value of AddComponent which will be the reference of the newly added Component. MRTK also has an extension method
T EnsureComponent<T>(this Component component) where T : Component
so that you can simply use e.g.
var handler = this.EnsureComponent<ManipulationHandler>();
which internally first checks whether the component already exists, and if not it adds it.
Note that in order to enable near interactions you will also need a NearInteractionGrabbable so you should add this one too.
You also will have to make sure that your objects have some sort of Collider attached to the same GameObject as the NearInteractionGrabbable.
...
gameObject.transform.EnsureComponnet<NearInteractionGrabbable>();
var handler = gameObject.transform.EnsureComponnet<ManipulationHandler>();
handler.OnManipulationStarted.AddListener(HandleOnManipulationStarted);
handler.OnManipulationEnded.AddListener(HandleOnManipulationEnded);
...
/// <summary>
/// If you need it later you need to store the pointer since unfortunately in
/// OnManipulationEnded the <see cref="ManipulationEventData.Pointer"/> is null
/// (no idea why they do it this way :D )
/// </summary>
private IMixedRealityPointer _pointer;
private void HandleOnManipulationStarted(ManipulationEventData eventData)
{
_pointer = eventData.Pointer;
// whatever shall happen when manipulation started
}
private void HandleOnManipulationEnded(ManipulationEventData eventData)
{
// whatever shall happen when manipulation ended
}
Note: I am not sure if this thing you are trying to achieve is possible with this architecture ... it is very possible that nesting various ManipulationHanlder leads to strange behavior here and there. Especially very small parts will be almost impossible to grab ...

Is there any way to use AddComponent with a script in Unity if there is no instance of that script in the game yet?

I need a way to add a script to an object that I just Instantiated. Ideally I could just set the script to add in the inspector. The problem is that I can't use
public Component scriptToAdd;
because then I would need to already have an empty object or something with the script on it. While that would work it feels kind of dirty or hackish to make an empty that just stores references to something. Also the point of doing it like this for me is to make it more efficient to swap out different scripts. If I had to swap out a script on an empty and then drag the new one in I'd lose on some of that efficiency I'm after. Thanks for any help.
After you instantiate, you should use the GameObject.AddComponent() Class, to add any component Type you want.
for example, if you want to add a camera to the scene.
void Start () {
GameObject myNewCamera = new GameObject();
//creates an empty game object, you can already attach components to it.
myNewCamera.AddComponent<Camera>();
//adds a component of type Camera
}
You can also use the overloaded constructor
GameObject myNewCamera = new GameObject("my object name", typeof(ScriptToAdd));
GameObject myNewCamera = new GameObject("my object name", typeof(ScriptToAdd), typeof(MoreComponentsToAdd));
Also, you should never be afraid of using an empty GameObject on your scene, for keeping information, references, variable values, saves, or anything really. It doesn't really affect the performance of your game, and you can make your life easy just by having an easy to find tag, such as "Engine".
Then you can access anything just by adding:
GameObject.FindGameObjectWithTag("Engine");
I hope I was able to help you :)
-Noe

Does Unity have a constructor when loading a scene?

I would like to populate the UI when I load a scene, with the correct data, instead of placeholders.
When I call "LoadSceneAsync", what would be the first object that is called, so I can fill the UI label with the correct data? I know that there is a scene GameObject, but I am not sure if that would fit my needs.
I am looking for some sort of constructor, called when a new scene object is loaded; to plug in my setup function.
You say
Indeed I did use "onlevelwasloaded" but the UI element may not be there, ready to go, when I invoke it, which lead to errors
That would be an incredibly sever bug in Unity! :)
Could it be that you are mixing-up Awake and Start somewhere?
One way to think of it is once you call Start, you know all the Awake have already run.
When I call "LoadSceneAsync", what would be the first object that is called, so I can fill the UI label with the correct data
You are still within the same frame.
Once you see LoadSceneAsync you can be absolutely assured everything is Awake 'd.
Or indeed once you use Start you can be absolutely assured everything is Awake 'd.
1) could it be that in some of your UI elements (or whatever) you are doing something in Start which you should do in Awake?
2) if (for some reason) you want to "wait until the next frame", perhaps just during development - then do that, wait a frame. You'll see a flicker, but if that's what you want to do (for some reason) do that.
3) note that if you mean you want to go to the net to get something, well of course you have to wait frames (use Update/coroutine) until the information comes back from the net, obviously. (How else could it be?)
Note that in practice, one should be using UnityEngine.Events.UnityEvent everywhere.
Maybe this is what you are looking for http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnLevelWasLoaded.html
Relying on Unity internal functioning is not always the way to go. Particularly when dealing with RESTApi (which is somehow what you are dealing with here).
You cannot assume one object will be ready before another except if you control it.
Add a Controller script that uses Awake. In the Awake, call all the methods you are needing and use some callback to generate secondary code when primary is ready.
public class MyController: MonoBehaviour{
private ServerRequestController serverCtrl = null;
private UIController uiCtrl = null;
private void Awake(){
serverCtrl = this.gameObject.AddComponent<ServerRequestController>();
uiCtrl =this.gameObject.AddComponent<UIController>();
serverCtrl.GetData(uiCtrl.SetUI);
}
}
public class UIController:MonoBehaviour{
public void SetUI(Data data)
{
SetTopImage(data.topImage);
SetBottomImage(data.bottomImage);
// And so on
}
}
public class ServerRequestController:MonoBehaviour{
public void GetData(Action onCompletion){
// This may be a coroutine if you fetch from server
Data data = GetDataFromSomewhere();
// At this point, your data is ready
onCompletion(data);
}
}
Thanks to this, you are now able to know exactly when a piece of code is ready.

Storing a complex detached object graph in EF6

I have the current scenario:
I'm using EF6 Code first, and have created a data-model something like this:
public class MainObject{
..some properties
IList<SubObject> SubObjects{get;set;}
}
public class SubObject{
..some properties
IList<SubSubObject> SubSubObjects{get;set;}
}
public class SubObject{
..some properties
IList<SubObject> SubObjects{get;set;}
}
So basically I have a main object, that has 0 to many subobjects, and there is a many to many relationship between the subobject and the subsubobjects.
I am creating a MVC application, so my normal program flow is that the user request a page that basically uses a MainObject as it's data model. Then the user interacts with the page and changes, adds or removes subobjects and subsubobjects as he wishes, and then clicks save. On save, the objectgraph is sent back to the controller and it looks correct according to the changes done by the user on the client side. Now my problem is the following:
How to store this back into the database in a good fashion.
I need to attach my object back into the context, but I have no clue which objects are new, modified or deleted.
I have written some code that partially works now, but it's getting so ugly that I really don't want to go down that path. Would it be possible somehow to fetch the relevant object graph from the database, and have EF compare the two graphs toward eachother, and then save the relevant changes to the database?
Any help to make this smoother would be greatly appreciated.
I ended up using GraphDiff to solve this for me, and it works just great! This really should be built into EF, but untill it does, this is a great substitute.
To solve the example given in my question above, this will make sure that the detached graph gets saved properly (given I have a MainObject I want to save called main):
context.UpdateGraph(main, map =>map
.AssociatedCollection( m => m.SubObjects, with => with
.AssociatedCollection( s => s.SubSubObjects)
)
);
context.SaveChanges();