#archived-code-general

1 messages · Page 194 of 1

leaden ice
#

there might be

#

profile it and find out

#

however I think it's probably better to rely on trigger colliders or physics queries or something of that nature rather than looping through all enemies

gleaming imp
#

class variables automtically show in editor under the script or need the serializevalue ?

leaden ice
#

Only one of the two is needed

gleaming imp
#

ty

leaden ice
#

They also need to be:

  • fields
  • of a type that is serializable
gleaming imp
#

they were showing in editor but the code didn´t have the [SerializeField] attribute

leaden ice
#

They'd have been public then

#

Or your inspector is in debug mode, or you're using Odin or similar

gleaming imp
#

but now i need to reload the scene withoutn reseting them so i can play with the values during gameplay

#

SceneManager.LoadScene(SceneManager.GetActiveScene().name);
this reloads the init values

#

how do you prevent that

leaden ice
#

I mean that loads the scene fresh

#

The existing objects are destroyed entirely

#

If you want to save data between scenes you'll need to actually save the data somewhere external to the scene

#

DDOL objects are one option

gleaming imp
#

i tried that but i think it´s done incorrectly

#

i just added
private void Awake() { if (!_created) { DontDestroyOnLoad(this.gameObject); _created = true; //Init(); } }

leaden ice
#

you should look into the Singleton pattern

gleaming imp
#

headache intensifies

#

so it seems like this code is spagethi and adding singleton is pain

#

all the variables are in the player script and they should be on their own singleton class

strong nimbus
#

Hi, very confusing question so I made a picture. But basically I wanna know how to get a vector3 direction from a gameobjects transform.position to its rigidbody's position?? I tried:

´´´launchDirection = rb.position - transform.position;´´´

but it didn't work, it gave me a result of (0,0,0)

leaden ice
strong nimbus
strong nimbus
#

Interesting! I will try it out

leaden ice
#

idk your picture doesn't entirely make sense to me

#

what are you actually trying to do

strong nimbus
#

like I imported a model from blender where the origin of the mesh isn't in the center of the actual mesh, so it rotates around an invisible pivot

#

this is because the model is part of many different models, a sort of collection

leaden ice
strong nimbus
#

but then when I click a button I want the model part disband from the collection in the direction away from the collection

swift falcon
#

What is the difference between "WasPressed" and "WasPerformed" in the new unity input system?

strong nimbus
#

yeah I thought about that but I have so many meshes part of a collection that it would take ages, so I need a general script to do it for me

strong nimbus
#

I need it to be aligned specifically with the help of the pivot (so it looks like it is part of the collection of models in a very specific manner)

#

because from blender all the parts have the exact same origin (which is the transform.position, the orange part in the picture)

#

but I'll try center of mass

leaden ice
#

so it'd be:

Vector3 worldCenterOfMass = transform.TransformPoint(rb.centerOfMass);``` To get it in world space
swift falcon
strong nimbus
final dragon
#

Hey guys, could someone assist me with my code? I have a deadline coming up this Friday, and I'm running out of time to complete the assignment.

strong nimbus
#

should I still use worldcenterofmass? because when I do Debug.Log(transform.TransformPoint(rb.centerOfMass)) it returns 0,0,0

strong nimbus
strong nimbus
#

oh! collider position! smart

hexed pecan
#

Center of mass is calculated from the colliders. Weird that it would be zero with that object

strong nimbus
hexed pecan
#

But yeah if you have a box collider with the center in the cube then you can use that

strong nimbus
#

or like

hexed pecan
#

Or just make the cube a child and use that childs center

final dragon
#

I'm creating a Tower Defense game as a assignment to my university.
I tried to mix two codes, one for path generation (Wide Arch Shark - tower defense video) , with the Tower defense video code the wave spawner (Brackeys), but for some reason I don't know, the enemies generated by the wave spawner are not following the path from the other code. How do I connect everything and make it really work? I'm actually lost here.

I think the main problem is in the EnemyWaveManager under enemy = Instantiate...

If someone is willing to help, I would be more than happy to show the code's

code - https://paste.myst.rs/7kf34ao9

strong nimbus
final dragon
hexed pecan
lone quiver
#

Hi I'm a beginner, recently I have came across using scriptable objects as game events from this video:
https://youtu.be/7_dyDmF0Ktw?feature=shared

but I wasn't comfortable with adding assets and importing them as GameEvent in my components from editor, it seems error prone, and not type safe.
so I was wondering what is wrong with using singletons as game events in this way:

public abstract class GameEvent<Type>
{
    public delegate void Callback(Component sender, Type data);

    public static List<Callback> listeners = new List<Callback>();

    public static void Raise(Component component, Type data)
    {
        for (int i = listeners.Count -1; i >= 0; i--) {
            listeners[i].Invoke(component, data);
        }
    }

    public static void RegisterListener(Callback listener) 
    {
        if (!listeners.Contains(listener))
        {
            listeners.Add(listener);
        }
    }
}

class PlayerGotDamage: GameEvent<int> {}
class PlayerBuildModeTriggerdGameEvent : GameEvent<bool> {}

what do you think, what are the disadvantages ?

Let's build the ultimate event system in Unity. With just 2 Scripts, you'll improve your programming skills and be able to organise and decouple your code much better! Less spaghetti code and more independent systems!

★ Join the Kingdom:
https://discord.gg/M2qfnUGxAz

★ Download the 2 epic scripts here: https://www.gamedev.lu/game-assets
★ Wat...

▶ Play video
final dragon
upbeat roost
#

FYI you can create a mesh of the collider and with mesh.GetVertices(new List <Vector3>()); you can get all corners. That is quite ez.

hexed pecan
# final dragon Just updated the post with the code lol

Cant really look through all that right now, maybe someone else can or you can try reposting your question here another time.
Meanwhile try to narrow your problem down to fewer lines of code. I dont see any troubleshooting done here

#

If you dont understand what the code in those two tutorials does then combining them will be hard

near hemlock
#

hey anyone know how to fix that ?
its show when i try to build the game

part of error 1:

> Task :launcher:preBuild UP-TO-DATE
> Task :unityLibrary:GoogleMobileAdsPlugin.androidlib:preBuild UP-TO-DATE
> Task :unityLibrary:preBuild UP-TO-DATE

part off error 2:

Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
D:\myWork\Project\Ninja run\Library\Bee\Android\Prj\IL2CPP\Gradle\unityLibrary\src\main\java\com\unity\androidnotifications\UnityNotificationManager.java:165: error: cannot find symbol
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)

part of error 3:

CommandInvokationFailure: Gradle build failed. 
D:\2022.3.7f1\Editor\Data\PlaybackEngines\AndroidPlayer\OpenJDK\bin\java.exe -classpath "D:\2022.3.7f1\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-7.2.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleRelease"

somber nacelle
#

this is a code channel. build errors for mobile should probably be directed to #📱┃mobile

somber nacelle
modern creek
#
        /// <summary>
        /// Start moving camera around.
        /// </summary>
        private void OnDragmodeUnlockedDown(Vector2 screenPosition)
        {
            _lastCameraDragScreenPosition = screenPosition;
        }

        /// <summary>
        /// Move camera.
        /// </summary>
        private void OnDragmodeUnlockedDrag(Vector2 screenPosition)
        {
            Vector2 differenceScreen = _lastCameraDragScreenPosition - screenPosition;
            Vector3 differenceViewport = Camera.main.ScreenToViewportPoint(differenceScreen);
            _lastCameraDragScreenPosition = screenPosition;
            primaryVCam.transform.Translate(differenceViewport * DragSpeed, Space.Self);
        }

I have some code that's trying to pan the camera around when you click & drag. It works, but I have to multiply it by a constant (DragSpeed above). I can't seem to figure out why this doesn't just work 1:1? The constant is about... 9? to get the dragging to match the input.. Any ideas..?

#

oh and it doesn't work for up/down with the same scale..

modern creek
#

I tried using world coords instead of screen coords, and it works "better" with respect to scale, but now I get jitter.. I suspect from trying to move it tiny fractions of world coordinates

dusk apex
#

Hmmm, the delta is a direction (difference in position) with some scalar magnitude and we're trying to convert that to a point relative to the viewport.. which kind of doesn't make sense to me. Maybe try converting both points then acquire the difference for the translation of the virtual cam?

modern creek
#
        /// <summary>
        /// Start moving camera around.
        /// </summary>
        private void OnDragmodeUnlockedDown(Vector2 screenPosition)
        {
            _startDragCameraWorldPosition = primaryVCam.transform.position;
            _startDragScreenPosition = screenPosition;
            v($"Camera drag starts at screen:{_startDragScreenPosition}, world:{_startDragCameraWorldPosition}");
        }

        /// <summary>
        /// Move camera.
        /// </summary>
        private void OnDragmodeUnlockedDrag(Vector2 screenPosition)
        {
            Vector2 differenceWorld = (Vector2)Camera.main.ScreenToWorldPoint(screenPosition) - _startDragCameraWorldPosition;
            Vector3 newWorldPosition = _startDragCameraWorldPosition - differenceWorld;
            primaryVCam.transform.position = newWorldPosition;
            v($"Moving camera to world:{newWorldPosition} (difference from startdrag:{differenceWorld})");
        }```
#

that's the current but.. something is wrestling with cinemachine brain trying to move the camera as well

#

as far as I can understand, i have all the "brain" of cinemachine brains turned off

#

oh weird, something else is going on.. every update cycle my drag vector2 position is getting reported as two different vectors:

#

I'm having a dumb day

dusk apex
modern creek
#

Yeah, I'm not keeping track of delta that way since I thought the rounding was the issue - so I was setting it to "start + difference"

#

but something else is busted.. those log lines have two different .. "differences"

dusk apex
forest ravine
#

Hello, what is good type-agnostic way to process input for a movement system I'm making?

forest ravine
#

Generics are proving to be a pain in the ass, whenever I have the idea to use them in it

rigid island
#

new Input System I suppose

forest ravine
#

I mean that I could maybe implement the same e.g. script that receives input and adds a force, were it a float, Vector2 or Vector3

rigid island
#

all three are value types 😛

forest ravine
#

Generics seem like could solve that but then I have to create as many dummy classes putting a type into the generic as I want implementations

modern creek
forest ravine
rigid island
forest ravine
#

Imagine you wanted to create some rigidbody movement system that worked as well in 2D as it does in 3D

#

Given that Unity splits the physics, that'd mean you'd have to duplicate the amount of classes/files you have to account for both

#

And 2D physics usually talk about Vector2, float, etc. while 3D we want Vector3, Quaternions, etc.

sharp sable
#

does Unity automatically create plain class members of MonoBehaviours ?
I have a plain class as a member of a component, and want to keep it null, unless explicitly created and assigned, but looks like Unity constructs it anyway

forest ravine
#

However, in a declarative way, what you want is not caring about if it's 2D or 3D but to apply the godddamn force and alike

sharp sable
#

hard to google question because all the results are related to gameobject instantiation

rigid island
#

even 2D

somber nacelle
hollow stone
sharp sable
#

it may be marked as serialized by the attribute, I'll check

forest ravine
#

Ok, I'll take that, thank you

sharp sable
#

@hollow stone @somber nacelle thank you, [Serializable] was the reason

somber nacelle
#

it can still be serializable, you just need to make sure that the field you don't want to be serialized is not serialized

#

if you don't have the class marked as serializable then you won't be able to serialize it yourself for things like saving/loading

sharp sable
#

yep, trying that rn

#

it needs to be serialized, so yeah, going to try with the [NonSerialized] in the component declaration

#

it worked, perfect, thanks again guys

somber nacelle
#

if you want to update all of the enemies' positions every frame, you should either pass the path to the enemies when you spawn them so that they update their own position each frame, or you need to keep a collection of all of the spawned/living enemies so that their positions can be updated. of course you'd also need to track which point along the path each enemy is currently moving towards so the first suggestion is likely going to be the easiest

final dragon
#

hummm, let me try that rq

modern creek
#

was just me being dumb and calculating world position from camera position - which obviously doesn't work since I'm moving the camera in that frame.. actual solution was just:

        private void OnDragmodeUnlockedDrag(Vector2 screenPosition)
        {
            Vector3 tickDifferenceWorld = Camera.main.ScreenToWorldPoint(screenPosition) - Camera.main.ScreenToWorldPoint(_lastKnownDragScreenPosition);
            primaryVCam.transform.position -= tickDifferenceWorld;
        }

where _lastKnownDragScreenPosition gets updated every frame of a legal drag event after the handlers process it

lost carbon
#

sorry but i still don't understand.

If the interface of the attack is like
int attack cost
public void AttackEffect()

then how can i implement more then one attack into a single enemy (a class)?

teal knot
#

just wanted to say THANK YOU so much, took a while but i managed to get this working :)

lost carbon
#

that's the problem for anyone that want to help

swift falcon
#

can anyone help me? im trying to build an android APK but im getting this error, Exception: Unity.IL2CPP.Building.BuilderFailedException: C:\Program Files\Unity\Hub\Editor\2020.3.30f1\Editor\Data\PlaybackEngines\AndroidPlayer\NDK\toolchains\llvm\prebuilt\windows-x86_64\bin\clang++

rigid island
swift falcon
#

i deleted all my clang files

#

now it does not work

#

can somebody please help

#

alright i fixed it but im getting another error, Unity.IL2CPP.Building.BuilderFailedException: C:\Program Files\Unity\Hub\Editor\2020.3.30f1\Editor\Data\PlaybackEngines\AndroidPlayer\NDK\toolchains\llvm\prebuilt\windows-x86_64\bin\clang++

#

Build completed with a result of 'Failed' in 54 seconds (54323 ms)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

#

UnityEditor.BuildPlayerWindow+BuildMethodException: 2 errors
at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (UnityEditor.BuildPlayerOptions options) [0x002ca] in <68089899e4c84456bfc1de3436accf4a>:0
at UnityEditor.BuildPlayerWindow.CallBuildMethods (System.Boolean askForBuildLocation, UnityEditor.BuildOptions defaultBuildOptions) [0x00080] in <68089899e4c84456bfc1de3436accf4a>:0
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

wild tendon
#

I'm in need of some help, i'm trying to get a game model to show up, but it won't for some reason. Is there any solution?

heady iris
#

that's extremely vague

#

and not a code problem, from what you've said

wild tendon
#

Oh, i thought it was a coding problem. sorry, wrong room. Though which room is the stuff i need help with? Mainly a model not showing up even though it shows the model in the folder or something, I'm not the best at explaining.

heady iris
#

use #💻┃unity-talk .

i don't know what "not showing up" means -- is nothing appearing when you drag it into the Scene View? If so, share a screenshot of what's going on in that chat

dark kindle
#

when u have both multiplayer and singleplayer versions of a scene, is it preferred to use the same script for both offline and online, or separate scripts?

lean sail
dark kindle
celest iron
#

Could someone tell me why my neighbours array here works fine
https://pastebin.com/a9fkLcB9
But once I expand it to include the diagonals neighbours (so I increase the size of the array to 8 too), I get an out of bounds error?

radiant shadow
celest iron
#

Yeah, I only get 4 elements on the list on the inspector

#

And the first 2 are empty

radiant shadow
#

I think this its what you need: [NonSerialized] private Tile[] neighbours = new Tile[8];

grave quarry
#

currently getting the fault: the type or namespace name 'keyValuePair<,>' could not be found. I'm using System.Collections.Generic, which should contain keyValuePair, but the system still doesn't recognize it. Any help on what my issue is would be appreciated.

radiant shadow
celest iron
radiant shadow
celest iron
#

Ok, trying with the property then

radiant shadow
#

you could write like:
the property:
private Tile[] neighbours;
then inside GetTileData:
if (neighbours == null) neighbours = new Tile[8];

you should be fine

celest iron
radiant shadow
celest iron
#

Why was it being serialized as a size 4 array instead of 8 tho? so weird

radiant shadow
#

When you first created, your code was like new Tile[4]; ?

celest iron
#

No, it didn't even had the array

radiant shadow
#

weird 🤔

celest iron
#

Wait, the first time I implemented the array

#

it was new Tile[4]

#

But the first time I made the tile object, it didn't had the array

#

I guess the first declaration is what counts

gleaming tundra
#

Hey y'all! Does using multiple viewports on different cameras work in windowed mode? Can I do that to make multiple windows with differnt views of the same scene running off the same application?

patent parrot
#

Guys I have one question I have an array that stores a class of type mobs.
but how do I see the information of the mobs within the array that stores them?

gleaming tundra
#

Did you import the relevant package?

patent parrot
gleaming tundra
#

If you want to iterate over all of them, use a for loop or a foreach loop.

#

I'm not a mod so take this with a grain of salt, but you might have better luck in the beginner section?

#

gimme a sec, I'll take some screen shots

patent parrot
gleaming tundra
#

Uhhh... Nevermind

#

That's depacated

quartz folio
#

It was deprecated years ago, and I don't think it will appear outside of the My Assets tab if you've never installed it. Use the starter assets pinned to #💻┃unity-talk if you need a character controller base. Or use the example controllers from the kinematic character controller asset if you're capable of dealing with something more complicated.

#

And don't cross-post

gleaming tundra
#

Unfortunately I don't think I can give out unity stuff without permission? They've taken it off the store page

gleaming tundra
frail ibex
#

Hello, i tried to make a save system with a binary file, but my existing code return this error now even though i barely touched it :/ May i have some help please ?

somber nacelle
#

also

a save system with a binary file
i hope that doesn't mean you are using BinaryFormatter

frail ibex
#

It does mean that ?

#

What's wrong with it ?

cold parrot
frail ibex
#

What did you recommand to use if not BinaryFormatter, i got told that's more secure so save file not getting modified but well if it's not secure better to change i guess

somber nacelle
#

the security in question has nothing to do with preventing modifications to the save data. without strong encryption it's not going to be too difficult to modify the save data no matter how you encode it.
it's a malware risk because deserializing arbitrary data with BinaryFormatter can lead to malicious code being executed on your machine. this makes sharing save files (which a lot of people tend to do) dangerous

frail ibex
#

I meant that i chose BinaryFormatter to prevent modification over XML or JSON

somber nacelle
#

and again, that's not really going to do much to prevent modifications of save files

frail ibex
#

i understand the risk now though

late lion
#

There are websites that let you upload and edit BinaryFormatter files anyway

frail ibex
#

Why people keep advising this then -.-

somber nacelle
#

this is a code channel

frail ibex
#

What alternative are you using ?

somber nacelle
#

i personally use message pack to serialize and encode to binary. that's probably not going to be easy to use for someone who cannot diagnose an NRE though. so i'd recommend just using json for now

late lion
#

First it's important to understand that you can't prevent save file editing. You can only make it more difficult. Some basic encryption of plain text files like JSON will prevent most people from being able to edit it. But a person with enough time and skill can still reverse engineer it.

frail ibex
somber nacelle
#

yeah the only true way to prevent someone from modifying their save file is to not even give them access to the save files at all. but then you run into the problem of the game needing to be always online and hosting servers for the data

#

and even then, that isn't necessarily preventing 100% of cheating and the like

frail ibex
late lion
#

Then anything that isn't plain text will suffice. You could even just encode JSON to Base64.

frail ibex
#

Ok, thanks for your advise, i'll do research about JSON then

mellow sigil
#

The real solution is to not care if people mess with their own save files, because why would you

frail ibex
#

It not like i really care about it, i just don't want it to be easily messed

somber nacelle
#

but why

late lion
#

I think it's a valid concern. Players might report bugs that only happened because they messed up their save file.

frail ibex
#

Yes and also, i also want to try things as Dev

#

It's a part of thing that i want to achieve, just to achieve it

#

I'd like to have the knowledge to do that

frail ibex
#

@somber nacelle It seems that my NRE come from something being delete on my Scene for whatever reason which my objet was link with, as much i got an UI delete right now for free.

lost carbon
#

Is there a way for implement the same interface into a class more then 1 time or something that have the same effect?

#

I need to give some attacks at some characters, but every attack have a different effect, that is a method

late lion
lost carbon
late lion
#

But it's probably not what you had in mind.

lost carbon
#

Yeah

#

Maybe an interface isn't the right way. But what i should do other then do a class for every attack in the game?

late lion
lost carbon
#

The attacks contain the cost and other things too. Maybe i should do a struct with a delegate variable for the method into it

latent latch
#

^

lost carbon
#

Yeah seems not bad

latent latch
#

A list of delegates would be possible too and just implement it into the interface

#

Not exactly sure of your usecase but I do something similar

knotty sun
# lost carbon Yeah

Hi, Sorry, I missed your earler post, I meant something like this

public interface IEffects
{
    public delegate void Effect();

    public event Effect effect;
    public void AddEffects();
}

public class myClass : IEffects
{
    public event IEffects.Effect effect;

    public void AddEffects()
    {
        effect += Effect1;
        effect += Effect2;
        effect += Effect3;
    }

    void Effect1() { }
    void Effect2() { }
    void Effect3() { }
}
scarlet viper
#

by the way anyone feels like hes making mess with his c# methods?
ive been coding in unity for few years now but i always end up creating a mess where various methods are stuffed in the same files

plucky patrol
#

Hi searching for somebody for the game jam

#

Can anybody help?

dusk apex
tawny elkBOT
plucky patrol
#

!collab

tawny elkBOT
vagrant spade
#

What's the idiomatic way to return a slice/window of an array in normal unity C#? I saw that Span<T> exists but within the burst compiler bounds, I just need a slice, and by slice I mean a Rust style slice, where it's just an index and a length. I tried to use ArraySegment<T> but I can't seem to find it

leaden ice
#

e.g.

var array = new int[] { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
var slice = new Span<int>(array, 2, 5);
for (int ctr = 0; ctr < slice.Length; ctr++)
    slice[ctr] *= 2;```
vagrant spade
#

And it works with managed arrays?

#

In Unity?

#

I must've read wrong while reading google

leaden ice
#

As shown in this example, yes^

vagrant spade
#

Ok, let me try, thank you

leaden ice
#

not in burst/job system though

vagrant spade
#

Which napespace is it in

leaden ice
#

since you can't use managed arrays there

vagrant spade
#

?

vagrant spade
#

Ok, odd, thanks

#

I must've had the wrong doohickey when I added the thingamajig

#

Thanks, it compiles, let me test it out

leaden ice
vagrant spade
#

I have yet to tuch the burst stuff

#

Would you be kind enough to ELI5 the differences between IL2CPP, Burst, and DOTS? I just started working again with Unity since I took a hiatus in 2018 so I'm a bit out of the loop

#

If you don't mind, no worries, I can google it

#

I know DOTS is Unity's implementation of ECS, I used IL2CPP back in the day when publishing for mobile, but I'm not sure how burst fits into all this

leaden ice
# vagrant spade I have yet to tuch the burst stuff

IL2CPP is just a replacement C# CLR runtime (replacing Mono in Unity) that supports more target platforms and is faster (and is AOT instead of JIT compiled). It involves crosspiling C# code to C++ then building the binary from that C++ code
Burst is a special compiler for eligible code with strong limitations (only blittable non-managed types) and strong performance advantages (think loop unrolling, SIMD extensions etc)
DOTS is an overarching term covering ECS, the Job System, and Burst

vagrant spade
#

I remember the Job system was in beta when I stopped using it. How is burst different from IL2CPP?

leaden ice
#

It's a completely separate compiler IIRC that goes straight from C# to highly optimized machine code.

#

(with lots of limitations though)

vagrant spade
#

Right, so it bypasses the transpilation to C++

leaden ice
#

yes afaik

vagrant spade
#

And I assume it's AOT

leaden ice
#

yes definitely

vagrant spade
#

It makes sense in the context of ECS

#

Since the idea of ECS, at least when done right, is to have cache friendly data structures and that mostly requires blitable types

#

The Job System is a multi threaded scheduler?

#

It's Unity's own async runtime?

leaden ice
#

Yeah it's a multithreaded scheduler that hooks into Unity's internal native threadpools

vagrant spade
#

Cool

#

Well, that clarifies everything

#

How are people writing code these days? Are they mixing and matching MonoBehaviours with DOTS in those areas where DOTS will help or is there a red/blue function kind of thing going on with DOTS where once you have a couple of things in DOTS, it just makes sense to keep everything within the system?

#

If you're familiar with red/blue functions

#

or colored functions

#

Not sure if that makes sense

#

Like I never enjoyed OOP in Unity, could I finally fulfill my dream of avoding OOP if I do everything in DOTS?

leaden ice
vagrant spade
#

Much to the chagrin of designers I work with

leaden ice
#

In my experience I do most things in GameObject/MonoBehaviour world and do performance critical things in the Job system

#

but I haven't used ECS itself

spring creek
vagrant spade
#

Ok, cool

#

I'd have to start digging into it, the current prototype I'm working on would actually benefit from DOTS, as I would like to push the amount of entities on mobile to the tens of thousands

spring creek
#

Pure ECS is generally easier than Hybrid though

#

A lot of things don't play well together

vagrant spade
#

I can imagine

#

In terms of data ownership you mean, right?

#

Like where is the data actually located in memory

spring creek
#

Well, that and just the monobehaviour physics simply does not work with ecs physics

vagrant spade
#

How difficult would it be to port a MonoBehaviour design (is there a cool kids name for this?) vs a DOTS design?

spring creek
#

You have to do a lot of workarounds to get entities and gamobjects to even interact at all

vagrant spade
#

Yeah I mean, that makes sense

spring creek
vagrant spade
#

Oh so what's the difference between DOTS and ECS, I thought DOTS was just a kind of ECS but with burst and jobs if you need them

#

ECS being the generic architecture

spring creek
vagrant spade
#

Oh I see

spring creek
#

You can use the latter two with OOP

#

And monobehaviours

vagrant spade
#

Other than just not being OOP, does Entities have other benefits? Like even with only dozens of entities on screen, is it still more performant?

#

Is there a good book on DOTS?

#

I'm likely going to need it for this game, honestly, if not the entity count will be quite limited

spring creek
#

I just like it conceptually. I find it easier to develop in.... for the most part haha

scarlet viper
#

are there any ways i can integrate dots into a monobehaviour project and use both in same time?
id use monobehaviors for more complex stuff, and dots for simpler stuff
but no idea what could I use dots for to be honest
because the communication between monos and dots is poor/slow

spring creek
#

And yeah, it CAN be more performant even at low entity counts

vagrant spade
#

That's cool

#

I guess where you might run into trouble is if you use any 3rd party packages that are MB

spring creek
vagrant spade
#

So yeah, if you can recommend a book, I'll read it over the weekend

spring creek
#

*depending

vagrant spade
#

I don't like video courses, I prefer books, but I'm only finding this so far, I guess maybe I'll just have to work with the documentation

#

This is a bit old though

#

I guess I would just start with ECS

spring creek
vagrant spade
#

Oh.... Burst and Jobs were in development in 2018... I thought they would be ready and relatively mature by now...

late lion
#

You will get the most from just using Jobs and Burst. That's the part that makes Entities fast; good use of Burst compiled jobs. While Entities is still young (well, not really, but it keeps getting rebirthed), Jobs and Burst are very mature and stable.

vagrant spade
#

So I should feel confident developing with DOTS in production for mobile?

late lion
#

I don't like using the DOTS term, because it includes Entities. Jobs and Burst? Absolutely.

vagrant spade
#

Aethenosity mentioned that Entities is at 1.0 but burst and jobs are not, and yet the latter are more stable?

late lion
#

Jobs has been integrated as part of the core engine for many years now. Burst is still a separate package, but had its 1.0 release in 2019

#

Entities is dependent on Jobs and Burst to work, not the other way around.

spring creek
vagrant spade
#

Oh, yeah, I misunderstood, thought you meant burst/jobs weren't 1.0 yet

#

Cool

spring creek
#

Yeah, saying "pretty young" is pretty vague/misleading.

I more meant in terms of most people not really using them haha

spring creek
gray mural
#

Hello, how can Input.GetKey(KeyCode.LeftShift) possibly be false in Update if I am holding LeftShift key all the time? (assuming that I'm actually doing it, it works in other programms and I know where left shift is)

private void Update()
{
    print($"LeftShift: {Input.GetKey(KeyCode.LeftShift)}");
}
leaden ice
leaden ice
gray mural
leaden ice
#

Then I guess you're not pressing the key? IDK

gray mural
spring creek
leaden ice
#

or maybe this is a windows sticky keys thing or something?

#

Or a different keyboard layout

gray mural
gray mural
knotty sun
#

I think you will find that the shift, ctrl and alt keys do not register on their own. They are key modifiers not keys in their own right

knotty sun
#

exactly that

late lion
spring creek
gray mural
scarlet viper
#

I have one value in 0.0 to 1.0 range, and other value in -1.0 to +1.0 range. and theyre tracking the same thing but using different ranges
how can i keep them in sync ? so that first variable's 0.5 would be second variable's 0.0

dusk apex
#

Formula:cs var first = ... var second = first * 2f - 1f;

scarlet viper
#

i see thanks

proud hare
# scarlet viper i see thanks

Dalphat's answer is the best and most efficient.

But if you were concerned more about readablity, you can also do the same thing like this

second = Mathf..Lerp( -1f, 1f, first );

simple egret
#

And for more complex ranges, you can use a remap function, which is essentially two lerps
var newValue = Mathf.Lerp(newRangeMin, newRangeMax, Mathf.InverseLerp(oldRangeMin, oldRangeMax, oldValue))

viral prairie
#

is there a non cheaty way to apply a compute shader to your screen?

latent latch
#

wat

spring creek
#

Maybe describe what that is so it can be avoided

viral prairie
#

oh sorry
i can always just take renderimage run it through a compute shader and put it on a canvas that overlaps everything, but i hoped there is a better way

devout solstice
#

So this is all working right, but the ChangeSlot at the end never runs

leaden ice
devout solstice
#

oh shit your right the while loop never ends

unborn flame
somber nacelle
#

again, have you confirmed that nothing else is modifying it and that you are actually operating on the correct image component?

somber nacelle
#

okay and how did you confirm that?

unborn flame
#

in one of my lines of code I have it so that it can only open that image with the name fill

somber nacelle
#

how about this, put this log right before where you assign the fillAmount and show what it prints:
Debug.Log($"Changing fill amount on {healthFill.name} {healthFill.GetInstanceID()}. Previous value is {healthFill.fillAmount}", healthFill.gameObject);

unborn flame
#

alright

somber nacelle
#

i also recommend a Debug.Break(); right after the log that prints the new fill amount so that it pauses execution and you can check the state of your scene

unborn flame
#

like this? '''public void TakeDamage(int damage)
{
Debug.Log($"Changing fill amount on {healthFill.name} {healthFill.GetInstanceID()}. Previous value is {healthFill.fillAmount}", healthFill.gameObject);

    Debug.Break();

    currentHealth -= damage;
    currentHealth = Mathf.Clamp(currentHealth, 0, health);
    Debug.Log("Current Health: " + currentHealth);

    // Update health bar
    healthFill.fillAmount = (float)currentHealth / health;
    Debug.Log("Fill Amount: " + healthFill.fillAmount);

    if (currentHealth <= 0)
    {
        Die();
    }
}'''
somber nacelle
#

the log that prints the new fill amount is the one after you assign the fill amount

unborn flame
#

ah ok

somber nacelle
#

the log i gave you should also go right above your // Update health bar comment

delicate zinc
#

Is there a way i could rotate a Bounds struct by 90 degrees increment?

#

i'm asking specifically 90°, since i'm making (or at least trying) to make a proceduraly generated dungeon, and i want rooms to have a random, 90 incremented rotation on the Y axis

#

i was originally thinking on just instantiating the prefab room with it's rotation and then creating a bounds and growing them to encapsulate the prefab's colliders, but for whatever reason sometimes the instantiated game object's collider.bounds property return a bounds with center set to 0,0,0. which causes these huge bounding boxes

quartz folio
#

Swap the width and height

delicate zinc
#

but how would i do that

#

you mean swap the extent's x and z?

quartz folio
#

Yes

delicate zinc
#

yes that worked

#

thanks

hard viper
#

Let’s say I made a static class which is just one .cs file that I want to share. This .cs file is useful for both Unity and outside Unity. What is the best way to distribute for other people? Github?

quartz folio
#

Github has gists for sharing small disconnected things without a repo

hard viper
#

and is an MIT license needed to let everyone know it’s basically free to use?

Or can I just throw it up and say “Go gettem, champ!”

quartz folio
#

You can put a license in the gist or find another place to declare the license of all your gists if it's a common theme

hard viper
#

ty

knotty sun
# hard viper ty

you can console yourself by thinking your code will be used to train the next generation of completely useless 'AI' bots

south gorge
#

I am writing a code for a simple capture the flag and I have a script called flagpick up that is attacted to my flag object, When the player collides with the flag object it the follows the player. But here is the hard part, I want to when the player collides with the return point object and is also holding the flag to delete, but since the script is attacted to the flag i can only make it work when flag collides with the return

#

is there a way to reference the player colliding with the return, in a code that is attached to my flag

primal scaffold
#

this is bad code architecture

south gorge
#

you think i should a script that is attacted to the player

#

ok

#

i will fix it

#

ty

primal scaffold
#

you can have something attached to the colliding object

#

and check if the colliding player

#

has the flag

#

then use a switch case statement

south gorge
#

okay thank you friend

thorny spindle
#

If you really wanted to hack it, you would have an event on the player trigger that a function on the flag would be subscribed to

zinc eagle
#

Hey guys, does anyone know what I did wrong? Lets say I have a GameObject that has a script connected to it that is using OnDrag, OnBeginDrag and OnEndDrag.

This is the script (Test Script)

https://paste.ofcode.org/cUMhXZXezDUVHJzdPbLGzw

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class TestDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{

    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("OnBeginDrag");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Debug.Log("OnDrag");
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        Debug.Log("OnEndDrag");
    }
}

Now on the GameObject, I added an Event Trigger in which I added the Begin Drag, Drag, and End Drag and I conncted the same GameObject with the script to it.

But for some reason when I looked up the function, the options for OnBeginDrag, OnDrag, and OnEndDrag weren't there.

rigid island
zinc eagle
#

I guess the component. I wanted to call OnDrag and its peers on the Event Trigger Funtion, but it just doesn't show up

graceful latch
#

is it possible to change what bool your checking for in editor so like if (bool) where the bool is customisable in editor?

quartz folio
# zinc eagle

Why would you use an EventTrigger and a component with the interfaces on the one object? Afaik EventTrigger is basically the lazy prototyping way to do the interfaces, as it will capture every event

#

Also, your screenshot isn't showing TestDrag. But even if it was, EventTrigger sends BaseEventData, if your events don't match that I don't think they will appear.

zinc eagle
#

ah, I see

rigid island
# zinc eagle ah, I see

stick with doing everything in code, doing things in inspector is ok sometimes but really bad if you want to find something

#

code is better because you can search easily through your classes etc

plucky karma
rigid island
quartz folio
#

!code

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.

rigid island
#

edit msg, format the code properly

#

alsorigidBody.velocityin FixedUpdate overrides any AddForces you try to apply

tiny orbit
#

I have a VisualStudio/Unity question. I keep getting these errors when I open a script from unity and my script will open but none of the references to my other scripts are there. When I open multiple scripts each script opens in a new window of Visual Studio, instead of a VS tab. I can still edit my scripts. Anyone know whats causing it?

dusk apex
tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

dusk apex
#

Make sure that you've included the Unity workload.

#

It's often overlooked

tiny orbit
#

what happened though? it was working fine yesterday...

dusk apex
#

Uncertain about "yesterday" but it's not configured today

wanton wasp
#

I have a cloud save system using PlayFab, where the money amount is saved when it has changed or the game has been closed.
The problem is, the player can modify memory (RAM) and set any money value and it'll be saved.
Is there a solution?

dusk apex
#

Unless you're going to compute the transaction over the network/server, there isn't much you can do if it's on the client side.

scarlet viper
#

how do you always get the original +/- with mathf pow ?

#

negative values multiplied by itselves return positive values

fervent furnace
#

ofc negative*negative is positive...

scarlet viper
#

nvm got it

scarlet viper
fervent furnace
#

you want something like: -(mathf.pow(abs(base),exp))?

scarlet viper
#

not sure, i did this and it worked

        float torqueNormal = finalInput * dragInfluence * (horizontalPower * 100f);
        float torque = Mathf.Pow(torqueNormal, 2f);
        if ((torqueNormal < 0f && torque > 0f) || (torqueNormal > 0f && torque < 0f))
            torque *= -1f;
lean sail
#

Could even apply the same logic to higher exponents, where you just do the calculation on ((abs(theValue) ^(n-1)) * theValue

sonic edge
#

Hello,
I'm currently doing a prototype for my 2D game and I'm doing the generation of the levels. The generation of the rooms themselves works perfectly, however, When I atempt to spawn the enemies, I have an issue. To spawn them, I simply add their prefabs (the enemies) in each room prefab (example on the picture 1). It should in theory work well, but actually, it doesn't. Some enemies are working the way they should, and others are bugging. They are in they patrol function but they are just static with a run animation, which should be impossible as I modify the animator speed variable depending on the enemy's velocity. (image 2, video) It's been a week now and I still don't have a clue of how to resolve the bug. I guess that the problem comes from the way I generate my enemies because on a "normal map", they all work perfectly.
Does someone have an idea on what could create this bug ?

main shuttle
sonic edge
#

oh yea sry

main shuttle
# sonic edge

Well you clearly show that the speed variable is 1.5 for the stationary archer, so the problem is your code and/or your references.

#

Can't make more out of it without showing the full code, but if you probably added a:

Debug.Log($"The velocity of {gameObject.name} is: {rb.velocity.x}", gameObject);

(Haven't tested this, just out of my head)
Then you can click on the debug log in your console, and see if the things actually match what you think.

#

But I think some of the enemies are changing the animator parameters of another enemy.

tawny plover
#

Hello, I'm trying to find a Job System Documentation about "what are data types that supported in Job System process?"

#

Anyone have the reference/link?

main shuttle
tawny plover
#

Hmmmm... Ok, I'll try, Thank You!

sonic edge
pliant gorge
#

When i load scene and then load back into the original scene i get some problems:
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.

I think its the problem that i'm setting the initial value of that 'GameObject through' the inspector but i don't really know what to replace it with,don't really want to use Find for all the stuff
The same problem goes for the second scene, basically if i load a scene second time it gives me that error

somber nacelle
#

it sounds like you are using a DontDestroyOnLoad object that is referencing scene objects so that when the scene is unloaded those objects are destroyed. of course you haven't really shown relevant code so that's really just a guess

pliant gorge
#

Sorry, there's just really a lot of code and no, i haven't used any Don'tDestroyOnLoad since i don't need to have any objects go from one scene to another its just that when i try to use LoadScene on the same scene twice my references dissapear and my guess is it has something to do with me assigning them through inspector and not code but i may be wrong

somber nacelle
#

oh did you save your scene before entering play mode? because reloading the scene during play mode will load the scene that is actually saved in your project

pliant gorge
#

if you mean ctrl+s behind saving then yes, im sure both scenes are saved on needed versions

somber nacelle
#

well make sure you did save. then share the relevant code

fervent furnace
#

did you use any static variables to reference the gameobject or other persistent storage or call async codes

pliant gorge
#

i do have a static class for saving data to json but the error points to this row:
if(_swipeScript.currentButton.GetComponent<FoodSpawnButton>().currentObject != null){
_swipeScript is the object that im assigning through the inspector so i think the missing ref points to it

somber nacelle
#

hmm yes, a single line of code definitely provides enough context to solve this

pliant gorge
#

ill have to dig around for a bit to find which code will be helpful as i have a bunch of it

#

ok so i've commented those 3 lines as it's not vital but now the problem jumps out right on next line which is
GetComponent<Collider>().enabled = false;
so im guessing it is something not behind smaller parts of code but the scene loading logic overall

somber nacelle
#

until you provide more context, we can only really speculate

pliant gorge
#

well i will be firstly reading some more stuff about the scene loading as both the scenes have the same issue

somber nacelle
#

why don't you just show the full context for where the error is actually happening

pliant gorge
#
public class GrowthController : MonoBehaviour
{
public static event EventHandler OnSellWeightPressed;
[SerializeField] private Button _sellWeightButton;
public FoodSpawnSwipe _swipeScript;
void Awake(){
        DataSave.LoadData();
    }
    void OnApplicationQuit(){
        DataSave.SaveData();
    }
    private void Start(){
        _sellWeightButton.onClick.AddListener(delegate {OnSellWeightPressed?.Invoke(this, EventArgs.Empty);});
        OnSellWeightPressed += Event_OnSellWeightPressed;
    }
private void Event_OnSellWeightPressed(object sender, EventArgs e){
        if(DataSave.growthData.weight > 1){
            if(_swipeScript.currentButton.GetComponent<FoodSpawnButton>().currentObject != null){
                Destroy(_swipeScript.currentButton.GetComponent<FoodSpawnButton>().currentObject);
            }
            GetComponent<Collider>().enabled = false;
}
}

So here if i comment the part of IF i get the MissingRef for GrowthController script which is strange, its as if it tries to run this script from a gameObject from a previous scene

somber nacelle
#

there it is. it's an event that you are probably not unsubscribing before you reload the scene

#

see how easy it is to diagnose an issue when you actually provide the full context?

pliant gorge
#

ah damn, now i remember the stuff about unsubscrubing
sorry that it took a bit, just didn't know if getting those parts here and there would help

#

ok it seems to have worked nicely, thanks!

scarlet viper
#

if vehicle is based on keyboard input, how do people usually insert other velocities into the equation, such as velocity caused by speeding up, or velocity slowed by driving uphills

it seems it becomes some sort of relativity/reference loop where vehicle speed is controlled by both the keyboard input but also by vehicle velocity (that was previously increased by keyboard input)

worn oasis
#

Hey guys, I'm facing an inspector bug:

Any idea why that might be happening?

#

The script content is not accessible

#

The fix is to save a script to force unity to revise scripts. Would have to do that a few times sometimes and it ends up working again.

leaden ice
worn oasis
#

You reckon it would be solved if I upgrade?

leaden ice
worn oasis
leaden ice
#

that's a good idea too if you're willing to do so

woeful leaf
#

For some reason Unity never updates the sprite width, even though it is different, but when I get it with the width property it always returns the same as the first sprite

using UnityEngine;

public class BackgroundManager : MonoBehaviour
{
    private Vector3 scrollSpeed = new(-0.01f, 0, 0);
    [SerializeField] private SpriteRenderer[] renderers;
    [SerializeField] private Sprite[] bgs;
    private int bgIndex, bgTransitionCount;
    private int bgTransitionTreshold = 1;

    private void UpdateBackground()
    {
        foreach (SpriteRenderer renderer in renderers)
            renderer.sprite = bgs[bgIndex];

        renderers[^1].transform.position = Vector3.zero;
        renderers[^1].transform.position += new Vector3(renderers[^2].size.x, 0);
    }

    private void ChangeBackground()
    {
        bgIndex = (bgIndex + 1) % bgs.Length;
        UpdateBackground();
    }

    private void Start() => UpdateBackground();

    private void Update()
    {
        transform.position += scrollSpeed;

        if (transform.position.x * -1 >= renderers[^2].size.x)
        {
            transform.position = Vector3.zero;
            bgTransitionCount++;
        }
        else if (bgTransitionCount == bgTransitionTreshold)
        {
            ChangeBackground();
            bgTransitionCount = 0;
        }
    }
}
woeful leaf
rigid island
#

no that would be horrid lol

#

you should not update everytime new update is out esp on active project

hidden parrot
#

Not as far as I'm aware

#

There's definitely asset store assets and probably some random script out there for it

rigid island
#

Ohh thought you were referring to Unity

hidden parrot
#

My immediate thought is ping a server that checks the game version

#

and if game.version != server.latestgameversion then tell user to update

rigid island
#

ye this should be a simple query to the server

#

Addressables/AssetBundle

hidden parrot
#

that seems like the kind of thing a launcher would do, like a diff check

main shuttle
woeful leaf
#

Oh yeah I should just set it

#

That's my bad

#

I thought I reset it and then add it again

#

Either way it does the same

#

But I should just change it to the proper way lel

leaden ice
#

why not just

renderers[^1].transform.position = new Vector3(renderers[^2].size.x, 0);```
gray mural
#
Transform tempItem = _currItem ?? _currItemFrame.itemPrefab.transform;

_currItem is null here, _currItemFrame.itemPrefab.transform isn't. Why does tempItem end up being null ?

simple egret
#

?? should not be used with anything Unity because it does not take in consideration the "destroyed but not null yet" state of Unity objects

#

Use a regular null check

gray mural
simple egret
#

That works yes

shy knoll
#

when i try too make a custom cursor in build settings i get Failed to set the cursor because the specified texture ('Rat Cursor') was not CPU accessible.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
and idk how too fix that

gray mural
simple egret
#

If it was, you'd get an NRE

gray mural
late lion
#

In C#, objects cannot suddenly become null. No exceptions. Unity wants that to be the case, but can't, so they fake it by overriding the == operator to return true when compared to null and the object is destroyed.

simple egret
#

Then at some indeterminate time, the GC will sweep over it and it'll really become null

gray mural
#

so this will become null?

Destroy(nice.gameObject);
nice = null;
simple egret
#

Yes because it reassigns null explicitly to the variable

gray mural
#

ic

#

strange.

simple egret
#

The previous value still lives in memory until the GC goes over it, but it's not referenced by the variable anymore

gray mural
#

thank you, I fixed it by assigning it to null

rigid island
#

yea dont bother using obfuscator

#

is it single player?

simple egret
#

No need for obfuscation when the server ensures every client action is legal, you have that implemented right?

#

You're not doing multiplayer right, then

#

Everything should be validated by a server, or directly handled by the server itself

verbal rose
#

What's the common way to save data (like a highscore) so that people can use the same Google/Apple account on different devices and keep their highscore?

rigid island
verbal rose
#

didn't know about that, is it expensive?

rigid island
verbal rose
#

noice

rigid island
#

but does require CC on file

verbal rose
#

CC?

rigid island
#

credit card

verbal rose
#

ah right thats fine

#

thanks ill check that out

rigid island
verbal rose
#

oh yeah i see it, it is the latest vid right?

rigid island
#

i have another one in the works to show how to connect accounts

#

right now its just anonymous sign in, just to give idea how easy it is to start

verbal rose
#

thats good ill check it out

woeful leaf
#

I fixed it though

#

But the main issue is still a problem

#

Any ideas? (Anyone?)

lost carbon
#

is there a way for select some methods to put into a delegate variable from the inspector?

golden garnet
#

Hey! I'm currently working on a top-down 2D game and am trying to get a game object to rotate towards the position of the mouse on screen. This usually would be easy, but I'm using the New Input System so I haven't gotten very far. Nothing online has been very much help. Any ideas?

rigid island
#

i find that impossible to believe lol

#

just replace Input.mousePosition you use Mouse.current.position.ReadValue()

#

the rest is exactly the same

#

or if you want not only mouse use Actionmap or w/e

golden garnet
#

I was going to also add that I was going to use the mouse posiiton in conjunction with an action map for certain actions, but I thought of a better way of doing it so I won't be needing that. I replaced Input.mousePosition with the Mouse.current and that did work. So thanks!

worn night
#

Hello! I'm in need of some help as I have to start looking for multiplayer online solutions for our game and I don't really know which one to choose honestly 😅

#

I feel like this is important, and I'm a bit scared of not choosing properly... I'm trying to read some info on pros and cons but everything seems "right"?

rigid island
worn night
#

It's quite small as only 6 players max per match

#

But yeah still

rigid island
#

I like netcode because its easily integrated into the engine for the most part

worn night
#

Mhmhm I see

#

I have seen fishnet and photon

#

Like they are my 2 alternatives apart from netcode

#

With netcode how does the hosting go? I guess is not as integrated as in photon sadok

rigid island
#

everything is integrated on UGS

#

you can use Lobby and Relay for example

#

unity does all the hosting for you

worn night
#

Nice! That's quite good then!

#

Then ill write that up as an alternative

rigid island
#

yeah having everything integrated makes it easier

worn night
#

Totally right!

#

Also if it's first party probably event better as you said

#

Integrated with the engine

rigid island
#

yeah it all works with each oither, they have a free tier too so its easy to get started with them as well

worn night
#

Perfect!

#

Altho, our game is quite physics demanding, I don't know if it offers like deterministic physics like in photon

#

Maybe this is a feature I don't really need afterall

rigid island
#

physics gets quite complex

#

fast

worn night
#

😅

rigid island
worn night
#

I have found this online too:

#

It's a comparison between NGO, Fish-net and Mirror

#

For me rn fish-net is the most appealing solution just because it allows for client based prediction

#

I don't really have the knowledge at the moment for writing my own

#

Maybe it's not that hard, but the concept sounds a bit scary not gona lienotlikethis

lean sail
#

Tbh that ngo page about physics doesnt really say much about actually using it.
It gets a bit more complicated when you want server authoritative yet responsive input

worn night
#

Maybe for a fighting party game I don't need to be that restrictive with the responsiveness and physics?

#

Like, if it was a competitive fps I would need to be very careful

#

But a fighting game with overcooked visuals maybe can allow itself to be way more relaxed in that aspect

rigid island
rigid island
lean sail
rigid island
#

the server authorative simulates the physics and all the clients get Interpolated animations, it looks bad

lean sail
#

Ngl I was trying some client authoritative physics based game and I might just move on. I (painfully) got the basics working but it's just such a hassle because now im limited in a lot of aspects

worn night
#

Mhhh... Then... Where should I look up to? (Many thanks both of you for mentoring me on this, I appreciate it a lot)

rigid island
#

experiment and see what you're willing to sacrifice for accuracy vs speed

#

there is no definite answer usually

worn night
#

Okay! Yeah that is true ahahaha

#

Ahhh game dev, the "it depends" are everywhere

lean sail
#

If you have a good team I'm sure you can get it good so dont be discouraged. I was working basically alone (first multiplayer game too) so that's mostly why im moving on. I desperately wanted to get rid of input lag, and I didnt want to try client prediction because mine was an active ragdoll and I thought itd be too much. So I took another approach with client authoritative but now I'm limited because of it

worn night
#

In what way client auth is limited?

#

Also feel you with that, I'm in a small team too

#

Thanks for the encouragement ^^

lean sail
# worn night In what way client auth is limited?

its hard to describe briefly cause its niche. My active ragdoll could pick up a box via a joint so this is 100% physics moving the player and box. If another player grabbed the box, they wouldnt see that the other player is moving the box via physics, they would just see its transform updating and stuff would just start freaking out. Someone (one person only) has to own the box so then i made it so only one can grab at a time. thats a pretty major limitation already
Same thing applies, players cant grab each other

#

if your game is pretty simple where physics isnt used in everything then you're fine. I tried using physics for everything

worn night
worn night
lean sail
worn night
lean sail
#

i havent seen that one, the ones i looked at were human fall flat, gang beasts, and something else i forgot the name of

worn night
#

Gang beast also has quite a lot of ragdolls

#

Maybe some of them has more info on that and how they implemented it!

#

I read that Fall Guys for example implemented their own networked ragdoll physics in Unity

lean sail
worn night
#

Now it's all on local multiplayer

#

Thanks for the advise, at least now I know where to start looking at 🥹

lean sail
#

either way goodluck, if you choose NGO i recommend joining the discord pinned in #archived-networking because its more active

worn night
worn night
#

🙌

undone mesa
#

Hello guys! So, I can drag a Sprite Image to a GameObject (like a cube) through Unity's Interface, but how can I do that in C#?

rigid island
undone mesa
celest iron
#

Take a look at the resources folder

#

It allows to get assets through code

limber dust
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; // Import the UI namespace for the Text component

public class Page : MonoBehaviour
{
    public Text PageCollect; // Reference to the Text component

    // Start is called before the first frame update
    void Start()
    {
        PageCollect = GetComponent<Text>(); // Get the Text component
    }

    // Update is called once per frame
    void Update()
    {

    }

    public void CollectPage()
    {
        // Check if PageCollectCount is not null before setting the text
        if (PageCollect != null)
        {
            Debug.Log("PageCollectCount is not null. Updating text.");
            PageCollect.text = "1 / 4";
        }
        else
        {
            Debug.LogError("PageCollectCount is null.");
        }
        Debug.Log("Page Collected");
        Destroy(gameObject);
    }
}

why is this code not working, when i pickup a page it runs the collect page method, but it will not update the text

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.

rigid island
shell scarab
#

purple squiggly 👀

quick elbow
#

Using UniTask, how do I await a System.Threading.Task from a library? I am calling an async method from another plugin that I've pulled in.

quick elbow
#

@leaden ice Maybe I'm a bit confused on how UniTask works... I've run into issues in the past with traditional c# async where I'd get Unity synchronization context exceptions and also just poor performance occassionally. I know they work, but it doesn't appear to be the ideal way to do it. Trying to use UniTask to asynchronously authenticate to Azure using the Microsoft.Identity library. I'm not sure how to use UniTask correctly here. Do I only need to change the return type?

cosmic rain
quick elbow
cosmic rain
#

If it works, then you probably do.

#

If still in doubt, perhaps look at their documentation. Not everyone here uses the library.

fickle lichen
#
public interface IAmGood
{
    public bool IsGood { get; }
}
if(gameObject.TryGetComponent<IAmGood>(out var component))
{
    if(component is null)
    {
        Debug.LogError("interface is null");
    }
}
```Hey I have a question about interfaces, if I'm using `TryGetComponent<T>()` method is it safe to use C# null operators? Or anything similar such as
```cs
component?.ToString();
cosmic rain
#

Probably yes.
But you don't really need a null check there anyway. It wouldn't enter the if block if the component is null.

fickle lichen
cosmic rain
fickle lichen
cosmic rain
#

If you were to use GetComponent instead and check the result for null, that wouldn't be save(in case of interfaces).

fickle lichen
cosmic rain
# fickle lichen Alright. I dunno if I told you, in the past I used to create desktop application...

It's pretty simple: unity overrides null checks for the purpose of preventing access to destroyed unity objects. But that override doesn't work with the ? operator, so you might be accessing an object that has been destroyed, causing an error down the line.

This is only relevant to situations where you know you destroy objects and might access them though. If you don't have such cases you might as well ignore that rule entirely.

foggy maple
#

been inactive from programming for a bit so im coming in like im freshly stupid

#

how do I like

#

im trying to do a vector 3 to offset another position

#

but I want it to be local to the transform's rotation

fickle lichen
foggy maple
#

probably yea

#

thank you

fickle lichen
#

Even if not necessary in my simple case, will always work in all scenarios in the future

#

Anyway, thanks PathThumbsUp

#
EditorGUI.DrawRect(selectionRect, new(1, 0, 0, 0.2F));
```Is there an opposite method? To stop drawing a rectangle? Or should I draw a fully transparent rectangle and pretend nothing is there? ![beluga](https://cdn.discordapp.com/emojis/1092430758720835615.webp?size=128 "beluga")
cosmic rain
spring cobalt
#

Hello! My top down player gets glitched in a wall when I move it towards the wall. The colliders aren't working properly, this is the video. Any fixes for this, thanks!

worn night
scarlet viper
#

if i have carefully selected values for certain variables, and want to multiply by Time.deltaTime , is there any way to preserve current values/proportions/ratios ? Because multiplying by time.deltatime will result in about 100 times slower values and i will have to spend time selecting proper values again

spring cobalt
west lotus
scarlet viper
#

I wanted it to remain its original value (eg 100)

west lotus
#

Dont multiply it then ?

scarlet viper
#

but i have to make it framerate independent

dusk apex
#

If you want to use 100 in the inspector but want the resulting behavior to be 10000, just have it multiplied by 100 in code.cs value = speed * Time.deltaTime * 100;

#

That way, you can work with smaller numbers to get the behavior of something larger.

scarlet viper
#

100 was just an example

dusk apex
#

Figure out what the magic number is. Delta time isn't a fixed number.

#

I'm assuming you're wanting to work with a smaller number under the inspector

west lotus
#

Im confused at what you are trying to do. Show some real code

dusk apex
#

Example: a normalized value

worn night
#

Also angular/linear friction can sometimes do that

#

Try to play with thay values too

scarlet viper
spring cobalt
west lotus
spring cobalt
dusk apex
#

Multiplying by delta time would simply give you your value after one second

#

Instead of per frame

west lotus
mellow zinc
#

can anyone help me make an obstacle or refer me to a video that would help. unity 3d

mellow zinc
#

How do I make something happen when something colliders with something

#

for example my capsule colider and a box colider

wide dock
#

Basically include any of these methods in your script that is attached to the object with the collider, and that method will be called when the conditions are met

mellow zinc
#

its working now

mellow zinc
wide dock
#

You could check what you're colliding with first

mellow zinc
#

its the ground

wide dock
#

for example the tag

#

and execute your code only if the tag is correct

mellow zinc
#

okay, I made a tag called obstacle. Now what?

#

void OnCollisionEnter(Collision collision)

#

thats my code

wide dock
#
void OnCollisionEnter(Collision collision)
{
  if (collision.gameObject.CompareTag("obstacle"))
  {
    // Do stuff
  }
}
mellow zinc
wide dock
#

then you probably don't have a tag named obstacle

#

remember that the tag is case-sensitive

mellow zinc
wide dock
#

the tag is Obstacle, not obstacle then

mellow zinc
wide dock
#

change it to Obstacle in code

mellow zinc
#

It already is

wide dock
#

then it should be working

mellow zinc
#

The error is gone now but it doesnt work

#

Here is the Collider for the Obstacle

quartz folio
#

That's a trigger

wide dock
#

OnCollisionEnter won't work for triggers at all

#

Switch to OnTriggerEnter

mellow zinc
#
        {if (collision.gameObject.CompareTag("obstacle"))
        {
            transform.position = SpawnPoint.transform.position;
        } ```
wide dock
#

Trigger methods have a Collider param

quartz folio
mellow zinc
#
    {
       
        {
            transform.position = SpawnPoint.transform.position;
        }``` this works now but how do i make it so that only objects with the tag trigger it
wide dock
#

Similarly to how you did it before

#

This time you can ommit the .gameObject part tho

#

other.CompareTag("Obstacle")

mellow zinc
#

Yes I saw that on a tutorial but why do we write "other"?

wide dock
#

because that's the collider variable name

#

and you want to check the tag of that colliders GameObject

quartz folio
#

you can call it what you want, it's the other collider that's involved in the collision

mellow zinc
wide dock
#
private void OnTriggerEnter(Collider the_thing_I_collided_with)
{
  if (the_thing_I_collided_with.CompareTag("Alien")
  {
    // Kill alien
  }
}```
quartz folio
wide dock
mellow zinc
#

Lets go it works

#

Thank you guys so much

odd tinsel
#

Hello everyone,
I am trying to create a non-monobehaviour script with a static class inside it which should function as a factory of GameObjects
and I want to access a property of the class from the Unity inspector, is it possible?

dusk apex
#

Serialized Reference

#

Assuming you want to simply reference the script

#

If you're wanting to inspect the fields, no.

odd tinsel
#

I want to access this factory class from a monobehaviour script but I also want to change a list of GameObjects on the fly using the inspector
I do not want to attach this script to a certain GameObject (hence not monobehaviour)

dusk apex
#

Consider scriptable objects for creating instances without game objects

odd tinsel
#

Oh I totally forgot that's an option

#

Thanks :D

copper star
#

Does anyone know why this code wouldn't be finding any of the colliders on my ragdoll?

#

Collider[] colliders = GetComponentsInChildren<Collider>();

        foreach(Collider hit in colliders)
        {
            Rigidbody rb = hit.GetComponent<Rigidbody>();
            rb.AddExplosionForce(explosionForce, this.transform.root.position, radius, upwardsForce);
        }

#

this runs within a simple coroutine that gets called on start

somber nacelle
copper star
#

yeah on the parent of the ragdoll

#

just on the "Brute(Rigged)" GameObject

somber nacelle
#

are those components inactive at the time you call this method?

copper star
#

i don't believe so

somber nacelle
#

well GetComponentsInChildren will only find active components unless you pass true in as a parameter to find inactive ones

copper star
#

yeah i'm aware of that much

#

i've just tried to add a rigidbody to the root and addexplosiveforce to that but it didn't work either

somber nacelle
#

okay well the possibilities for why it may not find the components is either that they are inactive or that you are not calling this method on the object you think you are

#

add this between the GetComponentsInChildren call and the foreach loop:
Debug.Log($"{name} {GetInstanceID()} has {colliders.Length} children colliders.");

copper star
#

ummm so it didn't add anything to the console

#

but i confirmed that it definitely ran the code using the visual studio debugger

somber nacelle
#

either that code isn't actually running, or it is happening on a different thread somehow. or you just didn't save/compile after adding that line

#

oh or you are ignoring errors in your console

copper star
#

....uhhh yeah i forgot to save and compile

#

lol

#

result

somber nacelle
#

there you go, it is successfully finding the colliders

#

so what is the issue then

copper star
#

So something is wrong with the way the explosion force is running then

#

because I'm an idiot and thought it wasn't finding the colliders because my breakpoint was on that line

#

but it's just not adding any force to them EDIT : force too low --> fixed

odd tinsel
#

Hey, does anyone know how can I call a method from a scriptable object from its editor?

somber nacelle
#

you can use the ContextMenuItem attribute or something like naughty attributes or odin which both have a Button attribute. or you could create a custom inspector that draws a button to call the method

odd tinsel
#

Yeah I already created a custom inspector with a button but now I'm trying to run a method when I click the button

#

And I don't know how to access the method from the editor
The method is in a different script

somber nacelle
#

and make sure to actually provide context. you haven't shared code so i have no idea how you've set up your button

fickle lichen
# cosmic rain Don't you need to call that every frame? To stop drawing, just don't call it.
public static class Auxiliary
{
    static Auxiliary()
    {
        EditorApplication.hierarchyWindowItemOnGUI += HierarchyWindowItemOnGUI;
    }

    static void HierarchyWindowItemOnGUI(int instanceID, Rect selectionRect)
    {
        // ...
        EditorGUI.DrawRect(selectionRect, new(1, 0, 0, 0.2F));
        // ...
        EditorApplication.RepaintHierarchyWindow();
    }
}
```Oh, okay. It's a method I've connected to an event so I dunno how often it's being called ![catStare](https://cdn.discordapp.com/emojis/1092430769508589578.webp?size=128 "catStare")
#

I guess I need to check my if() statements and how often event hierarchyWindowItemOnGUI is being called by Unity

thick socket
#
[SerializeField] private EnemyIdleSOBase EnemyIdleBase;
public EnemyIdleSOBase EnemyIdleBaseInstance { get; set; }
private void Awake()
{
        EnemyIdleBaseInstance  = Instantiate(EnemyIdleBase);
}```
Good or bad idea to do this for SO?
somber nacelle
#

nothing wrong with that since it will allow you to use serialized data assigned in the inspector on the SO without actually modifying the SO at runtime (since that would change the serialized data in the editor).

thick socket
#

(I've used SO a lot...but not getter/setter and certainly no instances 😄 )

somber nacelle
#

my only note for that would be to change the name, there's not much point in including Instance in the name for hte property

thick socket
#

sounds good, was following a small tutorial by Sasquatch B Studio and figured I doublecheck that hes doing things correctly 🙂

#

too many videos I've watched that had horrible coding advice lol

#

just watched him move lines of code "up" in Visual Studio with a shortcut...and then highlite "private" on all 4 variables and rename them to [SerializeField]

#

how do you do that 😄

thick socket
#

ctrl+w highlights word...not sure how to grab the one above/below it to highlight also

somber nacelle
#

it's multi caret selection

thick socket
rancid halo
#

I'm having some issues with occlusion.

I have a main_scene that is always loaded and handles most of the logic. (basically has the canvas and camera's, with no largely nothing else, so doesn't have any occlusion data)

I load the map scenes additively, and swap them, depending on what level I'm in.

In editor I can see the occlusion working correctly in each individual level, but when loading them in additively during runtime, it's like the occlusion data never loads.

knotty sun
#

dont cross post

fringe ridge
#

so, what the hell. SpriteRendeder.bounds.size.y gives 1.37 when the sprite is smaller and 0.58 when the sprite is bigger? it's completely random values

#

i'm scalling it down with transform.localScale

#

also the pivot point is at the bottom of the sprite

slate lark
#

The inner if statement is not working.
Any Mistakes?

rigid island
#

it could not possibly be true

#

put a tag on it, check for tag instead

#

eg if(other.gameObject.CompareTag("BoostTag")

leaden ice
#

they are different objects, categorically

leaden ice
slate lark
rigid island
#

👍

slate lark
mellow sigil
#

They have to be the exact same collider on the same instance. The collider of a prefab != the collider of an instance

dusk plume
#

hi i have an question
i am using physic.checkbox
is there an way to get the gameobject inside it?

knotty sun
dusk plume
knotty sun
#

lots

dusk plume
#

physic.boxcast works?

dusk plume
#

i am gonna do it

leaden ice
#

OverlapBox is the same as Checkbox but gives you the information about what was there

dusk plume
#

tysm

swift falcon
#

My transform.Translate's are not working correctly,
Code Snippet: WhitePieces.transform.Find("WKing").Translate(new Vector3(STATIC_SquareSpace * 3, 0, 0));

Vector Output: (-0.144, 0, 0)
(Correct as STATIC_SquareSpace is -0.048)

King location:
Before: 0, 0, 0
After: -0.07199856, -7.638242e-06, -50.00004

leaden ice
swift falcon
#

because 0, 0, 0 + -0.144, 0, 0 is not -0.07199856, -7.638242e-06, -50.00004

leaden ice
swift falcon
#

thats right

#

it needs to be x -0.144 from parents position

leaden ice
#

also is this for chess or something? Translate seems like a poor approach. You should have some kind of Grid class that simply has a mapping from grid coordinates to world coordinates

swift falcon
#

Probably, but im just messing abt so I wasnt trying to get the best approach

leaden ice
#

so it's hard to say what's going on

#

I'm 100% sure transform.Translate is not buggy though

#

you're most likely misinterpreting something

leaden ice
#

so if the object is scaled or rotated, it's going to skew things

swift falcon
#

What other context would you need, and maybe I just assumed transform.translate, translated it from its current position

leaden ice
#

it does

swift falcon
#

so 0x + -0.144x would be -0.144x not -0.07199856x

leaden ice
leaden ice
#

and no

#

not necessarily

#

because localPosiiton for example is in the parent's coordinate space, but Translate operates in the object's own coordinate space

swift falcon
#

0 is the transform in the unity inspector
-0.144 is the x of the vector 3 passed into translate
-0.07199856 is the position in the unity inspector after translating

leaden ice
#

and you are confusing the parent's coordinate space for the object's own coordinate space

swift falcon
#

Probably

#

But telling me im confused is not helping :/

#

I know im confused bc if I wasnt it would be working

leaden ice
#

I'm explaining the source of your confusion

#

Translate operates in the object's own space.
localPosition (the position shown in the inspector) is in the parent's coordinate space

#

and your king is probably scaled / rotated

swift falcon
#

its not

leaden ice
#

so those coordinate spaces are not the same

swift falcon
#

Im aware of that

#

Still doesnt explain what it means

leaden ice
#

If you want to move the object in its parent's coordinate space just add to the local position

swift falcon
#

Or more accurately, how I would edit translate the local position and not the global position

leaden ice
#
Transform king = WhitePieces.transform.Find("WKing");
king.localPosition += new Vector3(STATIC_SquareSpace * 3, 0, 0);```
swift falcon
#

I got it dw

#

Ty ty for the help

leaden ice
#

rather than manually moving stuff

swift falcon
#

I know, As I said I wasnt going to the best approach I was just going for a quick one, but apprently it wasnt quick bc im bad at translate

#

lmao

leaden ice
swift falcon
#

Im aware

#

I duno if I am doing something stupid but for some reason my prefab isn't updating correctly?

When I double click it in the project window it's correct but then when I drag it into scene it doesn't match up

#

In scene if I click the root there are no overrides

#

When I duplicate the prefab in the project, the duplicate is correct? what

#

I'm chalking this one down to a bug

#

Weird... I didn't even change the prefab, it just randomly broke

civic palm
#

Trying to create a sprite from the editor and not at runtime

#

However the sprite shows up as "type mismatch" in the field

#

What am I missing?

rain crater
#

Hey, quick question, should I use only one instance of System.Random (in a Singleton, for example), or is it better to create a new instance per every script where it's needed?

dusk apex
rain crater
#

generally I don't need multiple seeds, but I'm also kinda asking, which way is better for writing good code.
Making only one in a singleton seems to have the advantage, that I won't have to deal with many instances, and so less memory should be used

lucid valley
#

Unity has a static random you can use instead of making your own singleton

rain crater
#

oh, that is nice

#

thanks!

zinc parrot
#

Hey so say I have a compute shader and a rendertexture
on the CPU the rendertexture is defined as argbfloat
on the gpu its defined as RWTexture2d<uint4>
I encode a distance into the z component by doing asuint(distance)
how do I read the float value back on the CPU?(I really only need the center pixel to autoset focus distance)

late lion
livid kelp
#

Hey there quick question, how do i add stuff to the tilemap, please?

thick socket
#

dumb question...why do I need the "field:" here?

[field: SerializeField] public float CurrentHealth { get; set; }
knotty sun
thick socket
#

Could someone explain the difference between these 2...I've tried to look it up in the past but still dont get why I would pick one over the other

#
[field: SerializeField] public float CurrentHealth { get; set; }
vs
public float CurrentHealth```
#

I get if you have a get; private set; but not a get; set;

knotty sun
#

no difference at all

thick socket
#

sweet thanks 😄

simple egret
# thick socket sweet thanks 😄

Properties are the de-facto standard way of exposing data outside of a class. Fields should not be public (as per the C# conventions)
Also, properties allow you to replace the get; set; with your own code logic, to return custom data, validate the value you're setting, etc.
No not quite a "no difference at all"

knotty sun
#

as he asked the question there is no difference at all

simple egret
#
private int _age;

public int Age {
  get => _age;
  set {
    if (value < 18)
      throw new InvalidOperationException("Too young!");
    _age = value;
  }
}

Validation with custom setter example

thick socket
#

still use the get;set one?

simple egret
#

Still use a property for exposing public values

rigid island
thick socket
simple egret
thick socket
#

redoing all my old enemy code rn...fixing all my old stuff is "fun" 😭

simple egret
# knotty sun why?

Conventions. And if you ever need to add validation to the value when you set it, update the setter and it's done. With a field, you'd need to add the validation to all the call sites of said field

knotty sun
#

are we talking about game dev here or are you trying to teach app dev?

simple egret
#

Same thing for both

#

Unity uses properties too lol

knotty sun
#

not at all, two totally different paradigms

simple egret
#

It's just how you code properly in C#

thick socket
#
public Stats stats;

public virtual void SetStats(int tmpHP, int tmpAtk)
    {
        stats.SetStats(tmpHP, tmpAtk);
    }

Is there a way to do this for getter/setter?

#

or just convert the public Stats stats; to a get;set; and leave function?

simple egret
#

If Stats isn't meant to be changed after it's set once, then you can do a public Stats Stats { get; }, and you'll still be able to set individual values inside Stats. Like doing Stats.Something = 42;

#

The absence of setter prevents the Stats to be changed entirely, not one of its properties

thick socket
thick socket
#

wow chatgpt does things that are so smart that I wouldn't have thought of sometimes 😄

#
if (playerTransform.position.y - transform.position.y > 1)
            {
                jump = true;
                down = false;
            }
            else if (playerTransform.position.y - transform.position.y < -1)
            {
                jump = false;
                down = true;
                //Debug.Log("enemy down");
            }
            else
            {
                jump = false;
                down = false;
            }
#

to

#
float verticalDifference = playerTransform.position.y - transform.position.y;

jump = verticalDifference > 1;
down = verticalDifference < -1;
thick socket
#

NullReferenceException: Object reference not set to an instance of an object
Feet.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/Scripts/sprites/Feet.cs:15)

The parent declaring isGrounded

    public bool isGrounded { get; set; }
 private void OnTriggerEnter2D(Collider2D collision)
    {
        var tag = collision.gameObject.tag;
        if (tag == "Wall" || tag == "Floor")
        {
            ***parent.isGrounded = true;***
        }
        else if(tag == "Platform")
        {
            parent.isGrounded = true;
            parent.platform = collision;
        }
    }
#

line15 has the stars...why would it say no reference?

knotty sun
#

parent is null

thick socket
#
public class Enemy2 : Fighter2, ITriggerCheckable
knotty sun
#

dont see anything there called parent

thick socket
#
public class Feet : MonoBehaviour 
{
    Fighter2 parent;
    private void Start()
    {
        parent = GetComponentInParent<Fighter2>();
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        var tag = collision.gameObject.tag;
        if (tag == "Wall" || tag == "Floor")
        {
            parent.isGrounded = true;
        }```
knotty sun
#

ok, but it can still be null, just because you do a Find does not mean it finds it

thick socket
knotty sun
#

obviously because you do not have the component Fighter2 in this or a parent object

thick socket
# thick socket

this screenshot should show the parent has an "Enemy2" class

#

and then I showed code that says Enemy2 extends Fighter2

knotty sun
#

yes, and Enemy2 is not Fighter2

thick socket
#

Fighter2 is the one with "IsGrounded"

#

oh nvm Im stupid

#

everything Im saying is working as intended

#

another object is hitting the ground the same time that isn't Fighter2

#

thanks for the help 😄

heady hull
#

this error popped up when i imported visual novel maker asset from the asset store,, how do i fix this??

rigid island
#

line 13, column 9

#

thought you should probably just use TextMeshPro instead of Text as thats now obsolete/legacy too

limpid owl
#

is it a good thing to fire an event in property getter or setter ?

somber nacelle
#

that's a typical pattern, nothing wrong with doing that

limpid owl
somber nacelle
#

yes

limpid owl
#

thanks

rigid island
heady hull
rigid island
somber nacelle
#

if it is in an asset then you probably need to give an assembly reference to its asmdef

heady hull
#

nope!! imported everythin

heady hull
#

where is that located?? im sorry for being so arrogant

rigid island
celest crescent
#

is anyone using scriptable objects that have a list of other (child) SOs with AssetDatabase.AddObjectToAsset and undo feature?

heady hull
#

i cant find it.. im so so sorry

rigid island
#

in the search bar

#

t:asmdef

#

also show package manager with Packages: In Project selected , doesn't hurt to make sure you do have UI package installed

swift falcon
#
if(gameObject){//do stuff};
if(gameObject != null){//do stuff};

perhaps a stupid question, but do this achieve the same thing in unity?

#
if(gameObject??false){//do stuff};

a bit confused on which one to use when doing null checks that is reliable

somber nacelle
swift falcon
#

okay, thank you 😄

#

i read this post


Unity overloads the == operator. Thats why if(gameObject == null) will return false even though the object is destroyed ( but not collected by the GC )

The only safe way to do this check is avoid the == operator and use the ?? instead - that one is not overwritten and plain C#

if(gameObjectToTest??false){
    // this will only execute if gameObject is not destroyed
}```

but I don't know if it still applies
somber nacelle
#

that information is backwards. == null will return true if the object is destroyed but null conditional and null coalescing operators will not be able to detect that the object has been destroyed

swift falcon
#

oh, okay good to know! so i'll just start using ```cs
if(object)

and it will be fine?
somber nacelle
#

like i said before, that exactly the same as comparing to null with the comparison operators == and !=

#

using those overloaded operators is the only safe way to check if a UnityEngine.Object derived object is destroyed or null. null conditional operator ?. and null coalescing operator ?? and ??= do not use the overloaded equality operator to check for null so they can only check for true null, but when unity destroys an object (which is not really a concept that c# has) it uses what is generally referred to as a fake null because c# doesn't really have the concept of destroying objects like that so variables referencing that object are not actually null until you assign null to them manually

swift falcon
#

thank you boxfriend, it much clearer to me now :)!

hard viper
#

I save level files as JSONs in the application’s persistent directory of my computer. I also want story mode levels that come along with the build. How do I target files in project’s file directory?

#

Like, if I have Level1.json, my path is something like /Users/Loup/blahblah/Unity/MyProject/Assets/Levels/Level1.json
But how would I get the build to target that level file when it goes onto someone else’s machine?

shell scarab
#

if Vector2s are not serializable to a file, I'm interested to know how they're saved in a SO for example?

shell scarab
#

try to serialize a Vector2 to a file

cosmic rain
#

Serialize how? There are many ways to do it.

spring creek
cosmic rain
#

What makes you so confident about it?

spring creek
shell scarab
#

because when you try to serialze a Vector2 to a file it literally produces an error saying that the type isnt marked as serializable.

quartz folio
#

Must be impossible then

cosmic rain
spring creek
shell scarab
#

no, you clearly can. I guess you guys can't read because I asked how it's done when they're not marked as serializable.

#

I don't appreciate this hostility

quartz folio
#

You didn't ask that

cosmic rain
warm aspen
quartz folio
#

You asked how it's done in SO's which is YAML using Unity's serializer