#archived-code-general
1 messages · Page 74 of 1
that section makes it so i dont slide on the floor and the issue still happens when i comment it out
thats... odd. Theres nothing else in the code which you sent me that could be altering the way which it moves unless ive missed something really obvious
do you want me to send you the variables
sure
In Unity, what's the ideal way to make player jump & check when it can jump again without a double jump? OnCollisionEnter is a nice way, but it doesn't distinguish itself with walls, which have collisions too, therefore can give player an extra boost, even if they happen to have a PhysicsMaterial2D -component with friction all the way down to 0.
raycast downwards from the player using a layermask to see if its on the floor or not
thanks!
is that true in other engines & languages too?
alright, thanks anyway :)
what exactly happends when you jump, could you send me a video or something?
alr
check ur private dms i dont think im allowed to put videos in here
yep
hey guys. im getting these errors everytime i start the game. i dont know what they mean and the game still works and everything is functioning as intended so i dont know where to begin to figure them out. let me know if you have any tips!
wait i closed my unity editor and opened it up again and now those errors are gone. silly unity
That's what internal errors usually do
None of those seem to be your fault
Either close and reopen Unity, Try updating the faulty package, or try updating the actual Unity version used in your project
I have code that moves an object (with a 3D trigger) to a random location in a range, but how can I check that the object hasn't moved to another object, or that the navMeshAgent can navigate to that object?
look into physics overlap box/sphere casts to check if the space is clear, and NavMesh has a calculate path method which should return false/incomplete if it can't reach that location
(both of these can introduce performance red flags, so you might need to consider that)
mhm, okay
IEnumerator ObtainSheetData()
{
Debug.Log("ObtainSheetData calles");
UnityWebRequest www = UnityWebRequest.Get("https://sheets.googleapis.com/v4/spreadsheets/1agzzw8BueGIWLf8rioLuUtpWvNgL9dQZgRfkFF4-NRE/values/Sheet1?key=AIzaSyCehiHUpbtpkLCtM_V0xWFueWWfdqc0RwM");
yield return www.SendWebRequest();
Debug.Log("Download done");
if (www.timeout > 2 || www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError)
{
Debug.Log("error" + www.error);
Debug.Log("Offline");
}
else
{
while (!www.downloadHandler.isDone)
yield return null;
string json = www.downloadHandler.text;
Debug.Log(json);
}
}
the code does not do anything after this line
yield return www.SendWebRequest();
it never logs "download done"
Is it possible to change a builtin button's OnClick via script?
oki let me check
button.onClick.AddListener(heldItem.UseInInventory);
like this?
well we will see
Average properly assigning things fan vs average throw != null everywhere enjoyer
ehh ill figure it out
found out that calling coroutines in start function kills coroutines after the first yield statement
thank you so much!
Hey hey guys has anyone every used Newtonsoft with unity? I'm having some issues but idk if i should post my question here
Alright so as i've said previously i'm using Newtonsoft as a way to save things into a file to server as a save file.
I'm getting the following error NotSupportedException: rigidbody property has been deprecated even though i'm not using any type of rigidbody.
I'll leave the methods i'm using of my DataManager to save things into a file:
public static void SaveData<T>(string key, T data)
{
if (instance._saveData.ContainsKey(key))
instance._saveData[key] = data;
else instance._saveData.Add(key, data);
Debug.Log("Hey Time to save!");
Save();
}
public static void Save()
{
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto, Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
Debug.Log("saving..");
//Serialize the save data
string jsonString = JsonConvert.SerializeObject(instance._saveData, settings);
WriteSaveFile(jsonString);
}
private static void WriteSaveFile(string saveFile)
{
// Combine the save file path and file name
string saveFilePath = $"{s_filePath}saveGame.json";
if (!Directory.Exists(s_filePath)) Directory.CreateDirectory(s_filePath);
Debug.Log("No Directory.. Creating..");
if (!File.Exists(saveFilePath)) File.Create(saveFilePath).Dispose();
Debug.Log("No File.. Creating..");
// Write the serialized save data to the file
File.WriteAllText(saveFilePath, saveFile);
Debug.Log("Saved!");
}```
My test class that i'm currently trying to save for example:
```csharp
public class SurvivorManager : MonoBehaviour
{
[JsonProperty] public List<Survivor> survivors = new List<Survivor>();
[HideInInspector, JsonProperty] public List<Survivor> FreeSurvivors = new List<Survivor>();
[SerializeField, JsonIgnore] private GameObject survivorViewPrefab;
[SerializeField, JsonIgnore] private Transform survivorScrollView;
}```
What a survivor has:
```csharp
public class Survivor
{
[JsonIgnore] private SurvivorStats stats;
public float movespeed;
public bool isBusy;
public bool isInShelter;
//Ui
public string name;
public Sprite icon;
}```
I have 0 ideas from where this might be coming from
probably due to serializing an entire monobehaviour
you can't pass a MonoBehaviour to methods inside JsonConvert
you can put the fields inside survivormanager on their own class, mark it Serializable in order to have it show up in inspector, and use that instance as an argument to JsonConvert instead
should i instead use a Dictionary like <string, Dictionary<string, T value>> so i can pass the things i want to save from the class instead?
phew
no do what i wrote
MonoBehaviour still contains some deprecated/obsolete members like rigidbody (which is what your error is currently complaining about). just do what doctorpangloss suggested and create a class containing the data that you want to save
try using unitywebrequest. there is nothing wrong with the URL
i am really surprised it is glitchy for you
Did anybody else just get a dm from somebody asking for some help on a game? or is this NOT spam?
(not help, but offering a job, the wording was sus)
yes, i think it was done in good faith
Okay thank you
this was the problem : found out that calling coroutines in start function kills coroutines after the first yield statement
What if i didn't want to create a new class but instead change the Save method a bit, what would you recommend? Just to see which one would create the lesser hassle
hmm
i don't think that's true
it isn't
you might have another bug
and its solved now but thanks
it will be less of a hassle. the class you create will still be totally compatible with the pre-existing saved JSON
idk but it works
you can copy the fields into a new class using another method
but you will still need to author a new class
also, i'm not sure what part is the hassle
Hm but wait I would call the Save method on the Serializable class right?
if you have a ton of stuff designed in the inspector in those fields
you can always copy and paste the serialized text in the .unity / .prefab / .asset file and indent it
Which doesn't inherit monobehaviour
the save method you authored just writes a string to a file. forget about it
and i'm not gonna do anything if it works 😅
i refered to this so ... https://forum.unity.com/threads/unitywebrequest-does-not-return.953573/ this might be the case
the meat of your thing is calling jsonconvert
you can jsonconvert deserialize the string to your new class, and it will Just Work
provided the field names are the same
you can jsonconvert serialize the instance of the new class, and it will Just Work
it doesn't need [Serializable]. [Serializable] is to make fields inspectable that use the class as their type.
i think you knew that*
what is the hassle you are trying to avoid?
class MyMono : MonoBehaviour {
public int y;
}
becomes
[Serializable]
class X {
public int y;
}
class MyMono : MonoBehaviour {
public X data;
}
this is not a hassle
I mean not the Save sorry but the SaveData method. I was thinking of a way to change it so instead it would simply cherry pick what i want to save and add it to the _saveData dictionary.
The Hassle is just creating the class cuz then i'll have pretty much to do it to all the other managers and it might delay most of my work, since some systems weren't even made by me but someone working with me.
then call jsonconvert on instances of X instead of instances of MyMono
The Hassle is just creating the class cuz then i'll have pretty much to do it to all the other managers and it might delay most of my work, since some systems weren't even made by me but someone working with me.
you can always declare properties to smooth that over
that delegate to the object you made
i mean what can i say? it's a mistake
you can't serialize monobehaviours
it will take you literally 5 minutes to make all these adjustments
you can use refactoring in Rider to declare the properties too
don't create a piece of garbage _saveData
just make a typed object
if you want to represent a Save that contains all these little manager types, do that
wdym?
// jsonconvert this
class Save {
public SurvivorData survivorData;
public InventoryData inventoryData;
...
}
// jsonproperty is redundant but included here for clarity
[Serializable]
class SurvivorData {
[JsonProperty] public List<Survivor> survivors = new List<Survivor>();
[HideInInspector, JsonProperty] public List<Survivor> FreeSurvivors = new List<Survivor>();
}
then jsonconvert Save
copy in whatever you need
if you want to architect this well, call Save GameData instead
and access a global game data object from all your managers
This is the way
well architected games store all their state in one place anyway
that's hard to do when you want to make everything decoupled, but saving a game IS STRONGLY COUPLED so there's nothing you can do about that
it's irreconcilable. eventually you have to gather all the data somewhere
you can do that with dictionaries (🤮) or a typed class
I was actually using a dictionary for that inside my DataManager 
public Dictionary<string, object> _saveData = new Dictionary<string, object>();
static string s_filePath;```
yeah i know
you see why this is barf though right
you're just reinventing a class
it provides no value
yeah in a way
it feels like it provides value, it actualyl is anti value
i know what you mean tho
you have to fight this feeling in your body that says "don't make more files" or whatever
that's what htis is really about
games have a lot of fucking files it's okay
and if your colleagues freak about that, wait until they see how many "files" unity creates and just hides from them
you already know all this stuff
you have already ascended
so i am validating you
i am validating these feelings that you wanna do things the right way
the properties are a way to make this work without breaking in-progress code other people are authoring
then when they're "done" you can refactor -> inline those properties
to clean it all up
properties meaning
public class SurvivorManager : MonoBehaviour
{
public SurvivorData data = new();
public List<Survivor> survivors => data.survivors;
public List<Survivor> FreeSurvivors => data.FreeSurvivors;
[SerializeField, JsonIgnore] private GameObject survivorViewPrefab;
[SerializeField, JsonIgnore] private Transform survivorScrollView;
}
it's not it's my laziness sometimes, but okay let me see if i've absorved everything.
So instead of a dictionary create a typed obj for SaveData. then use that obj to simply serialize everything using the jsonconvert.
Also just create a class for everything that needs to be serialized inside the managers. Just to make sure the SaveData would be called, on the manager and i'd pass as args the class right? (Not the manager, but the class with the data)
you can make them setters too
that's all correct
yeah i think you know all this
you're not lazy 🙂
it's just tough, the instinct to avoid breaking other people's code is good
look carefully at the properties example
to show how you can avoid doing that
hopefully you are using Rider
or Visual Studio with resharper
or something else that supports refactoring
I'm using VS Enterprise actually
sick
i think it has resharper
ty for the explanation btw, very much obliged ^^
how is it possible that I am getting this error if I am specifically returning beforehand
you should be using the IsNaN method. I don't think NaN == NaN
oh ok, ty
did you mean to use Atan2 instead of Atan?
Atan is arc tan right?
it says here that isNan is for double?
Both are
the code functions properly as long as z/x does not equal undefined
the difference is that Atan2 covers more cases than the regular Atan
is there any downside to using Atan2 over Atan
None that really matter
ok
ill try it
thanks
ok, I added both suggestions and it seems to work now, thanks
does LoadSceneMode.Single destroy DDOL objects?
Can i use Starter Assets - First Person Character Controller | URP with a normal 3D ( so a non URP )
Hey guys, I am very new to programming so I am trying to make a simple game and wondering how I should approach this:
I am making a 2D game where players will "race" each other with various obstacles or whatever along the way. However, I am wanting the ground that they run on to be randomized. This includes hills, flat ground, maybe wall jumping, etc. For now, I am trying to get it so that a platform will always spawn off-screen on the right, almost like an endless runner. How do I do this?
Sending it here because no one helped in #💻┃code-beginner
typically you create prefabs of small custombuild areas with traps/obstacles whatever, and you randomly instantiate them as the player moves closer
go to #💻┃code-beginner because now im getting help
destroying objects creates garbage so don't forget object pooling
hi everyone. So i have multiple prefabs of the same in my scene, each one with a health bar, that should be reduced when a receiveDamage function gets called. And it does, but only in one of the prefabs, like when i call the function in another instance of that prefab it reduces the health bar in another instance
how can i fix this?
I have an issue where i setup a prefab as a torch with a light 2d and enabled shadows. Only on of the 4 prefabs casts the shadow, what am i missing ?
Create a Light 2D
Place the light in the center of the scene
Set the Light Order to 999
Increase the light's Outer Radius so it covers your entire scene
Set its Intensity to 0
Enable shadows and set Strength to 1
Place your "real" lights in the scene using any Light Order < 999; typical numbers like 0, 1, 2, 3... use a "normal" radius, intensity, and so forth.
Viola you have working shadows with as many lights as you want.
or you could use the Smart Lighting 2D asset from the store
it seems to be an unresolved bug
@gray thunder This sounds confusing, but it worked thank you 🙂
Yeah I know lol
Ive had this is older versions of unity
and assuming ur using a newer one,
unresolved still sadly
It is intended by design. I believe you misunderstand the nature of a Prefab and should perhaps reiterate on the subject. Maybe this tutorial could help you to understand the true purpose and utility of a Prefab. (https://learn.unity.com/tutorial/prefabs-e)
That being said, there is other alternative to what you are trying to accomplish:
- Usage of static variables (https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members)
- Usage of singleton (https://refactoring.guru/design-patterns/singleton/csharp/example, https://gamedevbeginner.com/singletons-in-unity-the-right-way/)
- Usage of Dependancy Injection Pattern/Tool (https://github.com/modesttree/Zenject)
- Usage of function such as GameObject.FindObjectOfType or GameObject.Find (https://docs.unity3d.com/ScriptReference/GameObject.Find.html)
- Usage of ScriptableObject (https://docs.unity3d.com/Manual/class-ScriptableObject.html)
- Usage of not-instanciated Prefab.
- Simply the reusage of the object by passing its reference to the interested
- etc.
This is a common issue in programming that a lot of people spent myriades of years to prefect. Still to this day, we are contemplating new and more complex solution for the management of references to adapt to the ever expending needs of flexibility and modularity.
I'm using 2021.3.18f1, that blows
ill look in to it thx

hey guys, idk if this is the place to ask but i need some help with my character controller. whenever something touches my character's collider, the camera starts drifting to the right or left constantly. I have no controllers plugged in, and it only happens when a collider applies an effect on my character's rigidbody
if you need the scripts i will provide them
Character controller:
Sounds wierd, this is how i did it in my camera script attached to the main camera to follow the player
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.position = smoothedPosition;
it doesnt matter what collider it is, if im hit with a simple projectile it starts to drift, and i was trying to add an explosion physics effect and if i am even near the radius it starts drifting, heres a video
You sure u don't have a collider component on the camera ?
How do I make sure Quaternion.Slerp always moves in one direction?
What do you mean ?
Nvm, I understand.
Yeah if I get a value over 180 it slerps backwards, but I want it to always rotate in a specific direction
Quaternion.Slerp will always go towards the shorter direction.
You will need to use other means of rotation.
I've tried transform.Rotate(Vector3.up, degreesToRotate); which works, but I need it to be in a coroutine so that it doesn't rotate all in one go
the issue is that not only the camera but the player also starts rotating indefenetily when something affects the players rigidbody, heres a video where you can see more clearly:
and I'm struggling with the frame by frame calculations for how that would work
You could recalculate the difference between your desired rotation and your current rotation each frame.
Usually, player controllers are made as Kinematic to prevents such issue.
that did it thanks
the issue is that i want the player to be able to rocket jump
and now the explosion doesnt make the cahracter jump
oh and now i cant move
I am unsure what is suppose to make your Character Move, but you usually use pseudo physics for the Character Movement as you want to have perfect control on what happens.
A "Rocket Jump" would be as simple as adding a velocity to your Character and then reduce it with the help of Gravity.
For my Character Controller, I work directly with the velocity of the rigidbody and simulate the push and jump by adding velocity to it.
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
Did you try to use CharacterController ? It is a good start for must project/prototype or beginner.
https://docs.unity3d.com/ScriptReference/CharacterController.html
I was able to get a start to the rotation that I'm looking for. Now I want to add dampening or some kind of animation curve to incorporate into it. cs IEnumerator Lerp() { float timeElapsed = 0; while (timeElapsed < lerpDuration) { valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration); transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(new Vector3(0, valueToLerp, 0)), Mathf.Infinity); timeElapsed += Time.deltaTime; yield return null; } valueToLerp = endValue; }
yea i started over, thanks for your help
void Start()
{
StartCoroutine(Lerp());
}
IEnumerator Lerp()
{
float animationTime = 0;
while (animationTime < lerpDuration)
{
valueToLerp = Mathf.Lerp(startValue, endValue, curve.Evaluate(animationTime / lerpDuration));
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(new Vector3(0, valueToLerp, 0)), 179);
animationTime += Time.deltaTime;
yield return null;
}
valueToLerp = endValue;
}```
Got it working with an animation curve. This a really niche issue so I may post it on the forums
You should not use Coroutine for such operation. It is hardly maintainable. Instead, directly use the Update.
There is no need to use Quaternion.RotateTowards, use directly Quaternion.Euler or Quaternion.AngleAxis.
Consider using an end time instead of using incrementation of a value.
Do not create intermediate value like lerpDuration whenever you can pass the value by parameter.
How dare you critique my perfect code. 😆
I have to use a coroutine since this will be event based, not just something that is chucked into the Update loop. I migrated away from Quaternion.Euler since it has gimbal issues at 90 and 270 degrees. I'll see about refactoring out the intermediate value
You see the fact this is event base is even more of reason why not use Coroutine. What would you do if you are already rotating ?
I wasn't using the lerpDuration for anything other than setting the time I want the animation to play for. So that's now just a serializefield member variable 🙂
My plan was to retrieve the current rotation of the object and set that as my starting point of rotation. I could also reset the rotation to 0 (or cache the original transform rotation)
If(I==null) yield break; Will this colse the if statement or the entire coroutine. I want to only close the statement.
The coroutine will stop.
I am pretty sure Gimbal Lock cannot happens whenever you only rotate on one axis.
why is everything going red?
You have a private modifier inside a function call.
If you ever struggle with the management of your state, remember what I said.
oh duh, idk how I didnt notice I was doing that
I am rotating on one axis
Not quite sure what you mean by the management of the state--I'd have to give a lot more context to maybe help you understand why I'm doing it this way and not another way. It's not just a simple rotation script unfortunately.
Thank you for your small critiques, keep up the good work
Hello! I'm having some trouble with angled surfaces! The player can shoot mines on walls and the ground but for some reason on an angled surface such as a wall, the rotation gets all messed up. Take a look.
I believe this is the code that is causing the issue. This is the only line of code in which I rotate the object. I assume it has something to do with the normal, but I'm not sure (i'm not great at math)
newGridObject.transform.rotation = Quaternion.FromToRotation(Vector3.up, collision.contacts[0].normal) * newGridObject.transform.rotation;
Nevermind, I got it working!
This isn't to help you, but I just wanted to say that's a really cool idea for mines!
Hi ! I'm having some problem with a method that uses reflection in a DLL that I share with my game server. The method works in the server. Any ideas why an exception is thrown (Unity 2022.2.13)?
Here is the Error and the function where the exception is thrown :
What does the Message says ? It should contains more information than the stack.
https://learn.microsoft.com/en-us/dotnet/api/system.typeloadexception.message?view=net-7.0
What is the value of typeof(IGameTask).Assembly ? Is the assembly correctly loaded ? Where IGameTask resides ?
Or is it the actual System.Reflection.Assembly that is not correct ?
If the actually issue is System.Reflection.Assembly, it might be an environment issue.
is there a way to write onto a cmd file? just trynna see if its possible
cmd is a program, not a file.
That's just called extension. .bat works for windows, whereas .zshc or .sh works for mac/linux.
ok
I am currently working on a script that should generate the mesh of a voxel Sphere, but I'm only generating the outer meshes. So I have this weird issue where when the worldradius is under 30, everything is fine, but when It's 30 or over parts of the sphere doesn't generate. Here is the code: https://gdl.space/ofuzirexud.cs
And here is a picture of what it looks like when the worldradius is 30:
how many verts? maybe exceeding 65536
What limit is 65536?
ah, that's probably it
so how would i go about changing it to a 32bit?
nvm i found it
thanks for the help : )
i have a problem, i am using a package for mobile input (joystick), and i am using the input system for the camera (fps camera game), the only problem is that the touch clicking the ui joystick is moving the camera, how can i avoid that?
here's my script (and my failed attemp to fix that)
//Cam movement before player movement
if (!usingJoystick)
move = moveTouch * touchSens;
else
{
//Here when you are already moving (or touching the joystick)
if (moveTouchSecondary != Vector2.zero)
move = moveTouchSecondary * touchSens;
}
i have tried everything but nothing seems to work
my bad
I'm trynna serialize some object with the newtonsoft thingy
And I got this error
UnityEngine.GameObject.get_rigidbody () (at <e8a406da998549af9a2680936c7da25a>:0)```
I'm not trynna serialize any rigidbody soo
I'm trying to make a script that will delete a tile from a grid if I hit it with a gameObject with a tag "bullet". For some reason, it doesn't work. The logs are appearing correctly (both the first and the second one), but the tile still stays. What am I doing wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class DestroyableWalls : MonoBehaviour
{
private Tilemap tilemap;
private void Start()
{
tilemap = GetComponent<Tilemap>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log("Something detected!");
if (collision.CompareTag("Bullet"))
{
Vector3Int tilePosition = tilemap.WorldToCell(collision.transform.position);
tilemap.SetTile(tilePosition, null);
Debug.Log("Tile destroyed");
}
}
}
Log the tile position and see if it's what you're expecting.
maybe you write a tag wrong in this line of code if (collision.CompareTag("Bullet"))
Please?
Maybe show us the code and actual error from the console tab.
if 'Tile destroyed' is printing, the problem is with your 'setTile' function
Likely you're attempting to access the rigid body property from Game Object that's been removed quite a while ago.
setTile should print if the cell value is incorrect, indirectly assuring worldtocell is correct
therefore set tile is broken
It looks like it
if that position is valid, then the problem is setTile
Was that the correct position?
Log the tile before and after setting to null.
it's a tile to the left
you'd still be able to tell if any tiles are null
Script:
https://pastebin.com/hLSgiSjw
Error:
https://pastebin.com/0A9viQx5
if it is out of range, you'd get an object null reference error anyway
Okay, it sometimes cashes the tile before the tile with the collider for some reason
Take an image of the console error.
When it hits the 252 -10 0 it is the correct one and destroys it.
but it sometimes hits the 251 -10 0 tile
which is weird, because the trigger is only set to 252 one
So it's to do with like 74.
you typed the same thing twice
oh wait
i get u
???
The collision will be in the correct place, might be an array issue in your 'WorldToCell' which returns slightly wrong tile
Also I know you've already made the code for all this, but there are some smarter ways you could design stuff
'tilemap.WorldToCell(collision.transform.position);' There will be a better way to do this probably, not involving transform.position to get something
thats a messed way of doing it
If you're trying to find the object, you can pass the object from the collision (collision.gameobject)
or you can give IDs to tiles, and reference with ID
Im just saying a lot of stuff yea but this isnt really something anyone can fix for you, you just gotta get involved with the logic and figure out where its messing up
sounds like, atleast in my opinion 'worldtocell' is going to cause problems purely due to the argument you give it
unless its a use case i dont understand
...
Is there any way to serialize all and any datatype?
Save the data you're wanting. Not the component.
Although, it should also be noted that rb property has been deprecated.
I'm not saving the component
All I'm saving is a Dictionary<string, object> and a List<SavableObject> where SavableObject is a plain custom class
Yes these can both be serialized. Unity's JsonUtility in particular cannot handle Dictionary though
You can either switch to a Serializable Dictionary implementation or a different serializer such as Newtonsoft json
Dictionary<string, object> is sus though
I am using newtonsoft
But it shows an error
That's what I'm here about
What error
then post the error, if that's what you're here about 😄
We cannot read minds
Looks like you might be storing a GameObject or a Component in one of these serialized objects
And trying to serialize that field/property
You'd need to share the full code for that objects you're trying to deserialize
i.e. SavableObject
I did
Scroll up
please
https://pastebin.com/hLSgiSjw
I wasn't here chill
you hadn't replied to any of your prior messages. the first message i saw was this one:
#archived-code-general message
i'm not really in the business of scrolling up in the off chance messages without replies are the continuation of an existing problem 😄
Okay sorry
It looks like you're doing some very strange reflection based way of trying to directly deserialize into a component
Why not just make a data object that the component has a reference to and just deserialize that data object and pass the deserialized object to the component
Whatever you're doing now it seems like your problem is there's a "rigidbody" field on the component and your reflection is finding the deprecated built in unity version of that field instead of the one in your subclass
Which is a hazard of doing this with reflection in the first place
Uhh
So what do I do about it?
And about the deserializing thing I haven't gotten to that yet, the error appears on serializing
Your reflection is way too permissive
FieldInfo[] fields = component.GetType().GetFields(bindingFlags);
Dictionary<string, object> fieldValues = new Dictionary<string, object>();
foreach (FieldInfo field in fields)
{
object value = field.GetValue(component);
fieldValues.Add(field.Name, value);
}```
This is finding fields like rigidbody that you have no business trying to serialize
Why not just use newtonsofts built in ways for identifying serializable fields
You're trying to build your own serialization system when there's a perfectly good one in the library already
Uhh how do I do it with newtonsoft then?
Okay, thank youu
Hello! We've reached the point where we would like to split our codebase into assemblies, but unfortunately since the project is few years old and we started as students, we have a lot of circular dependencies and it's not as straithforward as it could be since the architecture is, well, pretty shit, and since I haven't seen code of some of the core systems literally for a few years, it's basically hopeless.
Is there some kind of dependency mapping tool that I could use to spot parts of code or systems that do not have circular dependencies, so I can more easily figure out how to split it into assemblies more effectively? I feel like something like that must exist, since it sound like a tool that is both usefull and could be an interresting challenge to write for someone.
Start with a proper folder structure.
After that I would go with trial and error of just putting and assembly somewhere and seeing how many things actually don't compile properly 🤔
You are looking for Monolithic to Microservices. A lot of what you gonna find on the subject will be applicable on your issue.
There is numerous solution that has been propose for dividing an application in multiple smaller one, but most of them originate from white paper. To be honest, I think you should take the time to review your architecture an apply pattern such as the Strangler Pattern.
Most of those paper treats Application such as ERP and are made for large Application. Which is not exactly what you have in your hand.
We do have a proper folder structure at least, but unfortunately there's always that one UI script that needs something from random game mechanics, or various game managers directly calling functions on scripts instead of a proper observer/event system (which we implemented only like two years into the project).
Yeah, I will probably just do trial and error, but I kind of hoped that there is a tool that would print out a graph of what calls what, so I can identify distinct groups with only small number (or none) of two way links. I've tried to figure it out from an NDepend graph, but my trial has ran out before I managed to figure out what am I even looking for and how to use it for what I need.
@steady moat You are looking for Monolithic to Microservices. A lot of what you gonna find on the subject will be applicable on your issue.
Thank you! this sounds like the keyword I need. I wasn't sure if dependency graph is even the correct keyword for that (since I didn't manage to figure out what does the graph returned by NDepend actually means before I gave up). And the Strangler Pattern does sound interresting, so far we've had to rewrite a few systems during the years, but we usually just improvised and having a pattern to research and support the next refactoring will be useful.
On a slightly different note, how do any of you avoid such circular dependencies in your project? I'm usually at loss about how to handle some situations where different systems need to share information or call their functions. I can't think of any concrete examples from the top of my head, maybe for example something like UI having to pause the game (which couples UI with GameManager), Movement system needing to know if the player is dead from HealthSystem, AI needs the speed of players, buffs and effects need to make changes in almost any other system, same as per-level mechanics in gamemanager.
Are events and delegates (or observer pattern) the way to go, or am I missing some pattern.
Uhhh and how do I use that for it?
These are the most important attributes you need:
https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm#JsonObjectAttribute
https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm#JsonPropertyAttribute
you put them on the objects and fields you want to be serialized.
Ye I still don't get it
can someone tell me how to rotate gamobject to look at rightstick in 2d?
What you are missing might be the usage of interface. Look into Dependency Inversion Principle of the SOLID principle.
Event is a way to enforce this principle, but you should know that having an event base architecture can be a nightmare as everything becomes indirectly affected. You then have an hard time to figure out what is affected by what and you are exposing yourself to circular events. Keep the depth of your event system shallow and use them only when it make sense, not to prevent dependency.
As a side note, you should limit the number of refactor to only the "core" of your system. You should strive to have a "clean" code for things like controller, inventory, audio, vfx, networking, but do not try to make everything that is specific to your game "clean". Otherwise you going to do more harm then good by adding unnecessary complexity. In other words, if the feature could not be reuse in an other project, do not "clean" it.
There is also the concept of DSM (Dependency Structure Matrix) and the concept of Screaming Architecture that you could find interesting.
It means to have an architecture that is obvious to anyone.
You do not need to look into the code and you already know what the code is doing.
Dividing the project by System/Bounded Context is a way to achieve this.
By reading the Namespace/Folder Inventory you know there is an inventory. While if you have the inventory as a concept only in the Character, you wouldnt know that.
i should really figure out the architecture of my project, @steady moat if i draw out a diagram of an idea can you review it since you seem to understand a lot about code architecture and I don't because ive never done a massive project that needs it
If I am there. There is a lot of other people that understand such advance concept.
yeah thats true
I agree with the event-based nightmare, which is why I asked for tips. I've recently started working for a game studio that does console ports, and one of the games I'm working on right now is using Zenject with maybe too SOLID architecture, and figuring out what calls what, especially since I still don't know the architecture that well and the project has been finished and extended for the last few years, is a nightmare. Figuring out how to for example Disconnect from MP took me way longer than it should, since it was a mess of callbacks, where almost every step only took the callback, did something and then triggered his own callback.
I've also been traumatized with SOLID with one piece of code in our game, where since I was fresh out of Code style/solid college class at the time, implemented a UI loadout selection that was deeply abstract to be extensible, overenginered, and I'm sure it could be used for any kind of list-based selection we would ever need. And two years later I needed to change something and randomize the selection, and it was abstract interfaced hell that I couldn't even figure out how the hell it works and where the hell it takes the data it shows. (Oh, and our game does not have any lists anywhere, and probably never will). But that was more caused by my inexperience and needless overengineering, than by the principle.
Given those two recent experiences with this approach, I've kind of lost confidence that this is really the best way to go. But I'm still learning, which is why I asked for tips how others do it. I kind of like the Zenject approach, and will probably use that in my next project.
As for Interfaces - I've always liked using them, but stopped because of Unity and Inspector not supporting interfaces when linking/referencing gameobjects. But that's probably also something that's not a good practice - I've recently seen a few projects since I finally started working in gamedev, and most of them don't really use the Inspector that much (which we overuse, I'd say. Same with MonoBehaviors), which seems like a way better approach.
https://pastebin.com/axJ9NTWa
https://pastebin.com/6Pk9svrV
I have a component on my game object: AIC_PlayerCharacterInput. When I start the coroutine CalculateInput() of AIC_PlayerCharacterInput manager is set to Null (line 24). Why doesn't the code in the Start() method of AICBase_CharacterInput run?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
And another question - is there a way how to automatically solve missing references for assembly? If I add a asmref into a folder, the references are empty and I get bazillion of errors. Solving them manually isn't much of an issue, but I'd expect that there should be a button for that somewhere.
Unity now support Interface with SerializeReference, where it is true that it is not well implemented, you could invest a small amount of time to create/acquire a solution that would offers the serialization you want.
There is always a balance in everything, in college they push you all the way in the "clean" aspect, but, in practice, you need to figure out what is worth cleaning and keeping "abstract". As a rule of thumb, that would be whatever you consider to reuse or could be reuse in subsequent project. You also need to keep in mind that the SOLID principles are guideline and not universal rule. You need to see them as heuristic towards a good architecture, not literal rules to always follow like they are teaching in college.
An alternative of the usage of interface could be decoupling your class in smaller component. Instead of depending on inheritance to increase the functionality of a given object, you could use the composition. There is numerous advantage to use composition instead of inheritance, one being that there is little to no need for interface.
For dependency injection, I am not keen on the usage of library such as Zenject. I have not used it, but I never felt the need to use it. I use the ServiceLocator pattern for my "manager". The rest is being done with GetComponentInParent in the awake of a child.
I do not know.
hey can anyone help me with something. Im sure its simple i just cant find the solution because im pretty new
is it the same question you just asked
what do you mean
Ohhhh yes it is
do you know whats going on Ultra?
no because i dont have access to your project
The code is not running because you override the function by redefining the Start method. You would need to use virtual/override keyword and invoke the base method from the child.
I could show you my script
well, if you dont there isnt really any way to help you...
well thats a start, have you tried simplifying your movement script to just movement and seeing if that works
Thank you, you've given me a lot of stuff to look into. The ServiceLocator in parent sounds like a good idea, I'll check it out. The strength of Zenject from what I've seen in the project I work for is mostly in testability of the code. I'm still pretty amazed by the whole build process they have set up, tests for nullreferences or missing references in scenes, even mocking out a multiplayer game. Unless you do that then I guess the whole dependency injection is not that required in gaming.
Oh, unless you plan to do console ports down the way. Then it helps 😄
Anyway, thank you for taking the time to answer my questions, since I've recently finally seen some actual production code and architecture of larger studios, most of what I though I know about how to do game architecture was challenged, since every game I've seen does it different and extending their code each has different challenges, and I've lost most of my confidence about how to properly do stuff 😄 The conversation was inspiring, I have something to think about.
i dont want to change too much since im afraid that it will mess with everything else. I also followed a tutorial
well you should get used to making test debug scripts etc because debugging code is made up of stuff like that
ok thank you
@steady moat how does this look
some of the boxes arent super important
you might need to open the link
It is kinda hard to follow as you are leaving a lot out. But here what I can rapidly see.
- The inventory should be separate of the Player/Character. This way, you will be able to add the concept of Inventory on other object such as Chest or Shop.
- The concept of Player should be a duality of the concept of the AI. This way, you will be able to easily interchange and manipulate the player for things like - CutScene.
- The player should "control" an "avatar" the same way the AI does. This way you can manage what the player actual control and easily add others "controller" such as Vehicule or Menu.
- The concept of HP/Fall Damage should not be only applicable to the Player. You might need to reuse this in other object such as Destroyable.
- The UI should have direct access to the Player or other script via Interface and not use Event as means to communication. You should also add a "control" layer which would be the bridge between your object and UI. This way, you can replace the UI or the Object more easily.
Finally, you should do none of what I say and keep working as you are because you do not have the resources nor the need for a clean architecture. Pour all of your effort in creating mechanics and content for your game. Keep your project simple and you should not have any major issue.
anyone wanna partner up
hey so i'm trying to play around with creating a mobile game, and it looks like using Input.GetAxis("Mouse X") and Y works for camera movement based on where you move your finger on the screen. but the problem is that when I have my other movement joystick on the left side, if I move that, it will also move the camera. anybody know how I can restrict this zone?
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
hello, i am trying to add rocketjumping to my game, but sadly it isnt working. when the projectile hits the ground or something, all the rigidbody objects fling off, but the player remains static. i will send some of the scripts
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour
{
public float explosion_radius = 100.0f;
public float power = 5000.0f;
public GameObject projectile;
private void OnCollisionEnter(Collision collision)
{
// Get the collision point and normal
Vector3 contactPoint = collision.contacts[0].point;
Vector3 contactNormal = collision.contacts[0].normal;
// Calculate the explosion radius and power
float explosionRadius = 25.0f;
float explosionPower = 100.0f;
// Calculate the explosion direction
Vector3 explosionDirection = contactNormal + Vector3.up;
// Apply the explosion force to all rigidbodies within the radius
Collider[] colliders = Physics.OverlapSphere(contactPoint, explosionRadius);
foreach (Collider col in colliders)
{
Rigidbody rb = col.GetComponent<Rigidbody>();
if (rb != null)
{
rb.AddExplosionForce(explosionPower, contactPoint, explosionRadius, 5000.0f, ForceMode.Impulse);
rb.AddForce(explosionDirection * explosionPower / 2.0f, ForceMode.Impulse);
}
}
// Destroy the projectile
Destroy(gameObject);
}
}
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Thank you
send the player script with one of the paste links in the embed
I have the resources this early in development, the picture is my design goals, not what it is right now, and I do need a clean architecture to operate as a programmer otherwise i obsess over tiny things and my code becomes a mess of different architectures so that each piece sort of feels clean by itself
- It is, this was just for demo, I haven't added chests yet.
- I won't have cutscenes, not a story game, just a mission based ghost hunting game
- Sure, I can add an avatar class
- Maybe, I don't think anything else in my game will have fall damage but HP for sure
- This is the point where it starts to feel like overengineering to me, I will keep this simple, the UI does have acess to the properties, but I'm using events to notify the UI when something changes, such as when settings are loaded at the start of the game, or when the user presses Reset Settings, Reset Controls, etc.
thanks for the input!
Using FormerlySerializedAsAttribute, do I need to leave it in? Or once the fields are detected in Unity it can be removed?
Also, do you think the IManaged thing I put out is a working idea? It seems much nicer than what I have now, but not sure of its overall quality
Look into ServiceLocator, it is basically what you are suggesting.
After reading a bit more, you should simply it to be something of the ampler of the ServiceLocator.
alright I'll look into that
What I am suggesting for the UI is something as simple as MVC instead of directly using the UI. This way, you can swap out the different element of your UI. By example, you create a component that shows the capacity of your player and sometimes down the line you want to show the capacity of your enemies.
Model would be Player/Enemies, the View would be the component that shows the capacity, where the controller would be the bridge between both. You can also add multiple View whenever you do MVC so you can have the information spread on multiple component. The only thing that most not happens is a call to the UI from the Player.
But like I said, you should not think to much about it.
I don’t see anything in here that constrains its velocity. Try printing the name of all game objects you are applying the force onto to see if it’s detecting the player
alright, I will absolutely be needing to show the capacity of enemies, so abstracting that a bit would be useful, this is what you mean by MVC right, it looks like there are a LOT of variations
This code checking if player is in field of enemy view but how can i check if player Exit from field of enemy view?
{
Collider[] rangeChecks = Physics.OverlapSphere(transform.position, radius, targetMask);
if (rangeChecks.Length != 0)
{
Transform target = rangeChecks[0].transform;
Vector3 directionToTarget = (target.position - transform.position).normalized;
if (Vector3.Angle(transform.forward, directionToTarget) < angle / 2)
{
float distanceToTarget = Vector3.Distance(transform.position, target.position);
if (!Physics.Raycast(transform.position, directionToTarget, distanceToTarget, obstructionMask)) {
PlayerInVisible = true;
}
else
PlayerInVisible = false;
}
else
PlayerInVisible = false;
}
else if (PlayerInVisible)
PlayerInVisible = false;
}```
ok ill try that
ok, the capsule is detected, but the rigidbody is placed in an empty parent object that contains the capsule, does it mean i have to move my scripts and rigidbodies to the capsule?
yeah
ok ok ill try that thanks
are static constructors called before Awake()?
Yes, it looks like that. There is multiple variant of MVC, but it seems to me that this is a good way to represent it.
alright, time to refactor
I would only consider passing everything through the controller tough. Otherwise, you will have a harder time to swap out your model. Usually the Model update the View, but I prefer to make it pass through the controller so you have better control.
I think a static constructor is called the first time that static class is called
THAT DID IT THANK YOU!!
so this practically means that if I need to initialize static class before anything else, I just need Initialize() method instead of static constructor
i have a class which has a static constructor, it is called in edit mode once it has been changed or created
not sure what you mean by 1) edit mode 2) changed 3) created
that means right after the compiler compile the static constructor, i believe it will be called immediately
i see the debug.log in the constructor output after the compilation is done
🤔 🤨
I think we are talking about different things, I believe C# static constructors are 100% called runtime, not after compilation
well it's the JIT compilation
so runtime
what is he talking about then?
when you try to access the static class for the first time the JIT will run the static constructor
is my understanding
yes, i test it now, called after compilation is done
the simplest way to verify is to have a try
I don't understand still. What if I allocate something in heap in static constructor? If, as you say, it's called after compilation, I will have a random memory allocated for zero reason until I hit play?
And then it will get deallocated when I finish playing, and who on Earth will call this static constructor again if I don't recompile?
🤨
i think it is similar to you allocate some memory in awake/start, then you read/write on those memory in update()
now you have some memory allocate before play mode then you r/w them in start/updat
If i have a SortedDictionary<float,MyClass> and dont specify any IComparer<T>. Does it default to sort the float -keys in ascending order?
no, they don't mean script compilation after you change a script
It will default to the default sorting mechanism for the key type. Since float implements IComparable it will use that
And yes that would result in ascending order by value of the keys
then I don't understand what in the world they are talking about 🙂
afaic static constructor is called runtime 100%
It's also pretty sketchy to use float as a dictionary key because of precision error so be careful
well you could access it in an editor script
honestly, i just need a sorted list of KeyValuePair<float,MyClass>.
actually,there's probably a better way to do this now that i think of it.
it is worth saying that playmode != the runtime, it just gets reset with a domain reload when you play. Editor is also a runtime
well that's whole different story
ok, now I finally understood what they meant
makes sense
Also, whats the difference between new KeyValuePair<int,int>(5,5) and KeyValuePair.Create(5,5) ?
basically the same thing
just fewer keystrokes? x)
well, i guess new KeyValuePair<int,int>(5,5) makes the type clearer if that matters to you (e.g you used variables instead of 5 and they were badly named lol)
lmao
Can i just not use KeyValuePair.Create<int,int>(5,5) in that case?
or is that maybe not allwoed in this language?:P
think it is
I have a weird one and with it no real code to share.
I have eight cameras, all configured identically aside from which render texture they write to.
I'm displaying all eight cameras, but for some reason I seem to get this weird flickering only on the first camera
Just randomly parts of the image will go black
The camera is only looking at a skybox right now, and all other cameras render just fine
did you guys know you can reorder objects in the hierarchy via code? wtf
The flicker/artifacts are entirely intermittent as well, which makes debugging very challenging 😅
I wonder if it has to do with the depth
Yeah? You didn't know? It's object oriented design. It executes the code in the order of hierarchy unless otherwise explicitly state in the order of execution.
please dont rely on that
just set execution order
This goes the same for Audio stack as well! Beware! OnAudioFilterRead reads in the order of the component order of your gameobject!
I've been using unity for probably 3 years now and never knew that. Although I guess it's very rare that I would ever NEED to do it, but still
I wasn't relying on that, each component should be self contains and maintain a single responsible pattern. If I have several component that share the same functionality, I'd combined them into one component so that it doesn't behave unexpected at runtime.
Usually with a [DisallowMultipleComponent] attribute 🙂
Does anyone please have a working script for serializing and deserializing objects along with their components and the components' values that works and works universally with all types
Pleasee
no one is just gonna give you code
put some effort into it
Istg if I hear such a thing I'm gonna kms
I've been trying the whole day yesterday and the whole day today and can't get shit to work
no need to be dramatic.
Why don't you try posting what you have tried and where you got stuck
I tried
I got no answer
And I give up
Instead I'm asking Does anyone please have a working script and is willing to share?
People who refuse to google and ask for resource on discord is frown upon.
Just like how people asked us to correct ChatGPT answer.
I DID
I GOT NOTHING
is there a way to trigger oncollisionenter like a function?
that's a pretty big lie though, we are not stupid
I get literally thousands of results.. how can that be ?
and I am
And I got NOTHING
Maybe you didn't google it correctly 🤷♂️ Plenty of resources online on how to properly serialize and deserialize your script.
Sorry, nothing that works
this just makes me assume you tried NOTHING and you just want a lazy script
🤷♂️
no don't think so.. why do you need to do that
I tried
For like 18h now
I got frickin nothing
If there are so many then just please send me one
trying to make conveyors that update when a new one is placed next to them
please
Gotta pay him 10$ first for the effort
show what you tried and I'll believe you
using hit normals
so why doesn't it work now?
well all of them update when one calls oncollision
"All of them"?
every single conveyor in the scene
because all of the collision boxes are overlapping
and so they rotate again
OnCollisionEnter invokes when your object collides with another object containing rigidbody. No need to invoke the method directly.
You want a script handed to you
The engine will invoke the method for you.
and also when i place a new one it immediately turns to face the last one in the chain
Then implement that behaviour in your Awake() method.
https://pastebin.com/ew4jkdSU
I know what's wrong, you can't serialize components, got that
However I got no answer how to do that differently
I mean I got one and it still gave the same error of newtonsoft trying to access rigidbody for some reason
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
im not explaining this very well
what is even the point of serializing a gameobject.. just the data is important
then replicate the object
Alright
Still how do I save the data
You write the serializable class you got into a json or similar file
I use .bin if i wanna save space
Specifically how do I save the values of a component
make a struct/class for the values you wanna save , deconstruct it back on initialization of object when loaded
That's what google says
And that's why I couldn't find nothing
Cuz I need it to work universally, for any component
If you need object to exhibit behaviour as if it was colliding with something, you'd implement a public method outside of your OnCollisionEnter, which allows you to invoke the method from another class. Your OnCollisionEnter would still interface that method inside the class for collision purposes.
You can easily do that just boil it down to the primitive types..
The idea here is that you shouldn't invoke Unity's protected method, but you can invoke implicit method.
If you need to serialize component, then you're serializing it wrong.
^ good point
You should start thinking as data orient design instead of object oriented. All of your component should drive based on data you want to save, and your component should just execute with values saved/loaded.
I think you need to learn C# in general before you ask us what primitive type is.
Okay but I need it to work with custom types too
How do I simplify a random custom script that has I don't know what variables
also if you were more clear on specifically what from the gameobject you wanna store..
everything. (all components and their values)
how's it a custom script without knowing the variables.. that makes no sense
I just need it to work automatically and universally for anything
you seem to be jumping ahead of your current skillset
What does it need to do in the first place
"future proof something without knowing what IT is"
U wanna have serializable class with json?
Probably but I need it and noone wants to share their script so
because there is no single click 1 size fits all solution..
you need to learn how to tailor data
Wdym
what do u wanna make
like how to pass data around to fit a specific need? that includes serializing stuff
A saving system that would save a bunch of objects along with their components and the components' values
That would work universally, for all components and values
Cant u save into a prefab
Wdym by specific need
The need is universal saving
you want 1 button that saves all the shite for you like magic..
someone needs to make it happen cause it ain't magic
Idk I'll try that
Idk if u can save smthn into prefab at runtime at all, let alone do that in a build
Just a guess
Since prefab counts as an asset
You cant serialize a prefab itself into a file though
Isn't a prefab itself a file
So can't you just copy it
Idk I'm pretty sure I'm asking for a saving system not frickin teleportation but if that's called magic then yes, I need magic
Do u mean save as in actually keeping a file even after stopping the game
Or just to save a value basically at runtime somewhere
Yes
Yes to which
such a system needs to be built , there is no 1 click solution out the box
Yes, I need it working even after stopping the game
if you don't know what primitives and understand reference types vs value types, then you should go back into some basics of c# @uncut vapor
just honest advice, but this is #archived-code-general not #💻┃code-beginner
you should have some type of understanding
I know what primitives are
Ffs it's not my first time coding
so far you're coming off that way as you're not understanding why you don't serialize gameobjects
I'm just stupid alright
Is there a way to do it universally?
explain what "universally" is, maybe I'm inept here..
For it to work with any component and any variable of any type
You don't work with components, you extract the data from it then rebuild it with that data..
any variable of any type is fine as long as it's something that can be serialized fine..
Okay is there a way to save any values of any component and any variable of any type
Ye but most types can't be serialized fine
like what ?
Actually no most can with the newtonsoft thing but how do I save all the variables, how can I reference them to save what var it is and what data it has
each class creates a new SaveData object or similar serializable class
then you Load the data
from each object
???
stop spoonfeeding and google "serialization".
they did google, and apparently found NOTHING
hell even GPT can explain this shit with code examples..
they are just lazy and "want script plz"
I tried doing it myself, I frickin failed
But if it's so simple to search it then please, PLEASE tell me how to save all the variables of a component and I'll be happy
you need to go back and watch 5 hours of youtube tutorials, and then come back with a specific question
I told you how about 3-4 times
this ain't a tutoring site
Then please tell me one more time but in a way I'd understand it
colour me impressed
no because at this point I just think you're failing to troll
the knowledge is out there, put a little effort don't be lazy
I'm not
I'm just fucking stupid
Just tell me and I'll stop as you called it trolling
you're not stupid, you're lazy
^
yeah thats it
take a breath and relax
I tried for HOURS
About 18h now
you need a break
To find something
everyone has times where they feel like they cannot figure their problem out - you just need a break
I will if you just tell me how do this come on
yeah go paint a picture or something, then come back with fresh mind
in c we have pointer and read all memory in certain memory space, a similar approach in c# maybe just iterate all variable you can get and write them into file, for deserialize, revert the process, work at low level
in c
and then i stopped listening 😄
Just please
Please
Please
If it's so obvious
Then just tell me
C is low level access, c# is not
18h to GOOGLE how to serialize an object? did you try the approach where 10 chimpanzees use typewrites and eventually will type out the answer?
dont bully
yeah sorry
Okay that's hilarious but cmn just tell me
Pleaseee
at this point I think it's best you stop posting and take a long break, honestly. you have asked repeatedly and no-one has given you an answer you're happy with (although plenty of good answers have been given). at this point, short of someone writing the code for you (which is not good for you or what this channel was designed for), you won't be happy.
i don't think it's a good idea for anyone else to entertain this further
public override IEnumerator CalculateInput()
{
// Start forever loop that breaks when an action is taken
TileController selectedTile = null;
while (true)
{
Debug.Log("Update!");
TileController clickedTile;
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Left click detected");
Collider2D clickedCol = Physics2D.OverlapPoint(CameraController.Instance.cam.ScreenToWorldPoint(Input.mousePosition));
}
yield return new WaitForEndOfFrame();
}
}``` `Debug.Log("Left click detected")` never runs. How can this be? `Debug.Log("Update!")` does every frame
i have never seen mouse input inside a coroutine before
Maybe it has something to do with WaitForEndOfFrame? That is a special thing meant for rendering stuff, you should be using yield return null instead
@steady moat So the issue was with my DLL being compiled to dotnet 6 instead of dotnet standard 2.1. So I suppose what happens from the decompilation warnings is that unity binds its own assemblies and simply never crashes until it meets a problematic method or class.
Okay. Let me try that
That worked 💪
Thank you!
No problem :D
Im guessing by the time waitforendofframe was done, the input system had already cleared up and was getting ready for the next frame
how do i use List.Remove() to remove the first entry on a updating list?
does First() not work?
List.Remove(0); // removes item at 0th index```
First()? never heard of it
but what if its contentiously updated?
i suppose the next value will then becomes 0?
indeed
Yep
hm, says it cant convert from int to vec3
RemoveAt ?
By the way, a Queue is a data structure that was designed for this if you're adding to one side and removing from the other 🙂
Assets\Scripts\Newtonsoft.Json\Newtonsoft\Json\Linq\JContainer.cs(385,41): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'
i got this error out of nowhere in my project and i dont know how to solve it
any help would be appreciated
can you show the full stack trace?
what do you mean?
The console window will show you the full stack trace of the error when you select it
in the bottom panel
oh wait actually that's a compile error?
It looks like you've imported newtonsoft JSON incorrectly
You should be installing it from the package manager not by placing it somewhere in your assets folder
how do i do that
Install instructions can be found here:
https://github.com/jilleJr/Newtonsoft.Json-for-Unity/wiki/Install-official-via-UPM
Recommend deleting the one you have in the scripts folder and installing it like that
ok thanks
i followed the instructions but the error persists any idea why
sounds like you didn't remove the other installation
ill retry and ill let you know
i got 648 errors 
in the console
and basically every other package i have installed
From where do they originate
every package
such as?
why are all your packages installed in Assets/Scripts?
Looks like you've done something very wrong
packages should be installed from the package manager
because the original project was ripped
I would delete all of those packages you have in Assets/Scripts
install them from the package manager
k
I added the netcode for gameobjects package, but I get this error, what does this mean and how can I fix this?
anyone know how i can realize what i'm going for here?
operator + cannot be applied between types T and T
wondering if i should just make a unique class for each value type im interested in, or have overflows somehow within this generic type?
you will need to constraint T
how to do this properly is what im wondering i guess
unfortunately, I don't think there's a really nice way to do this in C#
it'd be easy in Haskell, but alas :p
well in the newest version of C# that Unity can't use there's the INumber interface, RIP
well dang then lol
multiclasses and overflows it is
but thanks very much for the help yall
I think you're looking for "overloads", not overflows :p
yea lol, my bad
Actually think you're looking for override in this case?
have been using overflow as a feature lately so it's a freudian
oof
no in this case it would be overloads (multiple same-named functions with different params to handle different cases)
i guess that works
although maybe inheritance and using override in some fancy way could be elegant to solve this
i want numeric type agnostic arrays that i can reshape like a tensor, do in-place elementwise operations on, as well as matrix operations and other junk
(so tensors, pretty much)
How do I code a level generator similar to this? https://ivess.itch.io/failing-but-gaining
google procedural dungeon generation
okay thanks
You could use the "dynamic" keyword, but I would highly suggest you find an alternative as it is not performant and it removes type validation.
Might anyone have a link to a primer on multi-threading with Unity?
Yes I could google it myself but I'd like to know if anyone had particular success with one and could nudge me in that direction
If I store multiple gameobjects under a single tag
How can I acces those game objects individually from that tag?
group them up into a list and access the elements or instead of tags make a script and attach it and look for that script
And how do you use
FindGameObjectWithTag
To find a tmpro textfield with a tag?
just reference the tmpro textfield component in the script with [SerializeField]
Can you show?
[SerializeField] private TMPro.TMP_Text textField;
drag the component in here ^
in inspector
Put a unique tag/script for it, look for the script that deals with TMP_Text textField component
Because I am making a prefab of it
Drag and drop references are losing
spawn the prefab that already has textfield reference in a script
See like
Previousl
I had
Public textfield xyz
Then when I prefab the object with the script attached to it and with a reference
It loses the reference when I instantiste it
it's very simple
make script type and spawn the prefab as that type then use it via script
Can you show me how?
You can explain or send some link explaining it
Cause I am not understanding properly how to do that
These are some of the best ways to reference game objects in the Unity engine. There are other methods of getting a reference such as the GameObject.Find and GameObject.FindObjectsOfType methods, but those methods are generally slow because they need to traverse the hierarchy to find the object and you don't get to choose which object it finds i...
you can just spawn it as that type when you spawn the prefab, no need for GameObject type tbh
Can you give an example?
Just the spawning part
Like the line for spawning what would you write?
var InstantiatedObj = Instantiate(myPrefabWithScript) InstantiatedObj.DoStuffWithTMPTextInHere;
one script on prefab will always have TMP reference since it's on the prefab
public class Tee : MonoBehaviour
{
[SerializeField] private TMPro.TMP_Text textField;
public void ChangeText(string text)
{
textField.text = text;
}
}
public class AnotherClass : MonoBehaviour
{
[SerializeField] private Tee prefab;
public void Spawn()
{
var instance = Instantiate(prefab);
instance.ChangeText("Hello");
}
}
Pretend Tee is script on the prefab
and AnotherClass is when you spawn prefab
I was looking at the App manifest file in my Unity project and saw this
This means Unity games have admin rights by default??
Its commented isnt ?
how do i find the name of an object that is a child of a certain gameobject
i have the gameobject as a variable, i just want a child that has a certain name
.name == "name"
No its green because of these things
Which is the way comment are made...
Yeah
but i need the child's name
transform.GetChild(0).name
thanks
this is the gameObject i have. i am making a prefab of dices containing a script called diceManager. when i prefab it,i am losing the tmPro references of ones and twos, in the 3rd pic you can see the Tmpro component i am trying to refer
So to answer your question, Unity does not have admin rights, at least not with what you are providing us. It merely show how can ask for admin rights.
you cant reference scene components inside the prefab
spawn the prefab with canvas that has text then
or don't control scene text through prefab, thats silly anyway
then?
huh?
how to do it the correct way then?
Have Scene Objects control Scene Canvas
I am dumb I just realized something, I was supposed to be looking at this (changing asInvoker to requireAdministrator will make it admin)
like this?
this makes sense only in certain situations
like canvas with certain text can be part of the prefab
this isn't a good usecase though it seems
what to do then?
I told you what to do, only have the scene object control the TMP text
why does prefab have text components
it shouldnt?
can you tell me how, idk how
this belongs in #💻┃code-beginner at this point...
You've yet to clarify why TMP text is inside prefab
the prefab changes the value of the text
so it has a reference of the text, to show the changed value
how else will i refer the text to change the value?
you only stream the changed value to an object in scene that processes that value
the prefab processes the value
prefab is a dice, the dice value is shown in the text
the dice doesn't need to control text at all
it supposed to just give you the final number
pass it to a class that deals with the rest
even then its the same thing?
no
the class has to send the value to the text
we clearly have a miscommunication here
the prefab literally has to reference 0 things in the scene
have a script in the scene that processes the dice's values
then update the text with that scene script
i showed you how you can pass the dice into another class on spawn
like have a game manager object with the script?
ok
and the dice manager will have reference to the text as well as the dice prefab?
yes
ok thanks
public class Dice: MonoBehaviour
{
public int RollDice()
{
return Random.Range(1, 7);
}
}
public class DiceManager: MonoBehaviour
{
[SerializeField] private Dice prefab;
[SerializeField] private TMPro.TMP_Text textfield;
public void Spawn()
{
var dice = Instantiate(prefab);
var number = dice.RollDice();
textfield.text = number.ToString();
}
}
``` Just to make an example
public class DiceManager: MonoBehaviour
{
[SerializeField] private Dice prefab;
public void Spawn()
{
var dice = Instantiate(prefab);
var number = dice.RollDice():
}
}
this will be in another obejct right
dice manager object?
public class Dice: MonoBehaviour
{
public int RollDice()
{
return Random.Range(0, 7);
}
}
``` and this in dice object?
alright thanks!!
yeah fixed my typo, 0 should be 1 but you get the point i think
Ok then dice manager will always be on scene
The dice will be spawned
And the scores have to be spawned as well
Because it's over PUN2
How do i refer them?
To the dice manager
Does anyone have a script which gets all the integer vector3's in an object.
what are you trying to do?
Im trying to get all the points in an object so I can run them through a marching cubes algorithm.
refer what exactly
@woeful furnace I’m still not sure what values you’re trying to retrieve
So all points in an object which are whole numbers so like vector3(1, 1, 1) or vector3(5, 10, 3). Then when I have these points I can use marching cubes on them. So lets say you have a cube which back left corner is at 0, 0 ,0 to the top the corner of 4, 4, 4 I would want to all the points between 0 0 0 and 4 4 4. I am not sure if an algorithm exists to do this or if there is some work around.
all points between as in 2,2,2 and 3,3,3 and 3.5, 3.5, 3.5? or did you mean the other vertex’s?
So like 0, 0, 1; 0, 1, 0; 0, 1, 1; 1, 0, 0; 1, 0, 2; and so on however I dont just want this to work with primitives' I want it to work with sealed shapes so I was thinking of maybe casting a ray and seeing if it goes through an object twice and cast it on whole points then return points which are detected when it is inside an object.
can you install nuget packages to unity?
don't think so, you gotta find a version of the package that has the dll compatible with whatever .NET you're running in unity
I am writing up what im thinking on paper
I think I kind of understand what you mean. Like raycast it from the front and back to figure out it’s enter and exit point?
Btw chicken scratch
So everytime we enter enter a plane increase an interger to 1 and then add all points the ray hits and if its even then dont add it.
We repeat this for the width and height of the object.
Atleast this is the idea Ive come up with im guessing there is probably a better way to do this.
It’s always whole numbers right?
Yes because marching cubes will use the number as corner for the cubes
I think all you need to do is raycast all over one face of the cube. Each raycast would be aligned to the x axis. From that you can find the start position (from the raycast) and the end point (a raycast from the other side). Then compute how many whole numbers fit between each raycast
public Vector3[] SingleLineOfPoints(Vector3 start, Vector3 end)
{
int length = (int) (end.x - start.x); // the number of whole numbers
var array = new Vector3[length];
for(int i = 0; i < length; i++){
array[i] = new Vector3(start.x + i, start.y, start.z);
}
return array;
}```
so as an example, there’s a 5x5 cube with the top left corner at 0,0,0.
You’d call this method 25 times, and then add together all the arrays at the end
Thanks ill try this out hopefully should work with spheres and the like ill try it.
Wait the way this works it wont function with example like the one with a cube inside the sphere
I think ill go and implement the raycast solution
number 2?
So each layer is just the topdown view or slice.
yes
I want it to work with any shape
it should be able to. Think about this, “cube thing” is 4 x 6 from front view. Take 24 toothpicks, and stick them onto a grid onto the shape. Then snip off any ends that touch air. You’ll end up with a grid with depth that resembles the shape.
2 2 4 4 4 4
2 2 4 4 4 4
0 0 4 4 4 4
0 0 4 4 4 4
0 show points where the raycast didn’t hit anything. The other numbers like 2 and 4 represent the number of whole number points between the front and back of the raycast
Alright I see
TextMeshProUGUI ones = GameObject.FindGameObjectWithTag("scores").transform.GetChild(0);
error - error CS0029: Cannot implicitly convert type 'UnityEngine.Transform' to 'TMPro.TextMeshProUGUI'
how can i fix this?
Don't try to shove a square block into a round hole
idk how to convert transform to textmeshprougui
GetChild returns a Transform.
Your variable type is TextMeshProUGUI.
You don't
You use GetComponent to get components attached to GameObjects
I see we're not learning with simply just using [SerializeField]
You don't "convert" anything
i used it
but this is different
then what's with this runtime shtick
dont have spawned prefabs control UI in the scene
no no, the dice manager is controlling it
the dice managaer is not spawned
but i will spawn the scores as well
why not, it was supposed to be part of the scne
yes it is in scene
like wont be spawned, as in it will always be in scene
but the scores will have to be spawned
why
do the same thing tho, you pass the data to the script that handles the scene UI and stuff
i am doing that
TextMeshProUGUI ones = GameObject.FindGameObjectWithTag("scores").transform.GetChild(0);
but dont know how to fix this
GetChild returns a transform
and you're looking for TextMeshProUGUI
and this isn't the same thing I meant but whatever
your spawned object shouldn't be touching UI components at all
anyway to solve this just GetComponent the TextMeshProUGUI
assuming it exists on child of "scores" GO
oh thanks this solves it
i am not, the score has to be spawned, so setting a run time reference for the dice manager to access the scores
what's the difference between (float, float) and float
(float, float) is probably vector2
probably a tuple
thanks
Finally got an implemenation using my raycasting method pretty fast and happy with the results.
(version 2020.3.33f1)
builds of my game throw this error: This Mesh Collider is attached to GameObject at path 'Level Control/The Rebel Alliance/ISD/Colliders/Collider.014' with Mesh 'Collider.014' as child of a non-uniform scale hierarchy, in Scene 'Testing'. Change the hierarchy scale to uniform, or mark the mesh read/write in order to be usable with the given transform.
The weird things are:
- This doesn't happen in the editor
- The scale is uniform. there's nothing that is manipulating the scale, and Debug.Log says the scale is uniform
do you know which Mesh Collider is referring to ?
yeah
i get the error message for all mesh colliders in an ISD
actually no, almost all of them
if ISD is some type of asset it sounds like it came broken or something
not sure tbh
I think I've found the issue
I followed an official unity tutorial on physics optimization that recommended turning off all cooking options except for Fast Midphase
I undid that and now everything is fine
I am trying to have specific code not compile on build, I have #if UNITY_EDITOR On the code so far, but some reason I am still getting build errors from that code.
you have #endif too, right?
yeah
Assets\Modules\3rdParty\Editor\Grapher\TimeKeeper.cs(29,18): error CS0103: The name 'EditorApplication' does not exist in the current context
using System;
#if UNITY_EDITOR
using UnityEditor;
namespace NWH
{
public static class TimeKeeper
{
Wiat sorry
Not quite the issue, but there you can see Time keeper shouldn't even be being compiled and yet it is. Thus it seeing a reference to other code that isn't included on build
I am restarting unity now as Line 18 of that file is comments, so I think it might not have been compiled again after my edit for some reason
sorry to budge in but I have a quick question.
I want to have my first-person camera's rotation to be "relative" to it's orientation. So if my character was laying sideways, I want the camera to rotate vertically on its local rotation.
I've been banging my head against a brick wall for the past hour but I just can't seem to figure it out, any way to point me in the right direction?
code snippet if needed: (don't know how to do the fancy code block outline in discord, sorry)
private void UpdateRotation()
{
_camYaw += LegacyInput.GetLookInput().y;
_camPitch -= LegacyInput.GetLookInput().x;
_camPitch = Mathf.Clamp(_camPitch, -89f, 89f);
transform.localEulerAngles = Orientation.up * _camYaw + Orientation.right * _camPitch;
}
"LegacyInput.GetLookInput()" is just Input.GetAxisRaw("Mouse X/Y").
"Orientation" is an empty Transform that the camera is attached to.
Hey, I think I have a solution for you! Try updating your UpdateRotation() function like this:
private void UpdateRotation()
{
float camYawDelta = LegacyInput.GetLookInput().y;
float camPitchDelta = LegacyInput.GetLookInput().x;
// Rotate around the local Y (up) axis of the parent transform
transform.RotateAround(transform.parent.position, transform.parent.up, camYawDelta);
// Rotate around the local X (right) axis of the camera itself
transform.Rotate(Vector3.right, camPitchDelta, Space.Self);
// Ensure the camera pitch stays within the desired range
Vector3 currentEulerAngles = transform.localEulerAngles;
float currentPitch = currentEulerAngles.x;
float clampedPitch = Mathf.Clamp(currentPitch, -89f, 89f);
if (currentPitch != clampedPitch)
{
currentEulerAngles.x = clampedPitch;
transform.localEulerAngles = currentEulerAngles;
}
}
I think this will fix it 🤞 but im no means professional myself
i wanted to ask for help from someone, this seems to be a common issue online since 2017 but i cant find any solution that works, ive deleted he library, reimported everything etc:
Building Library\Bee\artifacts\Android\iz17e\libil2cpp.so failed with output:
ld.lld: error: undefined symbol: GADUGetAdErrorCode
please any help at all i'd owe you one
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
thanks
I tried the suggested code, but it seems to be a little "unstable." I modified it a bit to try and get it working correctly and it "kinda" does what I want it to do.
private void UpdateRotationNew()
{
float camYawDelta = LegacyInput.GetLookInput().y;
float camPitchDelta = -LegacyInput.GetLookInput().x;
// Rotate around the local Y (up) axis of the parent transform
transform.RotateAround(transform.parent.position, transform.parent.up, camYawDelta);
// Rotate around the local X (right) axis of the camera itself
transform.RotateAround(transform.parent.position, transform.parent.right, camPitchDelta);
// Ensure the camera pitch stays within the desired range
//Vector3 currentEulerAngles = transform.localEulerAngles;
//float currentPitch = currentEulerAngles.x;
//float clampedPitch = Mathf.Clamp(currentPitch, -89f, 89f);
//if (currentPitch != clampedPitch)
//{
// currentEulerAngles.x = clampedPitch;
// transform.localEulerAngles = currentEulerAngles;
//}
}
I had to axe most of the code at the end because it was fighting itself
The only issue is that the camera is no longer locked to its axis, I can spin the camera to a different Z rotation if I move my mouse in circles.
when did this issue start? today?
I do not think you have looked into what RotateAround does
yeah that probably explains why I can spin it
mmm
Because it's not what you're trying to use it for. I would recommend following any of the multitude of camera controller tutorials out there, or hell, just use Cinemachine
maybe is there a free asset that does this?
hmm how bout this:
private void UpdateRotationNew()
{
float camYawDelta = LegacyInput.GetLookInput().y;
float camPitchDelta = -LegacyInput.GetLookInput().x;
// Rotate around the local Y axis of the parent transform
transform.RotateAround(transform.parent.position, transform.parent.up, camYawDelta);
// Rotate around the local X axis of the camera
transform.RotateAround(transform.parent.position, transform.parent.right, camPitchDelta)
Vector3 currentEulerAngles = transform.localEulerAngles;
float currentPitch = currentEulerAngles.x;
float clampedPitch = Mathf.Clamp(currentPitch, -89f, 89f);
if (currentPitch != clampedPitch)
{
currentEulerAngles.x = clampedPitch;
transform.localEulerAngles = currentEulerAngles;
}
}
i missed a line break in there between :
transform.RotateAround(transform.parent.position, transform.parent.right, camPitchDelta)
Vector3 currentEulerAngles = transform.localEulerAngles;
sorry
how do i set parent after instantiating an object on photon network?
isn't this just the exact code I just posted, without the commented out regions?
sorry i went for drinks with a mate of mine:
private void UpdateRotationNew()
{
float camYawDelta = LegacyInput.GetLookInput().y;
float camPitchDelta = -LegacyInput.GetLookInput().x;
// targ rotation
Quaternion targetRotation = transform.rotation * Quaternion.Euler(camPitchDelta, camYawDelta, 0);
//rotate toward target
float rotationSpeed = 5f; // Adjust this value to change the speed of rotation
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
// Ensure the camera pitch stays in range
Vector3 currentEulerAngles = transform.localEulerAngles;
float currentPitch = currentEulerAngles.x;
float clampedPitch = Mathf.Clamp(currentPitch, -89f, 89f);
if (currentPitch != clampedPitch)
{
currentEulerAngles.x = clampedPitch;
transform.localEulerAngles = currentEulerAngles;
}
}
if its not this im afraid im not sure, i'll be more than happy to try help you find tutuorials?
don't worry about it. I can't seem to find what I'm looking for so I'll go see if I can scout it somewhere else
im sorry mad man
I made an interface IColorSelectorCallback.
My idea is to open a color selector pannel with OpenColorSelector(IColorSelectorCallback callback)
And do this using a Button's UnityEvent.
However, the method that takes a IColorSelectorCallback as an argument, doesnt show, because interfaces cant be put into GameObject slots in unity.
What would be the way to do this? Do I need to create a MonoBehaviour for the callback?
do it all with scripts, without using editor assigned button events
seems a bit annoying, because I would have to create one method in each monobehaviour that calls the color selector
but I guess there is no other way
you could also not use an interface
what would that fix?
I am making a 2 player game
I want the users scores to be on the left side and the opponents score on the right side
I am spawning both the scores
How do I seperate them?
I presume they're on a canvas.
I'd just set the player's score to be anchored to the top left and the enemy's score to be anchored to the top right, then set their positions to put them in a reasonable place
I guess you could use a layout group to automate that, but it's hardly necessary for just two things
the enemy is another player
It's multiplayer
So they are spawning together
I am trying to use ismine
But can't figure it out
israeli devs?
Has anyone come across this before?
Building Library\Bee\artifacts\Android\iz17e\libil2cpp.so failed with output:
ld.lld: error: undefined symbol: GADUGetAdErrorCode
I've reimported, deleted library, resolved dependencies, I even made while new project and took everything over one by one
linker error!
i've never done android development tho
it's failing to find a definition for some of the Google Ads stuff
Yeah I've tried to reimport all that, and updated it even but same shyte
You're better off storing editor specific scripts in an Editor folder. Unity will not compile these in a build, due to obvious reasons.
Considering this whole script appears to be for the editor (assuming that directive has no end)
how do i convert this json text to a nest list? (list<list<object>>)
{"data": [[0, 0, "Example String", "Example String2", 1.4, 2.4, 5, 2, 14, 4.5]]}
to
list<list<object>> exlist = [[0, 0, "Example String", "Example String2", 1.4, 2.4, 5, 2, 14, 4.5]];
it should convert itself depending on which package you're using 
Use a Json serialization library
trying to use JsonUtility.FromJson
but I really, really, really recommend NOT having a "mixed" list of objects
that contains both strings and numbers for example
Unity's JsonUtility cannot handle naked collections or nested collections
it needs wrapper objects
so what library should i use?
newtonsoft 
ok thanks
windows -> package manager -> search it there
thanks but it was built-in to unity
@leaden ice got a question about the newtonsoft btw. it isn't able to serialize ScriptableObject is it?
yes it can
It can serialize anything you want as long as you follow its serialization rules
namely the [JsonObject] and [JsonProperty] attributes and their various settings, the serializer settings, etc..
hm i mean it can't serialize a monobehaviour, i was just wondering if an SO could be serialised cuz i need to save some data and they are in a SO
it can serialize a MonoBehaviour, or at least the managed parts of it, as long as you follow its serialization rules. Doesn't mean it's a good idea though.
an SO is not an MB
In any case I recommend using Memento objects though
totally don't want to tho. Too much data that doesn't even need to be saved
but my problem rn is thata part of my save file will need data from an SO obj
that's why you use the OptIn mode of JsonObject and use JsonProperty to mark the specific things you want to serialize
Shameless plug, check out ScriptableObject Pro on the asset store
when saving the game - copy the exact data you want into your saved game data.
will do later with the team
wait i'll send the way i'm saving data so you have an idea +/- and if it is possible to handle the SO, 1 sec
DataManager has these:
public static void SaveData<T>(DataType key, T data)
{
if (instance._saveData.CheckData(data))
instance._saveData.ChangeData(key, data);
else instance._saveData.ChangeData(key, data);
Debug.Log("Hey Time to save!");
Debug.Log(instance._saveData._saveData.Keys.Count);
Save();
}
public static void Save()
{
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto, Formatting = Formatting.Indented, ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
Debug.Log("saving..");
//Serialize the save data
string jsonString = JsonConvert.SerializeObject(instance._saveData, settings);
WriteSaveFile(jsonString);
}
private static void WriteSaveFile(string saveFile)
{
// Combine the save file path and file name
string saveFilePath = $"{s_filePath}saveGame.json";
if (!Directory.Exists(s_filePath)) Directory.CreateDirectory(s_filePath);
Debug.Log("No Directory.. Creating..");
if (!File.Exists(saveFilePath)) File.Create(saveFilePath).Dispose();
Debug.Log("No File.. Creating..");
// Write the serialized save data to the file
File.WriteAllText(saveFilePath, saveFile);
Debug.Log("Saved!");
}```
`_saveData` is a class on it's own that has a dictionary and some methods:
```csharp
public Dictionary<int, object> _saveData;
public bool CheckData<T>(T data) => data != null ? true : false;
public void AddData<T>(DataType key, T data) => _saveData.Add((int)key, data);
public bool CheckKey(DataType key) => _saveData.ContainsKey((int)key) ? true : false;
public bool CheckType(DataType key) => Enum.IsDefined(typeof(DataType), key) ? true : false;
DataType is an enum that serves as the key btw.
the info i'm trying to save that is the SO is something like this this one:
public class ShelterBuildingSO : ScriptableObject
{
public BuildingStatus buildingStatus;
public int buildingLevel;
public int buildingCondition;
public List<ShelterBuildingActivitySO> activities = new List<ShelterBuildingActivitySO>();
}
public class ShelterBuildingActivitySO : ScriptableObject
{
[SerializeField] public int nSurvivorsNeeded { get; private set; }
[SerializeField] public float baseTimeToCompleteInMinutes { get; private set; }
public string effectDescription;
}```
Sorry, but that is horrible
i'm lazy to type 0, 1, etc 
not the enum, the rest of the code
oh? how so?
To start SaveData<T> is a single file, what if you want to save multipe objects?