#archived-code-general

1 messages Β· Page 407 of 1

modern creek
#

like.. you've pasted some code that has validation that doesn't make sense.. is this AI generated..? if so - don't do that (this is why.. it doesn't make sense)

#

yeah this code makes no sense at all.. i'd take a step back and write this by hand

cursive lance
#

like this then?

modern creek
#

your code should (in general) make sense if you read it in "plain english"... Your code reads like this:

If the enemy hasn't lost life and the enemy's SCENE is valid, destroy the enemy. Then, destroy the enemy's health bar.

#

That.. doesn't make sense

cursive lance
#

[HideInInspector] public bool hasLostLife = false;

modern creek
#

So .. yes? but if you're about to destroy the enemy, why are you doing enemyData.hasLostLife = true? You're just about to destroy that object

vestal arch
tawny elkBOT
cursive lance
vestal arch
#

make sure to follow all the steps

somber nacelle
#

it looks configured πŸ€”

modern creek
#

So.. your code is all over the place right now and I suspect (?) it's because you're just plugging questions into chatgpt for this.. which is a surefire way to end up with code that's broken and you have no idea why, and we can't really help either since the intent isn't clear. AI generated code might compile and "look nice" but it won't make any sense, and your questions won't be able to make sense either since you don't know what the AI is trying to do.

If you want to delete a game object - then just Destroy() it like you're doing, and having the player singleton for Player.instance.LoseLife() is fine but .. you haven't told us what EnemyData is (a plain class object? a monobehaviour? if it's a MB, is it a prefab? a singleton that contains a list of enemies? etc)

vestal arch
#

you still seem to have extraneous errors on random methods

vestal arch
somber nacelle
#

those are warnings from rider about expensive operations

vestal arch
#

ohh, mb. what do errors in rider look like?

cursive lance
modern creek
#

same as VS - but those warnings are a bit close to that look, i think

cursive lance
#

the enemies are prefabs

modern creek
#

ok - what's Select Enemy? Do you mean selected enemy?

#

and what's that script on? some sort of singleton "enemy manager" or something?

#

or is that a single enemy

modern creek
#

ok so .. your enemy spawner needs to instantiate a prefab instance - which will progress along the waypoints and then when it gets there, you destroy it

cursive lance
#

yeah correct

modern creek
#

just stick your whole EnemySpawner into hastebin or some other code sharing site so i can see it

somber nacelle
modern creek
#

and Enemy too

cursive lance
#

this is enemy

modern creek
#

the whole thing, not just 2 functions from Enemy

cursive lance
modern creek
#

what's Enemy.enemies? or Enemy.SpawnTemporaryEnemy()

vestal arch
modern creek
#

i don't see where you're instantiating a prefab

cursive lance
#

i get this when putting the destroy outside the if btw

modern creek
#

ok this is backwards - you should put all this code that manages enemIES (plural) in the spawner

#

a single enemy should only take care of itself

#

public class Enemy implies "this is one enemy" not "this is all the enemies"

#

what does SetEnemy() do or mean? your naming should be more clear..

#

line 155 is where your problem is

#

you're creating a new enemy with Instantiate() properly... and then doing nothing with it

#

the game object you create on line 157 is what you want to destroy

#

gosh this code is upside down... you're creating a list of "enemy data" to hold your active enemies.. a separate list of "enemy health bars" to hold your enemy health bars.. but you're not trying to delete the instances of those things that you create during gameplay, but the original prefab.

So, take a deep breath, back up and read up on what a prefab and an instance are - you're kind of flailing and just trying to fix lines of code without understanding what you're doing here and this is a mess .. sorry for the blunt words.

In unity, you have prefabs and instances of those prefabs. Your prefab is what you'll link in the inspector, but at run time, when you want to create a single enemy - you INSTANTIATE (create a copy of a prefab) an enemy, and track that as it runs around the world and does stuff - and when it's done, you destroy that copy (not the original prefab).

#

All of this "enemydata" should be a single script that lives on a single instance - like.. an enemy should know it's own health and update it's own health bar. Your "enemy spawner" shouldn't be trying to coordinate and manage all these specific things about an enemy.. your enemy spawner should just ... spawn enemies, which you might not even really need to track because the enemies will delete themselves later

cursive lance
#

yeah it manages a lot of things but it also deletes the instances too right because i only get 1/2 warnings

modern creek
#

So that's fine, but on line 157 you make a new instance but you don't add it to your list of enemies, so ... you won't be able to delete it

#

anyway.. i have to run but maybe someon else can pick up the thread here.. but in a nutshell you need to understand the difference in prefabs and instances

cursive lance
#

thank you for the help tho will try to see if i can get a bit further πŸ™‚

modern creek
#

And don't use chatgpt (if you have been).. it's not gonna really help you long term (or short) πŸ˜›

cursive lance
#

@heady iris do you have some time to look at my code (spaghetti)?

vestal arch
#

if you need help or advice or review just ask

#

don't ping speciifc people for help

cursive lance
#

okie dokie πŸ™‚ just dunno where to start from here

vestal arch
cursive lance
#

then help me lol :/

vestal arch
#

what is your question

cursive lance
#

i dunno how i should fix the
you're creating a new enemy with Instantiate() properly... and then doing nothing with it
the game object you create on line 157 is what you want to destroy

somber nacelle
#

Instantiate returns a reference to the object created, store that reference in a variable and pass that object to the Destroy method instead of passing the prefab to Destroy

cursive lance
#

yeah that sounds nice but then i still don t know how i should implement that notlikethis

heady iris
#

stop and think about what each object represents

#
Foo prefab;
Foo instance = Instantiate(prefab);
cursive lance
#

public GameObject selectEnemy; here it takes the enemy from the list wich is a prefab
and here it picks up the prefab as new enemy
GameObject newEnemy = Instantiate(enemyData.selectEnemy, spawnPosition, Quaternion.identity);

#

but i get the warning only once or twice that is weird

somber nacelle
#

now look at what you pass in the Destroy method

cursive lance
#

the gameobject

somber nacelle
#

which gameobject

cursive lance
#

public GameObject selectEnemy;

somber nacelle
#

which you just said is what?

cursive lance
somber nacelle
#

yes. so you are explicitly passing a prefab to Destroy which is the whole problem.

heady iris
#

if you don't want to destroy a prefab, then...don't do that

cursive lance
#

but how can i then acess the new enemy and why do i only get 1or 2 warnings?

somber nacelle
#

where is that reference to the instantiated enemy stored?

cursive lance
#

public List<EnemyData> enemies = new List<EnemyData>();

#

right?

somber nacelle
#

christ, looking through your code and this is a lot of spaghetti because you're storing prefabs in the same exact variable as the instantiated object. use the debugger to figure out where you're passing an EnemyData that has a prefab assigned to its selectEnemy.
like wtf is the point of this:

if (enemies.Count > 0)
{
    SetEnemy(0); 
}

if all that method does is this:

public void SetEnemy(int index)
{
    if (index < 0 || index >= enemies.Count)
    {
        Debug.LogError("Invalid enemy index!");
        return;
    }
}
heady iris
#

because you're storing prefabs in the same exact variable as the instantiated object

this is a very bad idea -- the meaning of the variable now depends on whether you've instantiated something or not

cursive lance
cursive lance
#

so what should be the next step?

#

like dunno where i should look at the instantiated form of the variable

somber nacelle
#

use the debugger to figure out where you're passing an EnemyData that has a prefab assigned to its selectEnemy

cursive lance
#

but that is this part? im so confused πŸ˜… UnityChanHuh

#

this?

somber nacelle
#

do you know what a debugger is?

cursive lance
somber nacelle
#

and you've used it to actually inspect the objects you are working with?

cursive lance
#

just not really sure how to look for it have used the debugger before but not that expierienced with it

vital oracle
#

I asked this earlier, but didn't get any answers. Its regarding saving/loading data.

Basically I have a class that is created at runtime by referencing a scriptable object which sets its base data values, int, float, strings.

This is then added to a List and throughoout the game the data values are modified from their original state. These classes are also referenced by other gameobjects in the scene.

What is the best way to go about saving this list of classes in their runtime state in a way that can also be loaded to recreate the list? Is it possible to save other objects/classes that have an associated reference to the class in this list?

cursive lance
#

gonna go sleep now past midnight guess i will try to fix it then :/ annoying bug

vital oracle
cold parrot
#

also, FYI (to avoid confusion), classes that have been instantiated (via new or any other way) are called objects or instances.

vital oracle
cold parrot
#

so you can have multiple objects that have the same type which is defined by a class

cold parrot
#

most people don't do that, cause its complicated and instead just inject a prefab instance with saved data

#

if you use JSON, it will serialize the individual objects in the list

#

you can't really serialize a list without serializing its contents, i.e. it would be pointless

vital oracle
cold parrot
heady iris
#

yeah -- you instantiate a thing, then "rehydrate" it

#

This can be a recursive process.

vital oracle
heady iris
#

Create a thing, restore its state -- thus spawning more things, whose states you also restore

#

The real fun begins if you need to remember relationships between objects!

cold parrot
#

the above mentioned relationships between objects are trivial to solve when you build your entire system on top of unique IDs (UID) and UID-lookups. It is much more difficult if the relationships are only ID-based in the serialized data.

#

a popular approach is a GUID identifier serialized as a string

vital oracle
#

So with my initial example. I have the List of class instances. Each one has it's data modified from it's base.

To simplify say each instance in the List just has one int variable. If I make the base class serializable then save the List to a JSON should each instance be saved with the runtime data?

Then when I load the game I can create a new List and load in all of the saved class instances in the JSON?

cold parrot
#

you can restore the entire list from the JSON data

#

everything will be automatically instantiated and put into the list

#

i think you are currently imagining the part that this libary will do automatically for you as the "problem"

#

which it is, but thats why the library exists

vital oracle
cold parrot
#

conceptually what you can do, so long as you are using plain C# objects, you can make up an arbitrary structure of objects and just "save it to disk" and then just "restore it from disk".

heady iris
#

Yeah -- it requires more finesse when you're dealing with Unity objects

cold parrot
vital oracle
#

Also part of my problem is I wasn't thinking about saving when I coded my game. I think I need to rework a lot of it before it gets too complicated so I know exactly what needs to be saved for everything. I've never made a game that is long enough to require saving.

cold parrot
vital oracle
cold parrot
vital oracle
#

One other aspect I'm confused about is how to save multiple pieces of data from multiple classes in one JSON. Say I have player stats, an inventory and then the world state data. So I need to save data from 3 classes in one JSON correct?

#

If everything is named unique will the library sort that out?

cold parrot
heady iris
#

there will be some grand SaveData object that holds references to every other object

cold parrot
#

one popular approach is to have a game state class, something like

// pseudocode
class GameState {
    Actor[] actors;
    Key[] unlocks;
    float playTime;
}```
and just save/load an instance of this
#

then have all game objects look into that GameState to figure out their state and maybe what needs spawning.

#

but you can do much more complicated things.

heady iris
#

you'll discover that it's tricky to record everything that's happening in your game

#

you want to record enough to reasonably reconstruct the original game state

cold parrot
#

a good strategy is to design a game in a way that only a trivial amount of data needs to be saved. Some games get away with just saving a list of checkpoints as "passed".

vital oracle
#

Thanks, this will help me get going. I think the main idea of reconstructing the game state is where I was overthinking. I just need to figure out all the data that changes in my game, save it to JSON, then write methods to load the JSON data and reconstruct the object's state when saved.

heady iris
#

yeah, if you can limit the preciseness of your saves, it'll be much easier

#

You don't have to remember every enemy's position, health, and velocity if you only save at checkpoints after defeating a room's worth of enemies

cold parrot
#

imagine a game in the old days of console gaming, where you had no memory-cards... these games created savegames by giving players a N-digit code, that would bring them back to a previously passed checkpoint

#

also, since saving/loading on consoles today is also a truly annoying thing, most console games do only save checkpoints. --> primarily because checkpoints dont easily break when you patch your game to fix bugs or add new content.

vital oracle
#

My game isn't really real time, its more a management sim. So my plan is to only allow saving during the parts of the game where no direct player input happens. The player sets things up and then plays out the day. So say they finish day 10. I can save all the data to reconstruct their progress on day 10. Day 11 is then generated using that day 10 data.

#

The reconstructing concept I think helped me stop overthinking it.

vital oracle
#

I'm probably going to consolidate some classes and then create one SaveManager like mentioned that will hold all the object references.

#

The days are short in the game like 10-15 min so I don't really want to think about trying to save all the runtime positions and states of the NPCs. They have simple decision trees that run on timers. i.e. look around, find thing, go to thing, take thing to register, buy thing, leave store.

cold parrot
vital oracle
#

I think letting the player save between days is plenty.

cold parrot
#

this will simplify so many things you aren't even aware of yet

vital oracle
cold parrot
#

makes sense

vital oracle
#

Eventually maybe have multiple save slots, but for now I'll keep it simple.

cold parrot
#

thats mostly a file management & UI problem

#

you will also probably want 2 types of save files, one for the player's settings/achievements/meta-progress/statistics, and one the for the actual game-session. But that depends a lot on your design.

buoyant ermine
#

It's likely my scripting, but when going from a silent video to a video with audio, the audio does not play. clip change is dealt with in scripting by changing the clip in the player and then sending the videoplayer the play() command

rugged pond
#

Hello, i'm wondering if there any perfomance difference in using switch or if/else statement in function which should be called often or if it insignificant. I've tried to find something similar but all i found is a switch superioty if used long condition list

chilly surge
#

Depends on how you are writing the if ... else if ... chain, but yes compiler is pretty smart that in some situations it can lower switch code to better if ... else if ... chains that you would intuitively write.

#

But also keep in mind that this is micro optimization territory, you shouldn't go rewrite your code and make it worse just because it's tiny tiny bit faster.

rugged pond
#

Its simple code which should be called often and basically i use if to check if an item is a weapon, consumable or something else to understand what function to call next. I didnt wrote much yet and if its possible i would prefer to make it in a better way from the start

chilly surge
#

Optimize for code readability/maintainability first, then if you positively identified that it's a problem (I can almost guarantee you it won't be) by profiling, then optimize.

#

You are way more likely to get significant performance gains from changing some O(n) code to O(logn), than optimizing this piece of code by rewriting if ... else if ... chain into switch and hoping compiler does something smart.

rugged pond
#

Got it, thank u

atomic kindle
#

why is this happening?

#

in awake it also produces an error

rigid island
atomic kindle
#

yeah I figured it out thanks

#

Im silly

quartz folio
#

It makes no sense to do that too

atomic kindle
#

shhh

#

im a neoob

quartz folio
#

Assignment only happens once, so it would only be getting the key when the object initialised

atomic kindle
#

how can I print somethign to check that it is working in unity?

rigid island
quartz folio
atomic kindle
#

Lemme go to the beginner channel

earnest gate
#

Can anyone tell me about C#?
I wonder if what I know is correct.
Please. If anyone has just one person, please text me.

#

Please!

earnest gate
#

What??

rigid island
#

did you even read it ?

earnest gate
#

hey i am

#

I want to be good at English

#

There are several ways to do that,

#

I think it's a good way to communicate with people overseas.

#

Information in foreign countries may be different from information in our country.

astral flame
#

Hi, i have a big problem with my script: https://pastebin.com/spKrmcy0
although the logic (to me) seems correct for some reason the whole ConnectToNextConveyor() doesn't repeat even though it is in the Update().
I also have a problem when i try to change Orientation it doesn't change the raycast orientation, but i guess its connected to the fact that id doesnt repeat!
Can anyone help me please <3

earnest gate
#

That's why I saved people

rigid island
earnest gate
#

It's not a question. Find someone to compare with while communicating with each other!

#

Maybe...

rigid island
#

its very unlikely tbh

earnest gate
#

That's highly unlikely?

#

Oh, sorry the translation is weird.

astral flame
#

!code

tawny elkBOT
fleet gorge
#

if you do not have a question about c# don't ask

#

this channel is for help on c#, not conversation or communication

earnest gate
#

yes

fleet gorge
#

ask your question here, rather than asking to message someone

astral flame
#

i need help with c#!

fleet gorge
#

how may we help

astral flame
#

i have a big problem with my script: https://pastebin.com/spKrmcy0
although the logic (to me) seems correct for some reason the whole ConnectToNextConveyor() doesn't repeat even though it is in the Update().
I also have a problem when i try to change Orientation it doesn't change the raycast orientation, but i guess its connected to the fact that id doesnt repeat!

sleek bough
# astral flame !code

Not need to spam. You've just posted your question. Have some patience. If you want to improve your question post more details.

astral flame
#

i was just wondering if i posted it in the right format

sleek bough
#

@astral flame Need to attempt debugging it yourself as well. Debug messages are not to just put success messages, check conditions states to understand what's happening. See debugging guide pinned in #πŸ’»β”ƒcode-beginner

cursive lance
maiden trellis
#

where instance is a GameObject and not a prefab but instance

cursive lance
#

GameObject newEnemy = Instantiate(enemyData.selectEnemy, spawnPosition, Quaternion.identity);

sleek bough
cursive lance
#

like this?

sleek bough
# cursive lance

Show exact line that is throwing the error and what you are printing out to console

cursive lance
sleek bough
#

The code

cursive lance
#

mostly is about handling the waypoint right

sleek bough
#

Do you see which prefab it points to?

#

This is what you are destroying.

cursive lance
#

those 2

sleek bough
#

You didn't use context with Debug before the line like I told you to either

cursive lance
#

so just put a red dot infront the else?

sleek bough
cursive lance
#

this right?

#

or maybe im misunderstanding it πŸ˜… πŸ€·β€β™‚οΈ

sleek bough
#

ok, you need to understand the process. Go through the beginning. Where you are destroying the object and getting the error. Just before that line put Debug.Log(" message", contextObjectYouAreDestroying );

#

Then click on the message it outputs, it will point to the prefab you are trying to destroy.

cursive lance
#

like this?

sleek bough
#

Just before that line

#

When it hits the error it won't output anything

cursive lance
sleek bough
#

Did you click on it?

cursive lance
#

then it goes to here

sleek bough
#

Don't double click, just click. It will highlight the object you are trying to destroy.

cursive lance
sleek bough
#

When you see that it point to prefab, shorten object reference to just enemyData and print it out again, it will point to the object that referencing the prefab you are trying to destroy. Make sure it references instance next time and not prefab itself.

sleek bough
cursive lance
#

then i get a syntax error

sleek bough
#

Yea, it's not Unity object, can't use in context. Figure out what instance it belongs to and then continue from there. Make sure it references instance next time and not prefab itself.

cursive lance
sleek bough
#

selectEnemy is the script of the selectEnemy.gameObject it will point to the same prefab

#

Now you know that it point to which prefab and you know you can't destroy it

cursive lance
#

but i knew that from the warning already?

#

just don t know how to fix it

sleek bough
#

You know which prefab. You know where did you assign that prefab. Don't destroy prefabs to fix it. It's pointless.

cursive lance
#

yeah i should destroy an instance but wondering why i get the warning 1/2 in the game and not the whole time

#

and don t know how i can fix it

sleek bough
#

Do you know why you are destroying it at all?

cursive lance
sleek bough
#

Why are you destroying prefab though. It has nothing to do with instances on the scene.

cursive lance
#

i don t know didn t want to guess it is an accident

sleek bough
#

Why are you guessing what's going on in your own code?

cursive lance
#

because it is quite some code

#

so how can i make sure it doesn t try to delete prefab but just instances?

steady bobcat
#

if this is possible your logic is flawed, it shouldnt be possible to mix up a prefab and created instances...

sleek bough
#

When do you have instance to destroy, then destroy it

cursive lance
#

yeah but now i try to delete prefabs in my code and don t know how to fix it also don t understand why the warning only sometimes happens

agile sapphire
#

prefabs are just resuable assets in your code

#

your best bet is to just reference the object and Destroy(gameObject) when meeting a condition

steady bobcat
#

EnemyData is to store data about an enemy, but references a prefab? no wonder you have this problem

#

you should seperate the "enemy preset" and the "instantiated enemy"

#

e.g. EnemyData is used to create an Enemy and only the Enemy type is used at runtime to do ur logic

cursive lance
azure frost
#

So... important question.

Would every possible permutation of states and inputs have to be coded in a script? Or is there some way to do it more efficiently?

sleek bough
#

You can use State Machine

steady bobcat
cursive lance
steady bobcat
cursive lance
#

yeah i get that that went wrong but don t know how to clean it up/start from here to fix it that is the mainpoint understand the problem

steady bobcat
#

we have explained the issue and ways to correct it:
EnemyData -> Instantiate Enemy -> Set up speed, health, reward values on Enemy -> Process Enemy only at runtime.

#

i should clarify, I am using Enemy to refer to a NEW script you could make cus your current Enemy class is more of a EnemyManager

sleek bough
#

if you are keeping prefab references on scripts, at least name them so you you won't confuse them with instances, like myObjectPrefab

cursive lance
cursive lance
sleek bough
#

You can access data on Prefabs and Scriptable Objects assets you reference at runtime, yes.

#

Just don't try to delete them

cursive lance
sleek bough
#

start by clearly marking prefabs and check you don't reuse them as instances

#

if you need to hold an instance, create a field for it

#

Code refactoring is a large part of programming.

cursive lance
#

but now i simply need to refrom the script right since i knew by yesterday that i tried to delete prefabs in the scripts wich shouldn t happen but don t know how to rewrite it tought i wasd almnost done with the stupid project and then i got a bug wich i know what is is but not how to fix the code

steady bobcat
#

Okay so in Update() you loop over enemies but in a screenshot above you show prefabs assigned in this list. In this loop you call MoveToWaypoint() for these enemies which then causes the problem.

#

so solution is... remove this loop?

cursive lance
#

then it makes sense why the error only occurs twice

steady bobcat
# cursive lance im so stupid lol

this is why i suggested not sharing a type for data and created enemies cus its easy to mess up like this.
Anyway you should perhaps rename some stuff, change some types and make it not so easy to make this mistake.

cursive lance
steady bobcat
swift falcon
eager steppe
#

hey guys; just wondering how i could serialize a Unity Material, somehow? i know the engine hates it, but the thing i wanna do kinda relys on it.

I wanna allow players to load their own particle systems in my rhythm game's editor; and having materials be able to be loaded onto those Particle Systems would be kinda epic. It appears Newtonsoft.Json doesn't like doing that though - any way i can get around this?

knotty sun
#

I have an asset that does it, serializes Particle systems as well

eager steppe
knotty sun
#

Asset store - Save for Unity

steady bobcat
# eager steppe hey guys; just wondering how i could serialize a Unity Material, _somehow_? i kn...

well you can set material properties at runtime as long as you know the name and type. Its not gonna work to de serialize some json into a material as it wont be created properly.
If you know the shader and its main params im sure you can build a way to let a user edit the properties well and apply them.
You could also via shader graph make a shader thats easier to edit to simplify the process.

leaden ice
steady bobcat
#

Its not super simple as a lot of the options you can change on the urp/standard lit materials change many things or change features too

low rapids
#

https://www.youtube.com/watch?v=faY50bf4oWs

I have the exact same Problem as this user. Is this a generall problem that anyone here knows a fix for? Or is this problem related to the camera code?

Hi! I am having issues with my Camera jerking heavily when a camera-originated raycast hits an object and enables a Canvas UI item. I have limited it down to the disable/enable of the UI item and the movement script attached to my camera.

The bug is recreated when I move my camera onto the gameObject hit by the raycast with my mouse. If I don'...

β–Ά Play video
#

0:42

stark sun
#

https://pastebin.com/rvAmsfKv
I have this script for my stickman ragdoll enemies. But it doesnt work.I mean doesnt get the triggers from "weapon1 hold" gameobject.I want weapons to collide so I wanted to keep them as colliders but oncollisionenter2d doesnt work if gameobject doesnt have a rigidbody and when I put a rigidbody that is not kinematic, everything messes up.When I put a kinematic one, I prevnt collisions between weapons and thats not something I want. So I added a trigger collider to "weapon1 hold" and a normal collider on "weapon 1". Then, changed oncollisionenter2d to trigger enter.But it never triggers.

this photo is from when I equip a weapon.

stark sun
#

I'm going to take a shower sorry if someone answers and I reply late.

clever lagoon
#

need a sanity check please: I know I CAN put Unity editor code (like UnityEditor.AssetDatabase ), in my normal runtime code when it’s inside a #if UNITY_EDITOR.
But, if I want to do this for my OWN editor-only-code, I CANNOT actually store this editor-only-code in my project’s β€œEditor” folder (so it compiles to the editor assembly)?
Is this correct? If so, is it because, even with the #if UNITY_EDITOR conditional, the runtime assembly simply cannot access the same-project’s editor assembly?

knotty sun
#

Assembly-CSharp cannot access Assembly-CSharp-Editor but vice versa is allowed

clever lagoon
steady bobcat
#

Asmdefs will overcome the reference issue

knotty sun
#

not in this case, that would create a circular dependency

steady bobcat
#

Up to you to reference in one direction only

quick token
#

how can i make a 1 way 3d collider?

knotty sun
quick token
#

my bad. better phrasing, is there a way to make an object ignore collisions with another object? (probably when it hits a trigger)

#

maybe i just missed it while searching but i cant find anything

knotty sun
#

physics.ignorecollision

#

or physics2d if its 2d

quick token
#

no idea what that is, but it sounds perfect. i'll check the docs now, thanks UnityChanThumbsUp

alpine parcel
#

hello, i have been following a tutorial on procedural planets which i almost completed, and i have been trying to add a level of detail system (LOD) but im having issues with chunk generation, the verts and triangles are getting distorted when the chunks are generated and dont know why i get this problem, have been working on it for hours and im really starting to get frustrated, here is the code:

alpine parcel
# stark sun can someone take a look

after reading this and the code, first, i dont know what exactly u want, im confused or probably braindead after debugging for hours, in principle you want oncollisionenter2d to trigger enter, by that you mean this: private void OnTriggerEnter2D(Collider2D collider)?

alpine parcel
stark sun
#

but without rigidbodies oncollisionenter never gets called.

#

So I changed to triggerenter.

leaden ice
#

if you want collisions between weapons yes they need to have dynamic rigidbodies

#

when I put a rigidbody that is not kinematic, everything messes up
"everything messes up is really vague. The answer here is to dig down into exactly what is "messing up" and fix that.

stark sun
#

My problem is OnTriggerEnter2D() never gets called and enemy never gets damage

leaden ice
alpine parcel
rigid island
alpine parcel
#

sorry vro, didnt notice😭

leaden ice
#

From there video there are clearly collisions happening

#

that means OnCollisionEnter2D will work

#

the question is just - making sure all the components are on the correct objects etc

stark sun
#

when its dynamic,I need joints and some scripts to hold it.When its kinematic collision messes up and weapons dont collide thats why I didnt use it.No rigidbody works fine but I cant use oncollisionenter2D.

#

So thats why I changed collisionenter to triggerenter

rigid island
#

imo

alpine parcel
stark sun
leaden ice
rigid island
leaden ice
#

i don't really understand the question as it is

stark sun
#

and because I still want collision between weapons,I added a collider to the root of gameobject that is a trigger and one to the blade gameobject that is a collision.

stark sun
#

My problem is enemy not taking damage or getting the knockback on the script.

rigid island
stark sun
rigid island
#

yes

#

makes no sense having a rigidbody there with no collider

alpine parcel
#

yep

rigid island
#

its not even a parent so colliders dont get compounded

leaden ice
#

it's pointless

#

the colliders need to be on the same object as the RB or children of it

#

otherwise they are not part of that RB

#

they are part of the parent one

stark sun
#

thats because I can equip twohanded weapons to the hand I want. and the other arm gets added a joint, that joint gets connected to the offhandpoint.

#

So it looks like holding with both hands

#

and that works fine

leaden ice
#

ok but I'm explaining why this doesn't make sense if you're wanting to have OnTriggerENter2D or whatever

rigid island
#

sounds like you're in a XY problem. You're telling us your fixes / attempted solutions rather than root of the problem / what you want to do

leaden ice
#

and you didn't show where the script is either

#

bascially the script needs to be on the obejct with the collider

#

or on the object with the RB

stark sun
#

this is when I equip the weapon

alpine parcel
stark sun
rigid island
leaden ice
#

What does "on my character" mean

#

which GameObject is that

stark sun
#

enemyhealthmanager script is on the enemy

#

named Character (1)

rigid island
#

ONCollision/OnTrigger needs 1 dynamic rigidbody between those two objects trigger/colliding

#

look like you have it a child of the weapon not the weapon itself

alpine parcel
#

isnt the main problem that basically you want to deal damage and knockback but you dont get that (which are called ontriggerenter)

rigid island
#

you dont need it to have a rigidbody if enemy has dynamic rb

rigid island
#

okay and which object has the Function OnTrigger ?

#

that one needs a collider with IsTrigger on

stark sun
#

I have 2 scripts about health

#

one for my playercharacter and one for enemies

stark sun
#

I didnt know it worked like that

rigid island
#

well yeah. Without a trigger how do you expect OnTrigger to work

stark sun
#

yeah thats right

#

but also the enemy has to collide with other things too

#

so should I carry damaging function to a script on weapon?

rigid island
#

A root RB needs that script / function

stark sun
#

that script is on the root of enem gameobject

alpine parcel
#

but take it with a grain of salt

rigid island
stark sun
alpine parcel
#

what he just said now is correct i think

rigid island
#

Either collider needs isTrigger on

stark sun
#

nooo its not

rigid island
#

up to you which, enemy or weapon

#

thas why i suggested, for a weapon its easier to deal with Phyics queries like Overlap or spherecast so you never have to worry about rigidbodies.

alpine parcel
#

the problem is you need a lil of over write, but if that isnt is a problem, i recommend you to go for it so everything is easier down the road

alpine parcel
rigid island
#

realtime gen notlikethis

stark sun
rigid island
#

i know nothin sorry

alpine parcel
#

aw man, ty anyway

rigid island
alpine parcel
#

yh, i will ask there

rigid island
#

also try the forums/ unity discussion. Unity staff/ Devs lurk there

alpine parcel
#

ty

spark stirrup
clever lagoon
#

only other guess I have is .. some indexing issue at the edge.. but these are shots in the dark- pretty complex code to read without more comments

alpine parcel
alpine parcel
#

checked the values and they seem alright, i think the issue is somewhere in this code: `List<Vector3> vertices = new List<Vector3>(mesh.vertices);
List<int> triangles = new List<int>(mesh.triangles);

    // Get chunk mesh data
    int triangleOffset = 0;
    foreach (Chunk child in parentChunk.GetVisibleChildren())
    {
        (Vector3[], int[]) verticesAndTriangles = child.CalculateVerticesAndTrianglesOfChunk(triangleOffset);
        vertices.AddRange(verticesAndTriangles.Item1);
        triangles.AddRange(verticesAndTriangles.Item2);
        triangleOffset += verticesAndTriangles.Item1.Length;
    }`
#

in the 2 list, i first put the data from the vertices and triangles from ConstructMesh method, so that may be causing problems

quick token
#

!code

tawny elkBOT
gritty jacinth
#

Anyone used the animation rigging package? I need to adjust the position and rotatation of the hand bone and am trying to use it but only am able to get the rotation working

gritty jacinth
# leaden ice <#502171313201479681>

Yeah I did see that channel I was just hoping I could get some quick advice in general. I went ahead and posted my question there with more context hopefully someone knows what the cause of this is cause I am about to just revert back to the built in ik system 🀣

hexed pecan
#

It is possible to see which one of your rigidbody's colliders was hit, I think it was Collision2D.otherCollider

leaden ice
odd arrow
#

i have un-given up πŸ™ πŸ™ πŸ™ πŸ™

#

we're so back

random monolith
#

Hello guys, is there anyone who is familiar with Firebase auth Implementation? I am getting this runtime error, everytime I try to login in from android device. Let me know if you have encountered this before. (I looked up the online forums and tried their methods, still don't have a chance to fix it T_T)
DllNotFoundException: Unable to load DLL 'FirebaseCppApp-12_5_0'. Tried the load the following dynamic libraries: Unable to load dynamic library 'FirebaseCppApp-12_5_0' because of 'Failed to open the requested dynamic library (0x06000000) dlerror() = dlopen failed: library "FirebaseCppApp-12_5_0" not found

random monolith
#

Thanks

safe zinc
#

Hmm, anyone knows how to view Steam Stats? I can set them or get them with the SteamSDK. But does that mean they can only be viewed from within the game itself?

#

Not directly a Unity question, but I wonder.

#

I cannot find info on that heh

knotty sun
#

Not a Unity Question not a code question either. Ask Steam

jagged plume
#

I don't understand why only sometimes does it say that MC (orange box) collides with ground tile (yellow) and some other times it does say it collided with shroom tile (blue). I always collide from right

#

I think it has to do with floating point inaccuracy and the collision point being slightly outside the blue tile rather than inside it

marble dome
#

I have a player character using a CharacterController without a Rigidbody. A SwimmingReferencePoint (child of the player object) is attached to the character's neck. When the player enters a trigger collider marked as Water (with a Water layer), swimming mechanics activate, including vertical movement for ascending and descending.

However, when ascending to the surface, the player briefly goes above the water level before gravity is applied, causing them to fall back into the water. I’m trying to limit the player’s position so that they can only ascend until their neck is at the water's surface without going above it. I've tried clamping positions and implementing checks but couldn't resolve the issue effectively.

Here’s a snippet for context:

#

what would be best solution for this problem

heady iris
#

You could make it so that the "enter" and "exit" thresholds are different

#

Perhaps you have to get 0.5 meters underwater to start swimming, but then only stop swimming once you're 0.2 meters underwater, for example

wheat spruce
#

I've got some pretty basic code to apply force to my object with the wheels controlling the angle.

  private void Update()
  {
    Vector3 trainAimDirection = transform.right;
    float engineForce = _engine.CurrentForce; //gizmo only turns green when force is applied

    float wheelAngle = -_wheels.CurrentAngle;
    Quaternion rotation = Quaternion.AngleAxis(wheelAngle, Vector3.up);
    Vector3 rotatedVector = rotation * trainAimDirection;

    Vector3 force = rotatedVector * engineForce;
    _rb.AddForceAtPosition(force, _engine.transform.position); //engine is located at the gizmo
  }```The problem is that even when force isnt being applied and it stops moving forwards, the object continues to spin
hexed pecan
#

What is that bit on the rear/left?

#

Btw your forces are frame rate dependent in Update, do it in FixedUpdate

wheat spruce
hexed pecan
#

So are you adding sideways forces here or what

wheat spruce
hexed pecan
#

Should it turn right (down) at all?

#

Just trying to understand what's going on here

wheat spruce
#

Its a top down view of a train. The front set of wheels of the train are where the force is applied, and the back wheels are what rotates

hexed pecan
#

Are you holding D to turn right at ~6 seconds?

wheat spruce
#

Yeah

#

I have to do tiny amounts of rotation for the moment otherwise it gets out to control

hexed pecan
#

Maybe you just want to add some angular drag or manually set the angular velocity to stop it when you aren't turning

wheat spruce
#

Near the end of the video it starts to pick up too much momentum

#

Will be easy enough to limit that kind of speed

#

It just seemed a bit strange for it to keep rotating almost like it was on a ball bearing

#

no force applied would surely stop all torque

hexed pecan
#

Think about an object rotating in space

#

There's no air resistance

#

It will just keep rotating

wheat spruce
#

ah, true

#

I'm also not quite sure if the rotation calculation is correct

#

I think what I have is like this. I take the direction of the red vector and flip it around so the green moves in the opposite direction

#

in my mind it sounds correct

hexed pecan
#

If the center of mass is between those points then it should work fine

#

(Which it obviously is, unless you modified it)

wheat spruce
#

yeah its got the default values for that

#

It didnt feel like I had the full equation worked out, I thought that the length of the train would matter considering the rotation is found at the opposite end to where the force is applied

gritty jacinth
#

camera script works fine with a controller as well so im not sure why its behaving like that for one mouse

heady iris
#

oh, I've seen this exact problem before, ha

#

You have a very high sensitivity

#

The smallest possible movement that your Logitech mouse can report is causing a dramatic change in camera angle

hexed pecan
#

High DPI, right?

heady iris
#

Your Razer mouse is more sensitive than your Logitech mouse, so it's moving the camera even faster

#

which makes the problem a lot less obvious

gritty jacinth
#

So really the logitech just made some problem in my code more apparent?

heady iris
#

In theory, mouse DPI shouldn't affect how juddery it looks

#

well, hm..

gritty jacinth
heady iris
#

You should try turning your in-game senstivity down

#

then see how it feels with both mice

hexed pecan
#

I just remember reading about issues related to very high DPI mouses, or was it refresh rate πŸ€”

#

I think the latter actually

heady iris
#

3 billion Hz

gritty jacinth
heady iris
#

show me the script that handles mouse input

gritty jacinth
#

its too long to send here is there a site we use in this server for longer scripts?

heady iris
#

!code

tawny elkBOT
gritty jacinth
#

its still pretty messy tbh

#

i haven't cleaned it up yet

heady iris
#

what is PlayerInputManager?

gritty jacinth
# heady iris what is `PlayerInputManager`?

using UnityEngine.InputSystem;
using UnityEngine;

public class PlayerInputManager : InputManager
{

private InputAction moveAction;
private InputAction lookAction;
private InputAction sprintAction;
private InputAction walkAction;

public Vector2 MoveInput { get; private set; }

public Vector2 LookInput { get; private set; }

public bool SprintInput { get; private set; }

public bool WalkInput { get; private set; }

void Awake()
{
    moveAction = input.FindActionMap("Player").FindAction("Move");
    if (moveAction == null)
        Debug.LogError("Unable to find the move action on player action map!");

    lookAction = input.FindActionMap("Player").FindAction("Look");
    if (lookAction == null)
        Debug.LogError("Unable to find the look action on the player action map!");

    sprintAction = input.FindActionMap("Player").FindAction("Sprint");
    if (sprintAction == null)
        Debug.LogError("Unable to find the sprint action map!");

    walkAction = input.FindActionMap("Player").FindAction("Walk");
    if (walkAction == null)
        Debug.LogError("Unable to find the walk action on the player action map!");

}
internal override void CollectInput()
{
    MoveInput = moveAction.ReadValue<Vector2>();
    LookInput = lookAction.ReadValue<Vector2>();
    SprintInput = sprintAction.IsPressed();
    WalkInput = walkAction.WasPressedThisFrame();
}

}

#

using UnityEngine.InputSystem;
using UnityEngine;

public class PlayerInputManager : InputManager
{
   


    private InputAction moveAction;
    private InputAction lookAction;
    private InputAction sprintAction;
    private InputAction walkAction;

    public Vector2 MoveInput { get; private set; }

    public Vector2 LookInput { get; private set; }

    public bool SprintInput { get; private set; }

    public bool WalkInput { get; private set; }

    void Awake()
    {
        moveAction = input.FindActionMap("Player").FindAction("Move");
        if (moveAction == null)
            Debug.LogError("Unable to find the move action on player action map!");

        lookAction = input.FindActionMap("Player").FindAction("Look");
        if (lookAction == null)
            Debug.LogError("Unable to find the look action on the player action map!");

        sprintAction = input.FindActionMap("Player").FindAction("Sprint");
        if (sprintAction == null)
            Debug.LogError("Unable to find the sprint action map!");

        walkAction = input.FindActionMap("Player").FindAction("Walk");
        if (walkAction == null)
            Debug.LogError("Unable to find the walk action on the player action map!");

    }
    internal override void CollectInput()
    {
        MoveInput = moveAction.ReadValue<Vector2>();
        LookInput = lookAction.ReadValue<Vector2>();
        SprintInput = sprintAction.IsPressed();
        WalkInput = walkAction.WasPressedThisFrame();
    }



}
heady iris
#

okay, so that's just pulling from input actions

#

and you aren't multiplying by deltaTime erroneously

#

I would look at the actual values you're getting from the two mice.

#

Make sure to print them out with more than two digits of precision (that's all you get by default)

#

I believe you can do something like...

#
Debug.Log(MoveInput.ToString("N8"))
#

i think that's how you contorl the formatting?

robust dome
#

kind of obvius actually when he said one mouse act like that and the other like that

gritty jacinth
#

this is from th e "working" mouse

#

its always whole numbers

heady iris
#

did you set the input action to be Digital?

marble dome
heady iris
#

it should be a "Vector 2" control type

gritty jacinth
heady iris
#

do you have a processor on the Delta [Mouse] binding?

gritty jacinth
heady iris
#

hm, looks fine

gritty jacinth
#

nope

#

so logitech mouse is returning

#

much greater whole numbers

#

-24 and shit

heady iris
gritty jacinth
#

the logitech mouse isn't a gaming mouse its just some crappy office mouse

#

but it woorks fine in valorant

heady iris
#

But multiple mouse inputs during a single frame should be getting summed up

gritty jacinth
#

so idk its gotta be my code here

#

or a unity bug

heady iris
#

you can also look in the Input Debugger window

#

window > analysis > input debugger

#

it should show the same values

#

I see values that are always multiplies of 0.25 for the delta down/left/right/up

gritty jacinth
#

what

heady iris
#

What fps are you getting with and without it open?

gritty jacinth
#

400+

heady iris
#

Does opening it reduce your framerate noticeably?

gritty jacinth
#

180

#

so yeah

#

im trying something now

#

ima lock my fps to 60

heady iris
#

yeah, see if that changes the behavior

gritty jacinth
#

at 60 fps its fine

#

180 fps slightly noticable

heady iris
#

So with the logitech mouse, do you get many frames of 0 input and then a few frames of very large inputs?

gritty jacinth
#

Yes

#

but this mouse works fine in other games

#

i can play val at 240 fps and the mosue is smooth as butter

heady iris
#

I wonder if it's pulling input from the mouse differently than Unity is

gritty jacinth
#

must be

#

last night when this happened

heady iris
#

Can you check how many frames of zero input you get at a time?

#

like, is the logitech mouse giving input at 60Hz? 120Hz?

#

that kidn of thing

#

You could do this by logging

#
Debug.Log(Time.frameCount + ": " + LookInput.ToString("N8"));
gritty jacinth
#

sec i gotta relaunch the editor

#

unity keeps the fps locked even after removing application.targetframerate

gritty jacinth
heady iris
heady iris
# gritty jacinth

That certainly explains the jumpiness. It's odd that you wouldn't see that in other games, though

gritty jacinth
#

ima see what happens if I use the old way to gather input

#

same behavior sadly

#

i may have found a fix tho

#

nvm

lone bone
#

I'm trying to create a function that will let me check the area in front of the player for objects, but I want to be reusable for different interfaces. I currently have this:

public bool TryGetObjectInFront<T>(out T interfaceObject) where T : IPlaceable, IHoldable
{
  // Do stuff
}

I am calling it like this:

if(player.TryGetObjectInFront<IPlaceable>(out IPlaceable interfaceObject))
{
  // Do other stuff
}

However, this is giving me the following compiler error:
"The type 'IPlaceable' cannot be used as type parameter 'T' in the generic type or method 'Player.TryGetObjectInFront<T>(out T)'. There is no implicit reference conversion from 'IPlaceable' to 'IHoldable'."

That error doesn't happen if I remove IHoldable from this line:

where T : IHoldable

Is there some syntax issue here? How can I make the generic function accept both of those interfaces?

heady iris
#

where T : IFoo, IBar demands that the type implements both interfaces

lone bone
#

Ah, that's the issue then. Is there a syntax that would accept either? I'm not finding that online.

leaden ice
#

e.g. if you had

public class Interactable : IPlaceable, IHoldable``` then you could do ```cs
player.TryGetObjectInFront<Interactable>```
heady iris
leaden ice
#

Or if you had:

public interface IPlacableAndHoldable : IPlaceable, IHoldable``` you could do `player.TryGetObjectInFront<IPlaceableAndHoldable>`
heady iris
#

C# does not permit for this kind of "either" type

#

(I know Typescript can get really wild with that stuff)

gritty jacinth
#

or you could make a third interface

heady iris
#

It sounds to me like you shouldn't require either interface, though

#

You're just getting a ... thing that's in front of you

#

it doesn't have to always be placeable or have to always be holdable

lone bone
#

I want to create a function that will look for objects in front of the player, but filter for specific interface. I will need to recreate this exact function for each interface. So it sounds like there's not a way to have a function take the interface type (for example IHoldable)?

clear basin
#

!code (ignore this)

tawny elkBOT
lone bone
heady iris
#
public bool TryGetObjectInFront<T>(out T interfaceObject)
{
  // Do stuff
}
#

much like how GetComponent works

leaden ice
heady iris
#

(You may want to add a constraint that it's at least a Component)

#

wait, no you can't do that

#

these are interfaces

#

If you want to constrain the kinds of things you can look for, then I suppose you could make some kind of empty IQueryable interface..?

leaden ice
#
public bool TryGetObjectInFront<T>(out T interfaceObject)
{
  if (Physics.Raycast(..., out RaycastHit hit) && hit.collider.TryGetComponent(out T comp)) {
    interfaceObject = comp;
    return true;
  }
}```
#

something like this

#

you probably don't need that intermediate variable either

gritty jacinth
#

The way I handled this in the past, I created Rect for each object I wanted to be interactable with, then I added a rect around the player and used a spatial hash to get all nearby items, loop through if the rects intersect

lone bone
latent latch
#

Can also like include the interface onto other interfaces and ignore generics completely

#

then check by that interface type

lone bone
#

The interfaces should be separate. There could be any combination of holdable AND placeable, just holdable, just placeable.

#

And I think there may be other interfaces in the future that could be added to this list, so it would quickly get out of hand if I tried to create like IHoldableAndPlaceAndThrowable or something like that.

latent latch
#

Or just IDetectable even

lone bone
clear basin
#

hi there
I'm trying to make a script for moving platforms. now i need platforms to go to second point and teleport back to first point
The problem is that platforms move to second point and stop there instead of going to first point (teleporting to it)
https://paste.mod.gg/rwtihgwynwmn/0

#

(previous link was wrong, it was code by ai (which didn't help))

vestal arch
#

and also loop?

gritty jacinth
#

Is there a way to click and drag a non monobehavior script into the inspector?

rigid island
gritty jacinth
#

is there no possible way to do this?

rigid island
knotty sun
#

where are you expecting to drag from?

gritty jacinth
knotty sun
#

that ain't gonna work

rigid island
#

You can the file itself but it not work how you want it

#

its essentially just a TextAsset

gritty jacinth
#

what about types

#

can I make it so I can set up a list of types in the inspector then create instances of those types via reflection?

rigid island
knotty sun
gritty jacinth
# rigid island this sounds like an [XYProblem](https://xyproblem.info/)

no sir i am trying to create a way to attach leightweight behaviors onto things like weapons, items, AI etc. I do not want to use scriptable objects for the behavior cause thats not what they are for. I do not want to use monobehaviors for them cause they're bloated. so I was going to make a leightweight behavior class that other classes can inherit from, and I want the "behaviors" to be assignable to the items scriptable object that holds data like its display name and model etc.

vestal arch
#

how exactly are they bloated?

rigid island
#

this sounds like you're just doing skating around the same problem but in a more overconvoluted solution

rigid island
heady iris
#

Ooh, I see what you want

#

You're going to want to check out [SerializeReference]

#

It allows you to serialize a List<ParentType> and actually store specific child types

#

There is no built-in UI for this, but there are several packages

gritty jacinth
#

do they have to be monobehaviors tho?

heady iris
#

No. They're explicitly not unity objects

gritty jacinth
#

awesome

heady iris
#

If you're storing references to unity objects, the problem is already solved (an Object field can hold any Unity object, no matter what the exact type is)

#

I use this all over the place.

heady iris
#

So it doesn't really work

#

for example, I have a List<PerspectiveHandler> here. PerspectiveHandler is an abstract class

#

I can pick a specific derived type and then configure it in the inspector

#

If I didn't use [SerializeReference], it would only remember the serialized properties of PerspectiveHandler (of which there are none!). It wouldn't be able to remember that I had put specific concrete types into that list

gritty jacinth
#

So just so I am clear in your scenario the attribute goes on the class itself right?

heady iris
#

No, [SerializeReference] goes on the field.

#

Have a look at the repository I linked

#

You will need to use a third party package to get an actual inspector interface.

#

Unity does not provide one.

gritty jacinth
#

ill take a look now

#

thanks for all this information

heady iris
#

(I'm actually using another package here -- this is provided by Animancer -- but it's the same idea)

#

I use this anywhere I need to pick between multiple derived types

#

So, for example, my Entity class has an Anatomy field that tells you where you should look when focusing on the entity, amongst other things

gritty jacinth
#

yeah this is awesome I am glad you showed me this it opens the doors to a lot of code cleanup

heady iris
#

I have various Anatomy implementations that handle that differently

gritty jacinth
#

I am going to use this weapon behaviors

heady iris
#

This is fine, nominally, and it has some advantages -- you can easily re-use the assets in many places

#

But if this is describing something that's totally unique to the user, then it's a hassle to create a massive pile of assets

clear basin
heady iris
#

There are a few "gotchas" to watch out for

gritty jacinth
heady iris
#

Most notably: If you change the namespace, assembly, or type name, Unity gets upset. It's not storing the GUID of a MonoScript -- it's literally just storing the type's full name

#

There is an attribute you can use to tell Unity about an old namespace/assembly/name for a type

#

[UnityEngine.Scripting.APIUpdating.MovedFrom]

#

I went for a more direct solution: I wrote a Python script that rewrite your assets

#

It feels a bit gross

#

(it's literally just regex)

#

I was doing a very large namespace migration -- from one enormous root namespace to a bunch of namespaces

#

so that was helpful

vestal arch
#

see how it flows

heady iris
#

note that this is just one major use of SerializeReference (the second one that gets listed)

#

I've never used it for the first case, where you're serializing things like graph structures

gritty jacinth
still jungle
#

btw SerializeReference works also for generics since unity 6

vestal arch
clear basin
#

i might understood what you mean

quick token
#

some times i wonder if i use too many attributes... nah my code is perfectly readable /j

#

(just noticed that first variable isn't meant to have the conditional field attribute, whoops)

unkempt meadow
#

everything is wrong with it

#

it works well outside of tight tunnels cause it's a lot simpler, but it seems impossible here

quick token
#

can you show us the !code ?

tawny elkBOT
leaden ice
unkempt meadow
quick token
quick token
unkempt meadow
#

raycasts are hard to control in such a tight space

#

I did a lot of logic for them and they kind of work

#

but my hands take up too much of the screen and clip through the camera

#

also sometimes I get weird angles for surface normals, can't really control that

#

idk anyone have a better idea to control hand grabbing here?

quick token
#

if you want another solution, you could just fake it. you can manually animate the hands and have the animation play while moving

#

im not entirely sure what else you could do. maybe someone else does though

unkempt meadow
#

I have it so it raycasts left when I move left for example

#

or what if I'm crawling through a wall

#

they would clip with normal animations

quick token
#

it would look something like this

unkempt meadow
#

I already do that

#

but you can still notice something's not right when it's clipping hard

quick token
#

clipping with the camera or the terrain?

#

nvm, watched the video you sent again and i see what you mean

#

i haven't actually done much with this myself so im not 100% sure of how to fix that

#

but, i think its just because the animation is a little weird

unkempt meadow
#

There is no animation

#

It's just ik

quick token
#

the ik animation

unkempt meadow
#

And tweening ik targets

#

Yeah ok it's a bit unnatural

steady bobcat
#

can also use newlines to save your eyes

spare dragon
#

Is there a way I could create a system script that doesn't need to derive from MonoBehavior but has Update/FixedUpdate loops & behaves like a singleton? I want to make my system scripts similar to how systems work with Unity's ECS but with regular GameObjects

leaden ice
steady bobcat
steady bobcat
#

can also do:

[field: SerializeField]
public int MyProperty {get; private set;}
quick token
#

o, i did see someone mention that one a few days ago

#

i've learned a surprising amount just by reading chat, in the short while that i've been here lol

spare dragon
leaden ice
spare dragon
#

like, have they implemented a way to create/modify entities in the edtior window without prefabs?

#

I see

leaden ice
#

YOu can always create Entities and do whatever you'd like in code

leaden ice
gritty jacinth
leaden ice
#

you can freely do GameObject stuff with that.

spare dragon
#

I understood that, I was just going off track a bit haha

#

do you know if there's any plans for solely Entity-based authoring in the editor?

leaden ice
#

idk. Maybe in Unity 7 or something

spare dragon
#

gotcha, thanks for the pointers

gritty jacinth
spare dragon
#

really excited for Unity 7, especially with .NET 8

gritty jacinth
#

tbh tho

#

I would think hard about ecs

#

its very half finished in a lot of regards imo

spare dragon
#

yeah, it does seem like that, at least regarding convenience

#

but the performance gains are very appealing

peak jacinth
#

you can get most of the performance benefits with Jobs

steady bobcat
#

we will get some great gains from moving from old ass mono to modern .net from microsoft

gritty jacinth
#

when is this happening i didn't even know it was announced

steady bobcat
#

hopefully before i die

spare dragon
#

I heard they're working hard on it atm

#

but like

#

ik that's exquisitly vauge lol

somber nacelle
#

unity 7 should be the first version with the core clr, theoretically there should be an alpha with it sometime this year

spare dragon
#

what kinda performance improvements should we expect from it?

gritty jacinth
#

.net 10 will be out and unity will finally be geting .net 8

#

ahahah

somber nacelle
gritty jacinth
somber nacelle
#

yes i just linked that

gritty jacinth
#

and it mentions 8

somber nacelle
#

and .net 8 was also the latest version when that was posted

spare dragon
#

they mentioned going from .net 8 to newer versions should be easier

gritty jacinth
#

nice

spare dragon
#

what changed between net 4 and net 8 to have such a big shift in structure?

steady bobcat
#

the problem is how unity began with mono when .net core (and modern .net CLR) did not exist

quick token
#

!code

tawny elkBOT
keen surge
#

sorry abt that, give me just a sec

gritty jacinth
keen surge
#

https://paste.mod.gg/fdqjfhosrrgm/0
im working on my character controller and trying to get the player character to jump up and away from the wall when jumping while wall sliding, but i cant seem to get it to work. any ideas? also sorry for the awful code.

gritty jacinth
spare dragon
spare dragon
#

and that's what necessitates the structural rework?

steady bobcat
#

yea cus the engine ofc was created to integrate with monos clr and stuff

gritty jacinth
#

its also not built ontop of the .net framework runtime

steady bobcat
#

and i presume il2cpp has some specific things to how mono works too

gritty jacinth
#

so its faster

steady bobcat
#

πŸ™ will be amazing.
In S&box the code recomp and hot reload speed is super fast

gritty jacinth
#

also doesn't .net core allow you to compile to native code by default?

spare dragon
#

I'm probably gonna stick with Unity for the time being though

steady bobcat
#

I mostly used it before the massive rework it got (i worked on TFS2)
it is quite nice though and they are making things more "unity like"

#

Garry doesn't really like unity but they are stuck with it for rust blah blah you can search up

keen surge
spare dragon
#

I get their frustration, but like, Facepunch will be just fine lmao

gritty jacinth
spare dragon
gritty jacinth
#

like he was trashing the creators of the network solution he used originally on his blog so bad they revoked his license 🀣

steady bobcat
#

WHAT

gritty jacinth
#

when rust first came out it used some netlib by some company called muchdifferent i think it was called ulink or something like that

#

it was like the only out of the box multiplayer asset for unity

#

that worked well for dedicated servers

steady bobcat
#

was that before the old unity networking? (like unity 5 era)

gritty jacinth
#

it was unity 4 era i think

#

back when unity used raknet multiplayer

spare dragon
steady bobcat
#

I have fond memories of Unity 4. 1 directional light with hard shadows for us free peeps 😦

keen surge
#

im getting velocity outputs, but not actually doing anything

spare dragon
#

I see

#

looks like on line 70 you set the velocity to whatever the player is inputting at that moment

#

so right as your character jumps off the wall, the next frame isWallSliding is false

keen surge
#

is there a good way to overwrite that while wall jumping or something like that? i dont want the player to be slidey when walking

spare dragon
#

what you could do is, while isGrounded is false

#

make it so that, instead of setting velocity, you add or subtract it

#

one second

#

replace line 70 with this:

if (!isWallSliding)
{
    if(isGrounded)
        rb.linearVelocity = new Vector2(moveInput.x * moveSpeed, rb.linearVelocity.y);
    else {
        float delta = moveInput.x * (moveSpeed * Time.fixedDeltaTime);
        float newX = Mathf.Clamp(rb.linearVelocity.x + delta, -moveSpeed, moveSpeed);
        rb.linearVelocity = new Vector2(newX, rb.linearVelocity.y);
    }
}
keen surge
spare dragon
#

sweet!

#

you can also make a float variable for airAcceleration

quick token
#

and cs after the top `

keen surge
quick token
#

!code explains it better

tawny elkBOT
spare dragon
#

there we go

#

never knew how to do that

somber nacelle
#

you can also add the language cs or csharp immediately after the backticks (on the same line) and it will add syntax highlighting

quick token
spare dragon
#

got sidetracked by syntax lol

keen surge
spare dragon
#

yup yup!

keen surge
eager pewter
#

I'm 99% sure there's gonna be no issue, but I figured I'd check w/ y'all. I have a script which creates upward of ~3.5k GameObjects. It only creates them once when the game is started (or I suppose if the player resets), and then the game modifies them from time-to-time when needed. Additionally, it's just a mix of TMP objects and Image objects, so all 2D/UI stuff.

While I've had 0 issue running this game on either my laptop or desktop (both are pretty decent machines), I want this game to be smooth even on a complete potato. Should this be something I even worry about?

Looking up 'Unity too many GameObjects' comes up with people complaining about having tens-of-thousands or even hundreds-of-thousands of objects. And 3D ones no less. Not my measly 3.5k.

Thoughts?

latent latch
eager pewter
#

just initial load time

quick token
latent latch
eager pewter
#

nah, loading times are what I don't care about

latent latch
#

It's not so much about loading times and more about making the program unresponsive

eager pewter
#

I think I phrased it poorly

#

fair enough

steady bobcat
#

you can just limit how many of these game objects are created per frame if needed

kind musk
#

Hello, someone have an idea of why it tell me that a GameObject is not assigned, but he still can activate it / desactivate it ?
The variable is assigne in the inspector, but when i try to check if it is assign or not in the script it tell me that no.


void Update()
    {
        if (!estMenu)
        {
            if (Input.GetKeyUp(KeyCode.Escape))
            {
                if (settingsEstActive)
                {
                    Cursor.lockState = CursorLockMode.Locked;
                    hudSettings.SetActive(false); **//Here**

                    if (eleveCameraScript != null)
                        eleveCameraScript.settingsOff = true;
                    ...
                }
            }
        }
    }```
#

And the Settings Object is a child of a canvas

#
You probably need to assign the hudSettings variable of the GestionSettings script in the inspector.
GestionSettings.Update () (at Assets/Scripts/GestionSettings.cs:77)```
mossy snow
#

sounds like you have more than one GestionSettings

kind musk
#

yeah, didn't though about about that πŸ˜… , but normally the Gameobject that have the other GestionSettings script is disable, so it shouldn't execute the script right ?

mossy snow
#

yes, but something has woken it up and it sounds like it shouldn't be there in the first place if it's in a broken state anyway

kind musk
#

bruh, i had 2 same script, one on the parent, and one on the child, the parent one was empty

#

Thanks !

rigid island
kind musk
#

Sometime we need a exterior eyes on our thoughts x)

#

Yeah, my bad, the Gameobject which contained the script was disable

#

Nice it work :)

dim umbra
#

I have a health bar made up of a border object and a fill object, and I want to make it fade in and out at certain times. If I just changed the alpha values of both spriterenderers at the same rate, you would be able to see a small part of the red fill behind the border sprite during the fade. Is there any other way to do this without having this problem?

somber nacelle
#

you could probably use a mask as well

dim umbra
#

true

#

I think I might just go with some other transition tho

somber nacelle
#

i mean, alright, but the mask option should do exactly what you want

keen surge
#

https://paste.mod.gg/kzeamcrgbvey/0

I want to add a ladder layer mask that disables my gravity and allows the player to move in all 4 directions freely while overlapping the ladder background objects. I, in my severe lack of creativity and functional grey matter cells, cannot think of a good way to do this. does anyone have any ideas?

latent latch
#

Can you clarify because this sounds like two different problems with one being a rendering issue and the other being controls

keen surge
#

its entirely controls. when the player is in the same area as a ladder, i want them to be able to move freely

modern atlas
rigid island
#

you need a state machine asap

keen surge
keen surge
#

ive made a new one that half works

#

ive disabled gravity when isOnLadder is true, and now im trying to figure out out to move the character around without them sliding

modern atlas
#

And position that collider where you want 0 gravity

keen surge
#

my rigidbody's gravity is already off. im using my own code to handle gravity

#

i just dont know how to handle movement on the ladder

#

im still struggling to understand the new input system abit

#

a bit*

modern atlas
#

Perhaps constrain your X movement if you want to move only upwards?

keen surge
#

i dont want to move only upwards. i feel like that would make it difficult to climb off ladders

modern atlas
#

Well right before your ladder ends, position the trigger zone just below that point which returns your rigidbody state to normal for a natural transition. You can lerp the transition from RB 0 to your desired scale for a smoother transition

civic hatch
#

I've got a player and a enemy in 3D space, both have rigidbodies and push/rotate each other based on physics. I don't want them to push each other around, but I also don't want them to completely ignore each other by using the layer matrix.

I also don't want to have to increase both of their drag/angular drag to make them resistant to moving, then having to refactor how they both move and apply very large physical forces to overcome the increased drags.

Is there a simpler way for both to block each other, but without applying physical forces to each other?

somber tapir
marble glade
#

https://hastebin.skyra.pw/ivecarisim.csharp this script is starting a challenge inside a maze, https://hastebin.skyra.pw/oqemojeziq.java this is in the collider in the entrance of the maze, https://hastebin.skyra.pw/nezeciyara.csharp and this is in the collider in the exit. There`s some collectable objects inside the maze and a counter in the screen. The problem is everytime I enter and leave the maze (turning the challenge on and off) and go in and collect objects, the counter go nuts and count many times one single object collected, and sometimes the challenge just stops in the middle of the maze. How can I fix this?

civic hatch
civic hatch
#

I'd assume ```C#
private void CollectDiamond()
{
collectedDiamonds++;
UpdateDiamondCountText();

    if (collectedDiamonds >= totalDiamonds)
    {
        ExitChallenge(); 
    }
}
This is being called many times somehow and making your counter go nuts everytime you collect a diamond, since you are  calling ```CollectableDiamond.OnDiamondCollected += CollectDiamond;``` on every challenge start.
#

@marble glade C# var subscribers = CollectableDiamond.OnDiamondCollected.GetInvocationList(); Debug.Log($"OnDiamondCollected has {subscribers.Length} subscribers:");

#

See what that gives you. After trying to reproduce your bug with multiple attempts of the maze etc.

dense pasture
#

What’s some favorite super basic project management tools y’all use for your projects? I use JIRA for work but it’s a bit more convoluted than what I need for a 1-3 person team. A backlog, task workflow (waterfall is fine), and defect board is all I need

#

Would be nice if it can link into GitHub

civic hatch
agile nimbus
#

Ah we used to use Asana at work but we've switched to Linear.

I like how fast/lightweight Linear* feels with the desktop app, and it has a nice/simple Roadmap view to look at your "Projects" (made up of many tasks. Like an "Epic" on JIRA). It also links to Git/GitHub. Trello is a good one for starters though, we used Trello in college

dense pasture
agile nimbus
#

Ah my bad, Linear*!

chilly surge
#

GitHub has the Projects tab, it's pretty barebones but it might just suffice for a small team.

dense pasture
#

Yeah prototyping some epics with a subset of story lists would do well, and being able to link pull requests in them the way JIRA does

#

FWIW it’s just me now but if I get 1-2 other people on board I’ll need to be able to scale to that later on

#

For now it’s more like a wishlist/backlog I’m putting together and cranking out

storm ivy
#

Guys I want to make a grenade explosion that only damages enemies in range and with a clear line of sight (no walls or obstacles in between). How can I set this up?

rigid island
#

might be better with a capsule/sphere/boxcast if you want not just a thin line towards enemy
not fully working code but the basic idea

 void Explode(){
        var hits = Physics.OverlapSphereNonAlloc(etc..
        for (int i = 0; i < hits; i++){
            var col = colliders[i];
            var dir = (col.transform.position + offset - explosionOrign).normalized;
            var hitSolid = Physics.Raycast(explosionOrign, dir, etc..
                if(hitSolid && hitInfo.TryGetComponent(out Enemy enemy)) {
                    // explode this enemy```
tulip spruce
#

hello, so I have an issue, where I used instance thing so I set a script as an instance and then call it from another scene. However the gamobject I am trying to call is a settings canvas which is activated/deactivated based on button presses. If I start the game in unity and then click play (entering the main scene) and in the main scene I press esc to open pause menu and then I press Options which is referenced to the settings.istance.gameobject.setactive(treu). This gives reference error. But the thing is, if I start game and first open the settings menu and then close. Go into main scene and press esc and then option, the options pop up no issues. How do I fix this?

rigid island
tawny elkBOT
tulip spruce
#

Lmk if that worked

#

I did save and copy link

rigid island
# tulip spruce Lmk if that worked
 void Awake()
    {
        settingsScript = settingsScript.Instance;
    }```
you should never access `instance` in another script in awake, always access from Start. This gives their awake time to assign the instance
rigid island
#

also this is called the singleton pattern, its not just "instance" lol

tulip spruce
rigid island
#

instance refers to the fact that its THE Instance of this object (if assigned correct)

#

but yeah static make it the only one, but its good its doing Instance check in awake too

thin aurora
# rigid island ```cs void Awake() { settingsScript = settingsScript.Instance; ...

This is a problem with how most people initialize singletons, though. There's nothing wrong with accessing another singleton during initialization. The issue is race conditions since everything is initializing in awake methods, but ideally you'd want to have a general provider which you grab singleton instances from, which by itself handles the initialization

#

So rather than relying on each singleton to initialize themselves, have a general provider that wakes before everything else and have it provide all the instances

#

A pipeline that Initializes your game before it actually starts is a good idea to have in general

rigid island
#

bootstrapper that loads all these up or something

thin aurora
#

Yep

thin aurora
#

Pretty much

rigid island
#

the less you rely on script order and messing with it the better

thin aurora
#

You know in .NET APIs you also have a main entry point in which you configure your services. You register them, and only after that will it start listening for incoming connections

#

Right now you effectively try to work around a race condition, but the real solution is getting rid of it

rigid island
#

yeah unity is weird you can't really do a traditional DI initialization like you can with other .net frameworks

#

ideally you do a proper DI anyway and not have soo many singletons lol

thin aurora
#

Yes, I think Unity could have done better when it comes with initialization in general

#

Everything just starts at once. They should have had a main entry point like all .NET apps

rigid island
#

they kinda do

tulip spruce
rigid island
tulip spruce
rigid island
thin aurora
tulip spruce
rigid island
thin aurora
#

If I were you then I would make a single manager which has a GetService<T> method, and this stores the singleton on a general DDOL gameobject

#

If the script is already on the gameobject, just return that instance

#

But note there are existing DI frameworks for Unity. Maybe you could use those instead (or combine them even)

tulip spruce
#

DI?

rigid island
#

yeah those can get messy too, like zenject

rigid island
thin aurora
#

Yeah, ideally you can just work without them. Idk if they provide anything

#

Just a thought. Never reinvent the wheel until you have a working application πŸ˜›

rigid island
#

facts at some point OP should learn that, might be confused already with assignment is already what they struggle with lol

tulip spruce
tulip spruce
#

I tried implementing it

radiant frigate
#

monkey

rigid island
tulip spruce
radiant frigate
tulip spruce
rigid island
tulip spruce
#

I have main menu, where I have settingsmenu gamobject and a settingsScript attached

#

then main scene there is pausmenu gameobject and a pausmenu script attached to it

tulip spruce
#

idk what I wrote there

#

let me correct

rigid island
rigid island
#

if PauseMenu script is on the pauseMenu gameobject then you don't need a reference just use the property

tulip spruce
#

disable and activate

rigid island
#

eg cs public void Pause(){ gameObject.SetActive(true); Time.timeScale = 0; isPaused = true; }

tulip spruce
#

Maybe I am complicating everything

rigid island
#

with DDOL and singleton

tulip spruce
rigid island
#

hows it related to the pause menu and settings

tulip spruce
#

Pausmenu:

#

or should I just dublicate the settingsCanvas onto the other scene too?

#

and reference Playerprefs settings to same file?

#

that would work I think

rigid island
tulip spruce
rigid island
#

you want both scenes to have access to it no ? isn't that why you made it singleton ?

tulip spruce