#archived-code-general

1 messages · Page 74 of 1

wild pivot
#

if its not the move player function, speed control function or line 99. Then its going to be the section where you alter rigidbody drag

#

actually, its the drag section i believe. Comment lines 48 to 51

full rune
wild pivot
full rune
wild pivot
#

sure

dry widget
#

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.

wild pivot
dry widget
#

is that true in other engines & languages too?

wild pivot
#

not a clue

#

depends if they have raycasting and layermasks lol

dry widget
#

alright, thanks anyway :)

full rune
wild pivot
#

what exactly happends when you jump, could you send me a video or something?

full rune
#

alr

full rune
wild pivot
#

yep

fallen lotus
#

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

thin aurora
#

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

lean seal
#

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?

mental rover
high violet
#
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"

static matrix
#

Is it possible to change a builtin button's OnClick via script?

static matrix
#

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

high violet
fallen lotus
tired drift
#

Hey hey guys has anyone every used Newtonsoft with unity? I'm having some issues but idk if i should post my question here

tired drift
#

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

somber nacelle
#

probably due to serializing an entire monobehaviour

polar marten
#

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

tired drift
polar marten
#

phew

somber nacelle
polar marten
#

i am really surprised it is glitchy for you

spiral geyser
#

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)

polar marten
spiral geyser
#

Okay thank you

high violet
tired drift
polar marten
#

i don't think that's true

tired drift
polar marten
#

you might have another bug

polar marten
high violet
polar marten
#

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

tired drift
polar marten
#

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

tired drift
#

Which doesn't inherit monobehaviour

polar marten
high violet
polar marten
#

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

tired drift
#

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.

polar marten
#

then call jsonconvert on instances of X instead of instances of MyMono

polar marten
#

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

tired drift
polar marten
#
// 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

tired drift
polar marten
#

yeah i know

#

you see why this is barf though right

#

you're just reinventing a class

#

it provides no value

tired drift
#

yeah in a way

polar marten
#

it feels like it provides value, it actualyl is anti value

tired drift
#

i know what you mean tho

polar marten
#

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;
}
tired drift
#

kek 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)

polar marten
#

you can make them setters too

polar marten
#

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

tired drift
#

I'm using VS Enterprise actually

polar marten
#

sick

tired drift
#

i think it has resharper

polar marten
#

yeah so you'll be able to do this all

#

okay gotta go

tired drift
#

ty for the explanation btw, very much obliged ^^

proper pier
#

how is it possible that I am getting this error if I am specifically returning beforehand

somber nacelle
proper pier
#

oh ok, ty

buoyant crane
proper pier
#

Atan is arc tan right?

proper pier
buoyant crane
proper pier
#

the code functions properly as long as z/x does not equal undefined

buoyant crane
#

the difference is that Atan2 covers more cases than the regular Atan

proper pier
#

is there any downside to using Atan2 over Atan

buoyant crane
proper pier
#

ok

#

ill try it

#

thanks

#

ok, I added both suggestions and it seems to work now, thanks

mystic ferry
#

does LoadSceneMode.Single destroy DDOL objects?

light jay
#

Can i use Starter Assets - First Person Character Controller | URP with a normal 3D ( so a non URP )

weary cloud
#

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?

mystic ferry
weary cloud
mystic ferry
#

destroying objects creates garbage so don't forget object pooling

lavish mist
#

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?

frosty creek
#

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 ?

gray thunder
#

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

frosty creek
#

@gray thunder This sounds confusing, but it worked thank you 🙂

gray thunder
#

Yeah I know lol

#

Ive had this is older versions of unity

#

and assuming ur using a newer one,

#

unresolved still sadly

steady moat
# lavish mist hi everyone. So i have multiple prefabs of the same in my scene, each one with a...

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:

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.

frosty creek
gray thunder
#

Yupp

#

Though as mentioned before, the Smart 2D lighting asset is pretty good too

gray thunder
primal marlin
#

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

frosty creek
primal marlin
#

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

frosty creek
primal marlin
#

100%

#

heres a video

hexed oak
#

How do I make sure Quaternion.Slerp always moves in one direction?

steady moat
#

Nvm, I understand.

hexed oak
#

Yeah if I get a value over 180 it slerps backwards, but I want it to always rotate in a specific direction

steady moat
#

Quaternion.Slerp will always go towards the shorter direction.

#

You will need to use other means of rotation.

hexed oak
#

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

primal marlin
hexed oak
#

and I'm struggling with the frame by frame calculations for how that would work

steady moat
#

You could recalculate the difference between your desired rotation and your current rotation each frame.

primal marlin
steady moat
# primal marlin

Usually, player controllers are made as Kinematic to prevents such issue.

primal marlin
#

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

primal marlin
steady moat
#

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.

hexed oak
#

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; }

primal marlin
hexed oak
#
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

steady moat
# hexed oak ```cs void Start() { StartCoroutine(Lerp()); } IEnumerator L...

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.

hexed oak
#

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

steady moat
hexed oak
#

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 🙂

hexed oak
wise hollow
#

If(I==null) yield break; Will this colse the if statement or the entire coroutine. I want to only close the statement.

steady moat
sonic zinc
#

why is everything going red?

steady moat
steady moat
sonic zinc
#

oh duh, idk how I didnt notice I was doing that

hexed oak
#

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

cerulean mist
#

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!

short crypt
modest pawn
#

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 :

modest pawn
#

Just a moment !

#

Turns out the Message property is what I provided

steady moat
# modest pawn

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.

tardy beacon
#

is there a way to write onto a cmd file? just trynna see if its possible

plucky karma
tardy beacon
#

you can have a file with .cmd at the end

#

same at .bat

#

it seems

plucky karma
#

That's just called extension. .bat works for windows, whereas .zshc or .sh works for mac/linux.

tardy beacon
#

ok

warm shadow
#

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:

mossy snow
#

how many verts? maybe exceeding 65536

warm shadow
#

What limit is 65536?

warm shadow
#

ah, that's probably it

#

so how would i go about changing it to a 32bit?

#

nvm i found it

#

thanks for the help : )

worthy timber
#

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

thin aurora
upper crypt
uncut vapor
#

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
copper shoal
#

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");
        }
    }
}
dusk apex
#

Log the tile position and see if it's what you're expecting.

jovial meadow
dusk apex
jolly plank
dusk apex
#

Likely you're attempting to access the rigid body property from Game Object that's been removed quite a while ago.

jolly plank
#

setTile should print if the cell value is incorrect, indirectly assuring worldtocell is correct

#

therefore set tile is broken

jolly plank
#

if that position is valid, then the problem is setTile

dusk apex
#

Was that the correct position?

copper shoal
#

Yes

#

wait, no

dusk apex
#

Log the tile before and after setting to null.

copper shoal
#

it's a tile to the left

jolly plank
jolly plank
#

if it is out of range, you'd get an object null reference error anyway

copper shoal
#

Okay, it sometimes cashes the tile before the tile with the collider for some reason

dusk apex
uncut vapor
copper shoal
#

which is weird, because the trigger is only set to 252 one

dusk apex
jolly plank
#

oh wait

#

i get u

uncut vapor
jolly plank
#

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

uncut vapor
#

...
Is there any way to serialize all and any datatype?

dusk apex
#

Save the data you're wanting. Not the component.

#

Although, it should also be noted that rb property has been deprecated.

uncut vapor
#

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

leaden ice
#

You can either switch to a Serializable Dictionary implementation or a different serializer such as Newtonsoft json

#

Dictionary<string, object> is sus though

uncut vapor
#

I am using newtonsoft
But it shows an error
That's what I'm here about

leaden ice
#

What error

stable rivet
leaden ice
#

We cannot read minds

uncut vapor
#

I did
Scroll up
please

leaden ice
# uncut vapor

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

uncut vapor
leaden ice
#

I wasn't here chill

stable rivet
uncut vapor
#

Okay sorry

leaden ice
#

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

uncut vapor
#

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

leaden ice
#
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

uncut vapor
#

Uhh how do I do it with newtonsoft then?

uncut vapor
#

Okay, thank youu

summer sable
#

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.

fleet furnace
steady moat
# summer sable Hello! We've reached the point where we would like to split our codebase into as...

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.

summer sable
# fleet furnace Start with a proper folder structure. After that I would go with trial and error...

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.

uncut vapor
uncut vapor
#

Ye I still don't get it

steep sky
#

can someone tell me how to rotate gamobject to look at rightstick in 2d?

steady moat
# summer sable We do have a proper folder structure at least, but unfortunately there's always ...

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.

dim spindle
#

the what

#

screaming architecture

steady moat
#

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.

dim spindle
#

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

steady moat
#

If I am there. There is a lot of other people that understand such advance concept.

summer sable
# steady moat What you are missing might be the usage of interface. Look into Dependency Inver...

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.

full rune
#

can anyone help me

#

Every time i go on a cube while playing my game, i cant move

rustic ember
#

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?

summer sable
#

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.

steady moat
# summer sable As for Interfaces - I've always liked using them, but stopped because of Unity a...

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.

full rune
#

hey can anyone help me with something. Im sure its simple i just cant find the solution because im pretty new

dim spindle
full rune
#

what do you mean

full rune
#

do you know whats going on Ultra?

dim spindle
#

no because i dont have access to your project

steady moat
full rune
#

I could show you my script

dim spindle
dim spindle
summer sable
# steady moat Unity now support Interface with SerializeReference, where it is true that it is...

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.

full rune
dim spindle
dim spindle
#

@steady moat how does this look

#

some of the boxes arent super important

#

you might need to open the link

steady moat
#

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.

jovial turret
#

anyone wanna partner up

native folio
#

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?

steady moat
#

!collab

tawny elkBOT
jovial turret
#

oopsies

#

mb mb

primal marlin
#

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);
    }
}
tawny elkBOT
#
Posting 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.

buoyant crane
dim spindle
# steady moat It is kinda hard to follow as you are leaving a lot out. But here what I can rap...

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!

primal marlin
#

player movement

elfin tree
#

Using FormerlySerializedAsAttribute, do I need to leave it in? Or once the fields are detected in Unity it can be removed?

dim spindle
#

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

steady moat
#

After reading a bit more, you should simply it to be something of the ampler of the ServiceLocator.

dim spindle
#

alright I'll look into that

steady moat
#

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.

buoyant crane
dim spindle
lean seal
#

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;
    }```
primal marlin
primal marlin
#

ok ok ill try that thanks

granite nimbus
#

are static constructors called before Awake()?

steady moat
dim spindle
#

alright, time to refactor

steady moat
#

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.

https://www.geeksforgeeks.org/benefit-of-using-mvc/

lucid valley
primal marlin
granite nimbus
fervent furnace
#

i have a class which has a static constructor, it is called in edit mode once it has been changed or created

granite nimbus
fervent furnace
#

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

granite nimbus
#

I think we are talking about different things, I believe C# static constructors are 100% called runtime, not after compilation

lucid valley
#

so runtime

granite nimbus
lucid valley
#

when you try to access the static class for the first time the JIT will run the static constructor

#

is my understanding

fervent furnace
#

yes, i test it now, called after compilation is done
the simplest way to verify is to have a try

granite nimbus
#

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?

#

🤨

fervent furnace
#

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

candid trench
#

If i have a SortedDictionary<float,MyClass> and dont specify any IComparer<T>. Does it default to sort the float -keys in ascending order?

lucid valley
leaden ice
#

And yes that would result in ascending order by value of the keys

granite nimbus
leaden ice
#

It's also pretty sketchy to use float as a dictionary key because of precision error so be careful

lucid valley
candid trench
#

actually,there's probably a better way to do this now that i think of it.

lucid valley
#

it is worth saying that playmode != the runtime, it just gets reset with a domain reload when you play. Editor is also a runtime

granite nimbus
granite nimbus
#

makes sense

candid trench
#

Also, whats the difference between new KeyValuePair<int,int>(5,5) and KeyValuePair.Create(5,5) ?

candid trench
#

just fewer keystrokes? x)

lucid valley
#

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)

candid trench
#

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

lucid valley
#

think it is

zealous dawn
#

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

mystic ferry
#

did you guys know you can reorder objects in the hierarchy via code? wtf

zealous dawn
#

The flicker/artifacts are entirely intermittent as well, which makes debugging very challenging 😅

#

I wonder if it has to do with the depth

plucky karma
dim spindle
#

just set execution order

plucky karma
#

This goes the same for Audio stack as well! Beware! OnAudioFilterRead reads in the order of the component order of your gameobject!

mystic ferry
plucky karma
# dim spindle please dont rely on that

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 🙂

uncut vapor
#

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

potent sleet
#

put some effort into it

uncut vapor
potent sleet
uncut vapor
#

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?

potent sleet
#

this discord looks down on laziness

#

google it then or use gpt

plucky karma
#

People who refuse to google and ask for resource on discord is frown upon.

Just like how people asked us to correct ChatGPT answer.

uncut vapor
#

I DID
I GOT NOTHING

elfin scroll
#

is there a way to trigger oncollisionenter like a function?

potent sleet
#

I get literally thousands of results.. how can that be ?

uncut vapor
plucky karma
#

Maybe you didn't google it correctly 🤷‍♂️ Plenty of resources online on how to properly serialize and deserialize your script.

uncut vapor
potent sleet
#

🤷‍♂️

potent sleet
uncut vapor
elfin scroll
uncut vapor
#

please

gleaming sparrow
#

Gotta pay him 10$ first for the effort

potent sleet
potent sleet
elfin scroll
#

well all of them update when one calls oncollision

plucky karma
elfin scroll
#

every single conveyor in the scene

#

because all of the collision boxes are overlapping

#

and so they rotate again

plucky karma
#

OnCollisionEnter invokes when your object collides with another object containing rigidbody. No need to invoke the method directly.

potent sleet
plucky karma
#

The engine will invoke the method for you.

elfin scroll
#

and also when i place a new one it immediately turns to face the last one in the chain

plucky karma
uncut vapor
# potent sleet show what you tried and I'll believe you

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

elfin scroll
#

im not explaining this very well

potent sleet
#

then replicate the object

uncut vapor
#

Alright
Still how do I save the data

potent sleet
#

You write the serializable class you got into a json or similar file

#

I use .bin if i wanna save space

uncut vapor
#

Specifically how do I save the values of a component

potent sleet
uncut vapor
#

That's what google says
And that's why I couldn't find nothing
Cuz I need it to work universally, for any component

plucky karma
# elfin scroll im not explaining this very well

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.

potent sleet
plucky karma
#

The idea here is that you shouldn't invoke Unity's protected method, but you can invoke implicit method.

plucky karma
plucky karma
#

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.

potent sleet
#

is just 3 floats

#

you get the idea

plucky karma
#

I think you need to learn C# in general before you ask us what primitive type is.

uncut vapor
potent sleet
#

also if you were more clear on specifically what from the gameobject you wanna store..

uncut vapor
potent sleet
#

how's it a custom script without knowing the variables.. that makes no sense

uncut vapor
#

I just need it to work automatically and universally for anything

potent sleet
#

you seem to be jumping ahead of your current skillset

gleaming sparrow
#

What does it need to do in the first place

potent sleet
#

"future proof something without knowing what IT is"

gleaming sparrow
#

U wanna have serializable class with json?

uncut vapor
potent sleet
#

you need to learn how to tailor data

uncut vapor
#

Wdym

gleaming sparrow
#

what do u wanna make

potent sleet
# uncut vapor Wdym

like how to pass data around to fit a specific need? that includes serializing stuff

uncut vapor
gleaming sparrow
#

Cant u save into a prefab

uncut vapor
potent sleet
#

you want 1 button that saves all the shite for you like magic..

#

someone needs to make it happen cause it ain't magic

uncut vapor
gleaming sparrow
#

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

potent sleet
#

You cant serialize a prefab itself into a file though

uncut vapor
#

Isn't a prefab itself a file
So can't you just copy it

potent sleet
#

It's a YAML file

#

iirc

uncut vapor
gleaming sparrow
#

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

uncut vapor
#

Yes

gleaming sparrow
#

Yes to which

potent sleet
uncut vapor
potent sleet
#

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

#

you should have some type of understanding

uncut vapor
#

I know what primitives are
Ffs it's not my first time coding

potent sleet
#

so far you're coming off that way as you're not understanding why you don't serialize gameobjects

uncut vapor
potent sleet
#

explain what "universally" is, maybe I'm inept here..

uncut vapor
potent sleet
#

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..

uncut vapor
#

Okay is there a way to save any values of any component and any variable of any type

uncut vapor
potent sleet
#

like what ?

uncut vapor
#

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

tepid river
#

doesnt exist, cant work

#

theres no "universal save solution"

potent sleet
#

then you Load the data

#

from each object

uncut vapor
#

???

tepid river
#

stop spoonfeeding and google "serialization".

potent sleet
#

they did google, and apparently found NOTHING

tepid river
#

haha

#

did they use bing

potent sleet
#

hell even GPT can explain this shit with code examples..

#

they are just lazy and "want script plz"

uncut vapor
#

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

stable rivet
tepid river
#

you need to go back and watch 5 hours of youtube tutorials, and then come back with a specific question

potent sleet
#

this ain't a tutoring site

uncut vapor
potent sleet
#

the knowledge is out there, put a little effort don't be lazy

uncut vapor
#

I'm not
I'm just fucking stupid
Just tell me and I'll stop as you called it trolling

stable rivet
potent sleet
#

^

tepid river
#

yeah thats it

stable rivet
#

take a breath and relax

uncut vapor
#

I tried for HOURS
About 18h now

stable rivet
#

you need a break

uncut vapor
#

To find something

stable rivet
#

everyone has times where they feel like they cannot figure their problem out - you just need a break

uncut vapor
#

I will if you just tell me how do this come on

potent sleet
#

yeah go paint a picture or something, then come back with fresh mind

fervent furnace
#

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

stable rivet
uncut vapor
#

Just please
Please
Please
If it's so obvious
Then just tell me

potent sleet
tepid river
#

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?

wheat rain
#

dont bully

tepid river
#

yeah sorry

uncut vapor
stable rivet
# uncut vapor Just please Please Please If it's so obvious Then just tell me

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

rustic ember
#
    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
wheat rain
#

i have never seen mouse input inside a coroutine before

sage latch
#

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

modest pawn
#

@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.

sage latch
#

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

wheat rain
#

how do i use List.Remove() to remove the first entry on a updating list?

potent sleet
#

does First() not work?

buoyant crane
wheat rain
potent sleet
#

I'm spoiled with LINQ now

#

xD

wheat rain
#

i suppose the next value will then becomes 0?

buoyant crane
#

indeed

wheat rain
#

hm, says it cant convert from int to vec3

potent sleet
tropic sleet
#

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 🙂

eager citrus
#

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

leaden ice
eager citrus
leaden ice
#

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

eager citrus
#

how do i do that

leaden ice
eager citrus
#

i followed the instructions but the error persists any idea why

leaden ice
eager citrus
#

ill retry and ill let you know

eager citrus
#

i got 648 errors sadok

leaden ice
#

where

#

the number of errors is really pretty meaningless

eager citrus
leaden ice
#

obviously in the console

#

I mean

#

what are the errors

eager citrus
#

and basically every other package i have installed

leaden ice
#

From where do they originate

eager citrus
leaden ice
#

such as?

eager citrus
leaden ice
#

Looks like you've done something very wrong

#

packages should be installed from the package manager

eager citrus
leaden ice
#

I would delete all of those packages you have in Assets/Scripts

#

install them from the package manager

eager citrus
#

k

night cloak
#

I added the netcode for gameobjects package, but I get this error, what does this mean and how can I fix this?

weak vapor
#

anyone know how i can realize what i'm going for here?

#

operator + cannot be applied between types T and T

heady iris
#

T is a completely unconstrained type

#

You can't add most things together.

weak vapor
#

wondering if i should just make a unique class for each value type im interested in, or have overflows somehow within this generic type?

heady iris
#

you will need to constraint T

weak vapor
heady iris
#

unfortunately, I don't think there's a really nice way to do this in C#

weak vapor
#

eg, in the case that values will only ever be basic value types

#

(int, float, etc)

heady iris
#

it'd be easy in Haskell, but alas :p

leaden ice
#

well in the newest version of C# that Unity can't use there's the INumber interface, RIP

heady iris
#

ooh

#

that'd be what you want

weak vapor
#

well dang then lol

#

multiclasses and overflows it is

#

but thanks very much for the help yall

heady iris
#

I think you're looking for "overloads", not overflows :p

weak vapor
#

yea lol, my bad

leaden ice
#

Actually think you're looking for override in this case?

weak vapor
#

have been using overflow as a feature lately so it's a freudian

heady iris
weak vapor
#

no in this case it would be overloads (multiple same-named functions with different params to handle different cases)

heady iris
#

i guess that works

weak vapor
#

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)

steel vortex
leaden ice
steel vortex
steady moat
warm fractal
#

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

plush sparrow
#

If I store multiple gameobjects under a single tag

#

How can I acces those game objects individually from that tag?

potent sleet
plush sparrow
#

And how do you use
FindGameObjectWithTag
To find a tmpro textfield with a tag?

potent sleet
potent sleet
#

drag the component in here ^

#

in inspector

plush sparrow
#

That's what

#

I don't want to use drag

#

How do I set it via script?

potent sleet
plush sparrow
#

Because I am making a prefab of it
Drag and drop references are losing

potent sleet
plush sparrow
#

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

potent sleet
#

it's very simple
make script type and spawn the prefab as that type then use it via script

plush sparrow
#

Can you show me how?
You can explain or send some link explaining it

#

Cause I am not understanding properly how to do that

potent sleet
# plush sparrow Can you show me how? You can explain or send some link explaining it

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...

▶ Play video
#

you can just spawn it as that type when you spawn the prefab, no need for GameObject type tbh

plush sparrow
#

Can you give an example?

#

Just the spawning part

#

Like the line for spawning what would you write?

potent sleet
plush sparrow
#

Ah

#

So even if it's public drag and drop
It won't lose the reference?

potent sleet
potent sleet
#

Pretend Tee is script on the prefab

#

and AnotherClass is when you spawn prefab

swift falcon
#

I was looking at the App manifest file in my Unity project and saw this

This means Unity games have admin rights by default??

weary cloud
#

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

swift falcon
steady moat
potent sleet
#

in HTML**

#

or XML

swift falcon
#

Yeah

weary cloud
potent sleet
weary cloud
plush sparrow
#

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

steady moat
# swift falcon Yeah

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.

potent sleet
#

spawn the prefab with canvas that has text then

#

or don't control scene text through prefab, thats silly anyway

plush sparrow
#

then?

potent sleet
#

huh?

plush sparrow
potent sleet
swift falcon
plush sparrow
potent sleet
#

like canvas with certain text can be part of the prefab

#

this isn't a good usecase though it seems

plush sparrow
#

what to do then?

potent sleet
#

I told you what to do, only have the scene object control the TMP text

#

why does prefab have text components

plush sparrow
#

it shouldnt?

potent sleet
#

not scene ones

#

only if it's self contained canvas

plush sparrow
potent sleet
#

You've yet to clarify why TMP text is inside prefab

plush sparrow
#

the prefab changes the value of the text

potent sleet
#

why

#

doesn't have to

plush sparrow
#

so it has a reference of the text, to show the changed value

#

how else will i refer the text to change the value?

potent sleet
#

you only stream the changed value to an object in scene that processes that value

plush sparrow
#

the prefab processes the value

#

prefab is a dice, the dice value is shown in the text

potent sleet
#

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

plush sparrow
#

even then its the same thing?

potent sleet
#

no

plush sparrow
#

the class has to send the value to the text

potent sleet
#

we clearly have a miscommunication here

#

the prefab literally has to reference 0 things in the scene

plush sparrow
#

ok

#

i understand you are correct. like what should i do then?

potent sleet
#

then update the text with that scene script

#

i showed you how you can pass the dice into another class on spawn

plush sparrow
#

like have a game manager object with the script?

potent sleet
#

or DiceManager

#

since it deals with dice

#

or sum

plush sparrow
#

ok

#

and the dice manager will have reference to the text as well as the dice prefab?

plush sparrow
#

ok thanks

potent sleet
# plush sparrow 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
plush sparrow
#
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?

potent sleet
#

in scen eyes

#

scene yes*

plush sparrow
#
public class Dice: MonoBehaviour
{
    
    public int RollDice()
    {
        return Random.Range(0, 7);
    }
}
``` and this in dice object?
#

alright thanks!!

potent sleet
#

yeah fixed my typo, 0 should be 1 but you get the point i think

plush sparrow
#

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

woeful furnace
#

Does anyone have a script which gets all the integer vector3's in an object.

buoyant crane
woeful furnace
#

Im trying to get all the points in an object so I can run them through a marching cubes algorithm.

buoyant crane
#

@woeful furnace I’m still not sure what values you’re trying to retrieve

woeful furnace
# buoyant crane <@476428898821734421> 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.

buoyant crane
woeful furnace
#

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.

kind depot
#

can you install nuget packages to unity?

potent sleet
#

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

woeful furnace
#

I am writing up what im thinking on paper

buoyant crane
woeful furnace
#

Btw chicken scratch

woeful furnace
#

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.

buoyant crane
woeful furnace
#

Yes because marching cubes will use the number as corner for the cubes

buoyant crane
# woeful furnace 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

woeful furnace
#

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

woeful furnace
#

So each layer is just the topdown view or slice.

buoyant crane
#

yes

woeful furnace
#

I want it to work with any shape

buoyant crane
# woeful furnace 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

woeful furnace
#

Alright I see

plush sparrow
#

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?

leaden ice
plush sparrow
#

idk how to convert transform to textmeshprougui

leaden ice
#

GetChild returns a Transform.
Your variable type is TextMeshProUGUI.

leaden ice
#

You use GetComponent to get components attached to GameObjects

potent sleet
leaden ice
#

You don't "convert" anything

plush sparrow
#

but this is different

potent sleet
#

dont have spawned prefabs control UI in the scene

plush sparrow
#

no no, the dice manager is controlling it

#

the dice managaer is not spawned

#

but i will spawn the scores as well

potent sleet
plush sparrow
#

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

potent sleet
plush sparrow
#

so i need a run time reference to the scores

#

its on PUN

potent sleet
#

do the same thing tho, you pass the data to the script that handles the scene UI and stuff

plush sparrow
#

i am doing that

#

TextMeshProUGUI ones = GameObject.FindGameObjectWithTag("scores").transform.GetChild(0);

#

but dont know how to fix this

potent sleet
#

and you're looking for TextMeshProUGUI

potent sleet
#

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

plush sparrow
#

oh thanks this solves it

plush sparrow
exotic burrow
#

what's the difference between (float, float) and float

kind depot
#

(float, float) is probably vector2

potent sleet
#

probably a tuple

potent sleet
exotic burrow
#

thanks

woeful furnace
#

Finally got an implemenation using my raycasting method pretty fast and happy with the results.

soft wave
#

(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
potent sleet
soft wave
#

yeah
i get the error message for all mesh colliders in an ISD

#

actually no, almost all of them

potent sleet
#

if ISD is some type of asset it sounds like it came broken or something

#

not sure tbh

soft wave
#

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

fluid lily
#

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.

fluid lily
#

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

stiff rain
#

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.

olive shore
# stiff rain sorry to budge in but I have a quick question. I want to have my first-person ca...

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

tawny elkBOT
#
Posting 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.

stiff rain
stiff rain
# olive shore Hey, I think I have a solution for you! Try updating your UpdateRotation() funct...

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.

olive shore
quartz folio
stiff rain
#

yeah that probably explains why I can spin it

olive shore
#

mmm

quartz folio
#

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

olive shore
#

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

plush sparrow
#

how do i set parent after instantiating an object on photon network?

stiff rain
olive shore
# stiff rain 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?

stiff rain
#

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

olive shore
#

im sorry mad man

cerulean oak
#

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?

cold parrot
cerulean oak
#

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

cold parrot
cerulean oak
#

what would that fix?

plush sparrow
#

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?

heady iris
#

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

plush sparrow
#

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

tropic kraken
#

israeli devs?

olive shore
#

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

heady iris
#

linker error!

#

i've never done android development tho

#

it's failing to find a definition for some of the Google Ads stuff

olive shore
#

Yeah I've tried to reimport all that, and updated it even but same shyte

thin aurora
#

Considering this whole script appears to be for the editor (assuming that directive has no end)

kind depot
#

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]];

tired drift
#

it should convert itself depending on which package you're using concernedfrogstare

leaden ice
kind depot
#

trying to use JsonUtility.FromJson

leaden ice
#

but I really, really, really recommend NOT having a "mixed" list of objects

#

that contains both strings and numbers for example

leaden ice
#

it needs wrapper objects

kind depot
#

so what library should i use?

tired drift
#

newtonsoft SipRondo

kind depot
#

ok thanks

#

how do you install a nuget package to unity?

tired drift
#

no need to

#

unity has one of it's own

kind depot
#

ok thanks

tired drift
#

windows -> package manager -> search it there

kind depot
tired drift
#

@leaden ice got a question about the newtonsoft btw. it isn't able to serialize ScriptableObject is it?

leaden ice
#

namely the [JsonObject] and [JsonProperty] attributes and their various settings, the serializer settings, etc..

tired drift
#

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

leaden ice
leaden ice
#

In any case I recommend using Memento objects though

tired drift
#

but my problem rn is thata part of my save file will need data from an SO obj

leaden ice
#

that's why you use the OptIn mode of JsonObject and use JsonProperty to mark the specific things you want to serialize

knotty sun
leaden ice
tired drift
tired drift
#

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;
}```
knotty sun
tired drift
leaden ice
#

Why Dictionary<int, object>

#

that's... so generic as to be mostly useless

knotty sun
tired drift
knotty sun
#

To start SaveData<T> is a single file, what if you want to save multipe objects?

tired drift
#

SaveData is saving all the objects to be serialized

#

GameData is the file that contains a dictionary. the dictionary then receives a key, and whatever it needs to be serialized