#archived-code-general

1 messages · Page 189 of 1

leaden ice
#

but it seems like it's probably a struct

pliant gorge
#

yes, that worked nicely, thanks!

hard viper
#

is there a simple way to set up moving between selected buttons via dpad/arrowkeys without using a script?

#

i’ve been coding everything by hand, but now that I get into more hard-coded menus, I’m wondering if there is a better way

heady iris
#

well, by default, you get automatic navigation

#

which tries to figure out where to go based on screen position

#

did you run into problems with that? I know I did.

hard viper
#

i have not tried

#

my arrow keys normally move a cursor on the screen

#

maybe i need to decouple it to gain that feature?

leaden solstice
#

New Input system also has ui input module

sudden meadow
#

is it fine to use the new keyword to create a new instance of a class that inherits from ScriptableObject, using a normal class constructor, or do SO's have some issues with new like MonoBehaviors do?

jaunty needle
#

Is this valid?
public event System.Func<IEnumerator> ShotBall;

#

This is the script that listens for the event but when I invoke it it seems to not be activated:

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

public class DistanceDisplayer : MonoBehaviour
{
    [SerializeField] private float collisionDelay = 0.1f;

    ProjectileLauncher projectileLauncher;

    private void Awake()
    {
        projectileLauncher = FindObjectOfType<ProjectileLauncher>();
    }

    private void OnEnable()
    {
        projectileLauncher.ShotBall += DelayCollision;
    }

    private void OnDisable()
    {
        projectileLauncher.ShotBall -= DelayCollision;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        Transform passedBall = collision.gameObject.transform;
        print(passedBall.position.x);

    }

    IEnumerator DelayCollision()
    {
        print("Off");
        GetComponent<BoxCollider2D>().enabled = false;
        yield return new WaitForSeconds(collisionDelay);
        print("On");
        GetComponent<BoxCollider2D>().enabled = true;

    }

}

sudden meadow
#

as in it's not fine or it doesn't have the same issues as monobehavior? 😄

rigid island
jaunty needle
rigid island
#

also they do run Awake()

#

so thats kinda like your constructor for it ig (ofc is not a real constructor)

sudden meadow
#

hmm ok. this is fine, just wasn't sure. thanks.

fervent furnace
#

i havent use event (i use system.action) and i think this is weird if your event have return value

int i=ManyFuncReturnInt.Invoke();

how can you determine i value?
update: both invoke and () returns void

hard viper
#

the whole point of an SO is to not be destroyed

#

if you are creating an SO at runtime, your usecase is probably wrong

#

if you need persistent data saved between playsessions, you should save to a proper file like a JSON. Or use playerprefs.

if you need to just store data that can be created and deleted during runtime, a POCO might be better.

sudden meadow
#

yea I was simply creating a "bleed" status effect that was inheriting from "StatusEffect", and simply doing new Bleed() and send in the variables on creation was an easy way to generate new bleeds with variable values. However I also wanted other status effects that would work better as SO's so I was trying to see if it worked so just do new on an SO.

It does complain but it also works, so I guess it would be fine if I manage it myself, but I can also just instantiate the bleeds as SO's and then change the values on the clone so it's all fine I think.

hard viper
#

do not use an SO for this

#

use a POCO

sudden meadow
#

Hmm never heard of this before

hard viper
#

or a monobehaviour that manages a POCO

#

POCO = plain old C class.

sudden meadow
#

hmm

hard viper
#

ie don’t inherit from Monobehaviour, nor scriptable object

thin aurora
#

An SO is great because it reduces memory usage since all your reusable data is in a single reference rather than multiple primitive/complex fields

quick elbow
#

Anyone have any suggestions on how to store timestamped data for quick access? Essentially my gamestate is driven by IRL timestamped events. This is sort of a DSA question. I don't think a hashmap/dictionary would work well because the timestamp would have to match exactly when trying to key in on the time.

hard viper
#

if you use an SO, then you have to manually destroy it later to clear it

#

because you are creating it, and you are now responsible for destroying it

quick elbow
#

Users need to be able to navigate back and forth between the timestamped data, and ideally they should be able to change the time scale as well to essentially move through the data at say 0.5x or 2x

thin aurora
sudden meadow
#

hmm maybe. it's just that i have some use cases where i'd like to have a custom status effect that I can then do a comparison to, where just popping in a scriptable object to compare to would be nice.

i'll consider POCOs so thanks for the suggestion

hard viper
#

and if you fuck up the creation/destruction process, your project will have a bunch of SO files lying around

fervent furnace
#

skip list/sorted set

hard viper
#

you should basically never make a new SO during runtime, and only in editor

quick elbow
sudden meadow
#

i make clones of them sometimes but that's it. i guess i need to handle destroying those too.

thin aurora
#

But why make clones? They store data

quick elbow
# knotty sun Linked List and Binary Search

That's definitely possible. Lookup would be O(logn) though as opposed to O(1), but there may not be a way around that since I don't think I can use a hashmap as mentioned

thin aurora
#

If the data changes, make a new SO in the editor

knotty sun
quick elbow
hard viper
#

so, I have an EntityDataOriginal class. This tells exactly all the vulnerabilities and deets of an enemy. It is basically an immutable SO. During runtime, I make a POCO duplicate of it, which is mutable. This way I can make multiple entities which can have their vulnerabilities change during runtime, separate from each other, without altering the original.

#

and the GC automatically clears the mutable copies whenever enemies are destroyed

#

this is an example for robin

fervent furnace
sudden meadow
#

@hard viper thanks

orchid bane
#

How do I know if a point is to the right or to the left of my character if the character might be on a tilted plane, tho not too much so?

hard viper
#

are you in 2D or 3D

#

and what do you mean by “right”

#

transform.right points to the right, after adjusting for rotation, but not for scale

#

so… what is “right”?

orchid bane
#

Let me draw

orchid bane
#

The plane is tilted as you can see

eager yacht
#

Well you could use the dot product here, against the player's right direction and the direction to the enemy. If dot is greater than 0, it's on the right, if less than 0, it's on the left.

hard viper
#

does “right” depend on camera?

#

like, can your camera turn around

orchid bane
hard viper
#

so you mean the character’s right

orchid bane
#

Yep

hard viper
#

can the character’s scale be negative?

orchid bane
hard viper
#

negative scale mirrors you

orchid bane
#

Also it's important to consider that the player is always standing perpendicular to the plane it's standing on

hard viper
#

in this case. transform.right is a vector that goes to the object’s right

#

given any applied rotation

orchid bane
#

I need to know not the character's rotation but whether a coordinate point is to the right or to the left of the character

hard viper
#

if your character is straight on the plane, then transform.right is along the plane. If the character is always straight up (world up), then transform.right just points to the right given rotation

hard viper
orchid bane
#

Okay

hard viper
#

so now you have a vector pointing from character to his right, yeah?

orchid bane
#

Yeah

hard viper
#

so (pointOfInterest - transform.position) is a vector that goes from your character to the point of interest

#

which could be an enemy’s position or whatver

#

then we have transform.right dot product with (pointOfInterest - transform.position).

#

if this dot product is positive, then the vectors share enough component to be in the same direction

#

if it is negative, they are opposite

#

if zero, then it’s straight perpendicular

#

do you understand so far?

orchid bane
#

Everything besides the dot product

hard viper
#

do you not know what a dot product does, or how to do it, or what?

orchid bane
#

School was so long ago I've forgotten it

hard viper
#

you should learn again. vector math is important for this sort of thing

#

vector v dot u = v.x * u.x + v.y * u.y + v.z * u.z ….

orchid bane
#

I also saw cross product being used for these things. Which is better?

hard viper
#

cross product and dot product are two totally different things

#

dot product takes in 2 vectors (can have any number of dimensions), and outputs a number

#

cross product takes in 2 vectors (usually must be 3D), and outputs another vector (also in 3D) which is perpendicular to both

#

totally completely different

#

dot product is bigger if two vectors are in the same direction

#

when working in spatial coordinates, dot product of zero means perpendicular. more positive means they are more oriented together. more negative means more oriented opposite

#

vector2.up dot vector2.up = 1.

#

vector2.left dot vector2.up = 0

#

vector2.down dot vector2.up = -1

#

make sense?

orchid bane
#

Does, does, tho I think I need to give it more thought to understand how it works with vectors which don't have a 0 parameter

hard viper
#

you need a lecture then

#

there should be plenty on youtube

orchid bane
#

Okay, thanks. Evidently I need to know at least this much

hard viper
#

yeah. it’s basically mandatory to work with vectors

#

i will say dot product shows up a lot more than cross product.

#

cross product gets you a vector that is perpendicular to 2 other vectors. dot product generally tells you how aligned 2 vectors are.

#

but i work in 2D, so I never need cross product

orchid bane
#

I wonder if you didn't consider some cases which won't work in 3D with dot product

hard viper
#

dot product is dot product

#

you can have 69-dimensional vectors, and its interpretation does not change

orchid bane
#

If we want to know how aligned are your vectors in 1 dimension still

hard viper
#

same thing

orchid bane
#

Not complaining, just stating

hard viper
#

linear algebra is rarely taught with a specific number of dimensions in mind

#

only bad teachers will force learning in specifically 2-3 dimensions

orchid bane
#

Okay, thanks, gonna code it fast and go learn right after that

hard viper
#

gl

mystic ferry
#

sounds like one of the gameobjects is destroyed when you switch scenes. It needs to be marked with DontDestroyOnLoad(this)

#

#💻┃code-beginner if your manager needs references to an object that's destroyed when you switch scenes, you need to find a way to make sure either that that object isn't destroyed or that you generate a new one

orchid bane
#

I have separate animations for when my character is going slightly to the left or slightly to the right, it's controlled by a boolean animator parameter called TurnRight. The character is moved by root motion. So when it moves to the left or to the right, it almost always gets a bit off and needs to slightly turn to the other side. It results in a twitching animation. What do I do with considering that I would like my character to go as straight as possible?

hard viper
#

it depends on how you are moving

#

you need to expess your turn in a variable that does not change instantly like that

orchid bane
#

Will make a blend tree I guess

#

Atm I'm trying to make a sub-state machine in my animation controller, but I can't find a way to exit from any state in the sub-state machine. I can make transitions neither to Up (Base Layer) nor to Exit. What do I do?

urban lintel
#
    public IEnumerator SpeedUp(float speedMultiplier, float duration)
    {
        float timeRemaining = duration;
        while (timeRemaining > 0f)
        {
            movementSpeed = Mathf.Lerp(baseMovementSpeed * speedMultiplier, baseMovementSpeed, 1 - (timeRemaining / duration));
            timeRemaining -= Time.deltaTime;
            yield return null;
        }
        movementSpeed = baseMovementSpeed;
    }

I have this decaying speedup function in my player script that basically enables on certain conditions (e.g. colliding with a speed boost causes the speed boost to call this function), however this has unintended behaviour once i pick up multiple speedups. How do i go about ending the previous coroutine? Can i store a reference of it on the player script?

#

changed my public method to be this instead:

public void SpeedUp(float speedMultiplier, float duration, string name)
    {
        if (coroutine != null)
        {
            StopCoroutine(coroutine);
        }
        coroutine = StartCoroutine(SpeedUpCoroutine(speedMultiplier, duration, name));
    }

I guess in the future i could hold a list of coroutines instead and iterate or key/value them if i have buffs that are multiplicative

wanton wasp
urban lintel
#

yep, ended up doing that! The coroutine there is the reference, i just made it stop and reapply a new one since in my case i wanted it to refresh

dusk apex
urban lintel
#

True, that could also work if i stored the timeremaining outside the scope of the function

wanton wasp
dusk apex
#

He's already got a while loop and it's preferred over restarting coroutines, iirc

wanton wasp
urban lintel
#

if there's a better way to handle that than a while loop i wouldn't mind changing that too. I just needed a decaying effect and am not too familiar with the tools unity/c# offers out of the box

wanton wasp
dusk apex
#

Generally you'd let the routine run as long as possible - often times with infinite loops (not preferable in your case though). The condition to continue is something you can easily manage as a member of the class.

wanton wasp
spring creek
toxic helm
#

Hey

#

So

#

sorry to interub yall

#

but

#

I tried to code something and it kinda buggs out

spring creek
toxic helm
#

I have a preety problem with that

#

I made a script that breaks a capsule in 2 when you press B, but that makes the capsule dissapear

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

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

wanton wasp
toxic helm
#

like this?

spring creek
#

But yeah, it's a choice

spring creek
#

Weird. They aren't being parented or anything

jaunty needle
#

Why do these have different positions when they're in the same place?

#

Talking about the x component here

toxic helm
#

I don't know :((

#

I suck at coding

wanton wasp
dusk apex
toxic helm
#

No.

spring creek
toxic helm
#

They are dissapearing

primal wind
#

Do they perhaps have the same script on them?

dusk apex
#

It would be similar to using delegates with events versus calling functions directly.

spring creek
toxic helm
#

Sure

spring creek
toxic helm
spring creek
#

There is nothing in the code that should make them dissappear, and obviously no other scripts on them...
Can you make a short video showing it happen?

toxic helm
#

yes

wanton wasp
#

Can it be, that they spawn, but because of the prefab offset, they do it in the wrong place?

wanton wasp
#

They definitely spawn, try resetting offset of the prefab transform.
Also try freezing rigidbody position.

toxic helm
#

How would I do that?

knotty sun
# toxic helm

man, look ar your heirarchy, they have not disappeared

spring creek
#

Order of ops SHOULD make the offset transform.position + (2,0,0) or (-2,0,0).

#

They are getting chucked, or are below the plane?

wanton wasp
spring creek
#

The capsules tip, so the offsets are weird too, more up and down than left and right

#

Pause after you press b, select one of the minicapsules in the hierarchy and press f

toxic helm
#

Now what?

ashen yoke
#

where is it

spring creek
#

Well where did it take you

toxic helm
#

in the air

spring creek
#

Then they got chucked in the air

#

Didn't dissappear

toxic helm
#

hmmm

spring creek
#

Lower force a lot maybe?

knotty sun
#

debug.log your spawn position and force

spring creek
#

Also freeze the og capsules rotation

toxic helm
#

Why do they not have texture

#

like they arent capsusles

#

they are invisible

spring creek
knotty sun
#

they do not have a renderer

spring creek
#

You may wanna recreate the prefab
Did you make an empty gameobject and add the collider and rigidbody?
Create a capsule instead

ashen yoke
#

just add capsule as a child

#

remove collider from child

toxic helm
#

so

#

I added a renderer

#

now what

#

I dont know

#

??

ashen yoke
#

well do you see it now?

toxic helm
#

no

#

i dont

spring creek
toxic helm
#

Mesh renderer

ashen yoke
#

@toxic helm create a separate capsule

#

compare your capsule to the unity one

#

figure out the difference

#

apply the changes

toxic helm
urban orbit
#

Guys, can someone get the exact world position of a screen touch with a perspective camera?

ashen yoke
#

on the way you can also read what different components do by clicking the help button to the right of the component title

spring creek
toxic helm
ashen yoke
spring creek
ashen yoke
#

describe your task and ill help with best method to find valid Z

urban orbit
ashen yoke
#

the height will remain constant?

#

doesnt matter really, this is a clear case of Plane struct

#

when you click, you create a Plane that points up, then you create a camera ray and do plane.Raycast

urban orbit
ashen yoke
#

this will give you the point on said plane

#

to modify height you just change the supplied position when you create the Plane

urban orbit
#

is it possible to just ignore it and get the touch in the x and z coordinates?

ashen yoke
#

alternative to this is a cumbersome method of calculating distance from the camera

#

you need to provide a Z when you compute screen to world

#

since camera can be anywhere like -21.4f z

#

and your ground plane can be 1

#

the resulting Z of the point before convertion will be 20.4

#

you can do all that or just use the plane

maiden junco
#

tried. everything.

#

what the heck is happening

simple egret
#

It's probably not because of your code. Reboot, make sure your GPU drivers are up to date, install another version. That bright red Windows Update icon might have to do with it lol

maiden junco
#

just updated rtx drivers, imma try to update windows as well

#

ps. I changed ssd by cloning all of my data

ashen yoke
#

is that a laptop

maiden junco
#

nop

ashen yoke
#

any interfering programs

#

geforce experience, msi etc

maiden junco
#

idk

ashen yoke
#

did layout reset?

maiden junco
#

at first only hiearchy was rendered well, but when resetting layout everything turned to black

#

related also to the editor

wanton wasp
# maiden junco idk

If nothing helps you can try DDU (Display Driver Uninstaller)
Download it from guru3d
Load in safe mode
Open it, select your gpu and click delete and reboot
Exit from safe mode
Install drivers again

ashen yoke
#

and install older drivers

#

half year old or more

maiden junco
#

and then if nothing helps ill try what you told me

ashen yoke
#

and dont install geforce experience

maiden junco
#

right

heady iris
#

GeForce: Experience Pain

ashen yoke
#

installed it once with the driver back when it released, uninstalled and never reinstalled it since

wanton wasp
primal wind
#

Am i just so lucky to never have a bad experience with "dreaded" sofware?

maiden junco
#

uninstalled geforce experience

#

still black editor

#

imma try what R1nge suggested

ashen yoke
#

before that did you delete Library/Temp folders?

#

is that a new project?

maiden junco
#

ohhh

heady iris
#

always worth doing that

heady iris
#

you can get some wild gremlins in there

maiden junco
ashen yoke
#

create new project

#

see if same happens

maiden junco
#

ok imma try

#

ps. the project was with HDRP

#

should i create it completely blank? (i assume so)

ashen yoke
#

shouldnt really affect basic unity gui

#

blank yes

maiden junco
#

okk

heady iris
#

I could see a rendering error in the scene view causing the rest of the editor to explode

ashen yoke
#

true

#

may crash the driver even

#

test blank, if ok, test empty hdrp if ok, its Library/Temp or something specific to the project

maiden junco
#

right

#

Its kinda better but I still see weird behaviors that i've never seen, like wrong icons on wrong buttons that if i hover they look what they should look like

#

and still weird things

ashen yoke
#

tried reinstalling the editor itself?

maiden junco
#

I tried to reinstall it three times

#

even different versions

#

nothing helped

#

everything happened after I changed SSD nvme

#

which I cloned

#

from my old 256gb ssd nvme with a tool

#

never had these problems before

wanton wasp
maiden junco
maiden junco
#

same

#

thing

#

I could try to install january drivers

#

idk tbh

urban orbit
#

Can someone please explain to me why having a perspective camera affects things like converting screenToWorld position or ViewportToWorldPos when you put the z-axis to 0 even though you don't want to use it?

#

I just want to achieve the same result as by using an orthographic camera

urban orbit
opal bison
#

The first one is a range variable, whats the second? I wanna look up a tutorial but no idea what to even search

loud wharf
#

Sounds neat.

valid blaze
#

how to connect to planetscale, and get data? I am currently stuck on:

Assets\Database.cs(5,7): error CS0246: The type or namespace name 'MySql' could not be found (are you missing a using directive or an assembly reference?)

but I can't
dotnet add package MySql.Data --version 8.1.0 to unity
from terminal in project folder, ./Assets, or parent

valid minnow
#

if i had a function in a script that i wanna ignore if i check a box in unity editor, how would i write that? basically when i turn on the checkbox it turns on the function to appear in the editor like the variables in the function

spring creek
#

^ this is an early return. Put it at the top of the function

#

That's the best I can say

#

The method will still be CALLED. It just won't do anything

valid minnow
# spring creek if (boolVariable) return;

well i know that but what i want, is if its check to true, the variables of the function being checked show in the edtior, and if its checked to false, the variables dont appear

spring creek
#

Are you using "function" to mean script? Maybe that's why I'm confused

valid minnow
spring creek
valid minnow
spring creek
#

Maybe something like naughty attributes or odin could get you that functionality

valid minnow
scarlet kindle
#

is there any easy way to change all the fonts of every TMPro textfield in the editor? only other option I'm seeing is to make a script TextManager that deals with it on runtime... but that seems crappy

valid minnow
spring creek
#

What you want is to toggle serialization

#

And I don't know how

#

Sounds interesting though

valid minnow
scarlet kindle
#

o that sounds nice.

#

good idear

valid minnow
spring creek
# valid minnow yeah idk i just thought there was a simple function or something to do it but ma...
#

Seems like what you wanted

#

Like I thought though, it's a custom editor script

#

I didn't find any attribute for that unfortunately

scarlet kindle
#

like wait 0.2 seconds in update with a Coroutine, then check all the GameObjects?

#

damn i dont like this solution 😦

valid minnow
valid minnow
valid minnow
scarlet kindle
#

maybe there's a way I can just override the default loader for TMPro

#

to force a font whenever anything loads it

#

so that way it's before runtime

#

ya know?

#

well, sorta at runtime

#

sorta before

valid minnow
#

yeah look at the TMPro documentation maybe

spring creek
scarlet kindle
#

as in all the fonts will visibly change on the screen

spring creek
scarlet kindle
#

yea i just want a way to load one font into all my TMPros

#

before the game starts

#

i used a font i dont like, and i want to change it. but i dont want to have to change every tmpro in my editor

#

and also, if i want to change again later, its even more work

#

im investigating an override solution for some of the TMPro classes

spring creek
scarlet kindle
#

LOL! i was thinking of doing a nameswap thing too, but so janky

#

so keep same name, but replace the reference in that file. it would work

#

there's gotta be a better way

#

maybe I just change the default font, and then remove the font from all the tmpros in my editor?

#

so then it just falls back to the default

#

ill try that out and see

#

nah doesnt work, it just changes them at the time you set it to None in the editor

#

do the default

#

short of just attaching a script to each tmpro and then hooking that up to a textmanager

#

yeah I mean that works, its annoying to attach a script to every TMPro GO, but it's only the ones that are prefabs

#

so not too bad

tardy basin
#

Is it the correct behaviour for the Editor to crash on stackoverflow? Isnt there a way I could somehow keep it alive (if, for example, I catch the exception in debugger).

cosmic rain
#

I'm not sure if a debugger attached to unity editor can break in error automatically. Might want to check the relevant settings in the debugger.

And yes, depending on where it is thrown, stack overflow might crash the editor.

night harness
#
    [SerializeField, HideInInspector] private GameSettings gameSettings = new GameSettings();
    [ShowInInspector, ShowIf("@gameSettings.hasLoaded == true")]
    public GameSettings GameSettings
    {
        get 
        {
            if (gameSettings != null)
                return (gameSettings);
            else
                return (null);
        }
    }

GameSettings is a POCO class with [Seralizable], Would my GameSettings property be getting a reference to gameSettings here or making a new instance/copy of it

fading trail
#

any advice for getting like the framework of 3D dungeon generator

#

like placing rooms, etc.

#

would i need to have a room prefab, or could i just generate using the floor tiles, wall tiles, etc. of a room

cosmic rain
#

Also that null check is redundant. As well as the parenthesis around gameSettings and null.

cosmic rain
urban orbit
ashen yoke
#

page doesnt load

#

what is there Plane struct?

urban orbit
#

What I don't understand is the warning

night harness
ashen yoke
ashen yoke
#

unity doesnt allow nulls on objects

night harness
#

yee

ashen yoke
#

and if it were null at any point

#

@gameSettings.hasLoaded == true would throw

#

whats up with the ( ) btw?

night harness
#

i just like ()'s around my returns...

urban orbit
# ashen yoke some gibberish

My camera is set to perspective and I'm trying to clamp my player's movement with this code and it worked. Just that I solved it with trial and error until I ended up with the number 10 for the z-axis (for some reason).

#

Do you know a better way to do it? Or should I just leave it like this?

ashen yoke
#

i explained this already in detail to you

#

the 10 comes from distance of the camera to ground

#

reread our previous conversation its all there

#

what are you clamping?

#

player position?

urban orbit
ashen yoke
#

make a trigger collider, use its .bounds to get min max

#

modify it in the scene to setup the playable zone

#

bounds are axis aligned so dont rotate it

urban orbit
#

okay

worn oasis
#

Hey guys, I'm receiving this error when trying to open a script to see its content in the inspector. Any ideas as to why this might be happening?


cosmic rain
#

Something wrong with your class definition I'd assume.

#

Or one of it's fields.

worn oasis
#

public class DischargedSpellcast : NetworkBehaviour

cosmic rain
#

Share the whole script.
!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.

cosmic rain
#

Sharing the details of the error/info messages would be helpful as well

worn oasis
#
Unity.Netcode.Editor.NetworkBehaviourEditor.RenderNetworkContainerValueTypeIEquatable[T] (System.Int32 index) (at Library/PackageCache/com.unity.netcode.gameobjects@1.6.0/Editor/NetworkBehaviourEditor.cs:146)
System.Reflection.RuntimeMethodInfo.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at <1c8569827291471e9db0dcd976e97952>:0)
Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation.
System.Reflection.RuntimeMethodInfo.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at <1c8569827291471e9db0dcd976e97952>:0)
System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) (at <1c8569827291471e9db0dcd976e97952>:0)
Unity.Netcode.Editor.NetworkBehaviourEditor.RenderNetworkVariable (System.Int32 index) (at Library/PackageCache/com.unity.netcode.gameobjects@1.6.0/Editor/NetworkBehaviourEditor.cs:102)
Unity.Netcode.Editor.NetworkBehaviourEditor.OnInspectorGUI () (at Library/PackageCache/com.unity.netcode.gameobjects@1.6.0/Editor/NetworkBehaviourEditor.cs:268)
UnityEditor.UIElements.InspectorElement+<>c__DisplayClass59_0.<CreateIMGUIInspectorFromEditor>b__0 () (at <a47f8e4b37a644dfaac5a6945ff77d47>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)```
cosmic rain
#

Something with a network variable I guess.

worn oasis
#

it was a declared network variable that was never used

#

I'm surprised it would throw such an error

#

what gave it away?

cosmic rain
#

There's RenderNetworkVariable method in the stack trace.

worn oasis
#

Awesome, thanks again

valid blaze
#

ERROR:

Unable to resolve reference 'Google.Protobuf'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.
Unable to resolve reference 'K4os.Compression.LZ4.Streams'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.
Unable to resolve reference 'BouncyCastle.Crypto'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector```

CONTEXT:
can't find any of these in C:\Program Files (x86)\Microsoft SDKs\NuGetPackages even though it seems they are installed in nuget in VS. also in VS there are issues, but in unity I get the above err and 
I have tried to solve the missing MySQL.Data.dll in 2 ways. Through nuget, which wasn't recognized in namespace in Database.cs file, and by installing MySQLConnector and OBDC and copying a MySQL.Data.dll to Assets/Plugins which was recognized by both unity and VS..

ADDITIONAL ERRORS:
```Assembly 'Library/ScriptAssemblies/Assembly-CSharp-Editor.dll' will not be loaded due to errors:
Reference has errors 'Assembly-CSharp'.
and 
Assembly 'Library/ScriptAssemblies/Assembly-CSharp.dll' will not be loaded due to errors:
Reference has errors 'MySql.Data'.```
#

or should I just try to connect to DB through python script? what an annoyingly difficult task this is.

cosmic rain
#

Your message is really hard to read. It starts with an error and it's not even clear where the error ends and where the explanation of the issue is... Some proper explanation of what is going on is required: what happens, when happens, what causes ?

spring creek
#

You can format errors with this
```
```

So it looks like this

Mah big error stuff
Is bad
Don't like
quartz folio
#

they are installed in nuget in VS
Unity doesn't use Nuget

valid blaze
#

it seems as though it does? I was able to target the unity project in VS by selecting a file in scope, then Project->Manage Nuget packages

quartz folio
#

It doesn't

#

Unity generates its own csproj files

valid blaze
#

so, I manually satisfy the missing Google.Protobuf','K4os.Compression.LZ4.Streams','BouncyCastle.Crypto' and also put them in Assets/Plugins?

#

ooh, ill try

#

😖

#

I.. I think I got it. I had to install Nuget for Unity. Then I updated 'Google.Protobuf','K4os.Compression.LZ4.Streams','BouncyCastle.Crypto.dll'
And I changed the .Net target to .NET framework from Standard 2.1
and was getting another error for System.Text.Encoding.CodePages and updated that through NuGet.
Kinda silly to have old broken dependencies on a fresh install of newest LTS, and had to third party plugin manager

Is there anything else I should know as a Unity noob? (aside from Scriptable Objects, I got that one)

quartz folio
#

Kinda silly to have old broken dependencies on a fresh install of LTS
It's not a fresh install, you added a random DLL to the project without the dependencies

valid blaze
#

DB connectivity is not stock? Or is it just Azure

cosmic rain
edgy ether
#

so im not sure if this is the best place to ask this, but how do i change the "simple name" of an assembly file?
apparently i imported an assembly with the same name and im trying to keep both, so im opting to try to rename one and keep the other. but simply renaming the file doesn't change the fact that it's "simple name" is still the same.

quartz folio
edgy ether
quartz folio
#

Is there not a way to just use the latest? What packages import the same assembly but different versions? Usually it'll just use the latest

prime widget
#

I need a list<T> that only keeps the 10 latest items added to it. Does a collection like this exist for c# already?

#

something that works like this?

        var list = new SomeTypeOfList<int>(3);

        list.Add(33);
        list.Add(71);
        list.Add(22);

        //after the following is called remove the oldest added value(in this case 33) from list and add 12 to the list
        list.Add(12);
fervent furnace
#

queue

prime sinew
# prime widget I need a list<T> that only keeps the 10 latest items added to it. Does a collect...
prime widget
prime widget
#
public class FixedQueue<T> : Queue<T>
{
    private int threshold;

    public void FixedEnqueue(T value)
    {
        if (Count >= threshold)
            Dequeue();

        Enqueue(value);
    }
}
``` this is what i came up with and it appears to be working
thin aurora
somber nacelle
#

you'd probably want to make that Enqueue(value) to be base.Enqueue(value) or else it end up with infinite recursion

loud wharf
#

Totally.

thin aurora
#

Ah right, my mistake.

swift aspen
#

How do I assert for a Debug.LogError in a [Test]?

ocean osprey
#

So im making a game but every possible collision detectiong tutorial i find dosent work i have rigid bodies, colliders and everything but nothing works, anyone know a way i cat get collision to work?

mellow sigil
#

You'll have to show what you have for anyone to tell what you're doing wrong

#

post the code and screenshots of the inspectors of both objects

ocean osprey
#

ok

#
    void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.name == "Player")
        {
            Debug.Log("It Worked");
        }
    }```
ocean osprey
#

thankyou

prime sinew
#

what was it?

ocean osprey
#

i had it on enter instead of stay

junior falcon
#

Does anyone know if there is a setting to hide/show these:
I have various projects that don't show them, and some that do. Others working in the project have them, but I don't

#

Maybe that's more of an editor question but I don't know where to ask or what terms to search for.
I like to double click these to open the script, or single click to locate in project. Impossible to do the latter now without typing a search

halcyon radish
junior falcon
#

There's no custom inspectors involved, for me it's every script in the entire project, for them, they're all there

halcyon radish
#

And the panel isn't set to Debug mode i'm guessing.

junior falcon
#

I can see it the equivalent in debug mode, but not normal

#

If it's not Unity it may be a plugin, like Odin, but I've spent too long looking, and I don't know what it would be called

halcyon radish
#

Is that how it looks on your side right?

#

Can you show a small snippet of how it looks?
Have you tried creating an empty project to make sure that everything is working fine in your version of unity?

junior falcon
#

Yeah this is all my side, the screenshots are from a personal project, I'll show one where it's not, 1 sec..

halcyon radish
#

Hmm, that's a strange one. I'm not sure now, just thinking about it.

#

So every script you make for that projects, even an empty one, will look like that?

junior falcon
#

Yeah 💯

halcyon radish
#

Does it happen in a new empty project?

#

Which would suggest there is something in the project that is causing this override.

junior falcon
junior falcon
junior falcon
halcyon radish
#

You mentioned Odin, are they using this package in the project? There could be some conflict somewhere. I'm assuming you are not the original creator right?

potent helm
#

Could someone pls help me? Im trying to make player movement for an endless runner but i don't really know why my code doesn't work.

junior falcon
#

Yes Odin is in all of them, I'm not the original creator.
I thought the same there could be a clash. The ones blurred are part of our SDK, Odin is in one of those, it's the only editor plugin we use 🤔 I don't see anything else that would be causing it

halcyon radish
#

I haven't used Odin personally. But does it affect new script that you create? if its not an Odin script? (Sorry i'm not sure on the setup of it).

junior falcon
#

Cracked it! It's odin. There's a setting in preferences. (Literally the very first one) However something is borked with my installation because that page of the preferences is blank

#

@halcyon radish ^ Thanks for your help!

#

huuh - @ tag fixed

jagged rampart
#

i have a question and im not sure what i need to show to get help, i have a animation for run jump fall and idle, run and idle work just fine, i have a SetBool for IsJumping and i have code for it to be true on jump. issue is when i jump no animation but the weird thing is if i jump again before i hit the ground the animation will then play, so the jumping animation only works if i press jump two times

loud wharf
#

Very, very late reply but if you want to have the same functionality, you can use this. UnityChanThink
Used like this [Restrict(Restriction = typeof(IMyInterface))] public Monobehaviour _iMyInterface;.
Can't do IMyInterface as a field type, it won't show in the inspector, so ya have to cast it.
public IMyInterface I_MyInterface => (IMyInterface)_iMyInterface;

junior falcon
vague tundra
#

Oh that's really cool, thanks @loud wharf !

loud wharf
junior falcon
#

Clicks expand and facepalms, sorry looked past it. Nifty!

loud wharf
#

I actually just copied this code off a yt tutorial, then added Exclusion and Attributes. UnityChanThink
Idk, might be handy. Maybe not. UnityChanLOL

junior falcon
#

I've needed similar in the past and it was a custom attribute solution then, would be a nifty one to be a unity native

heady iris
loud wharf
heady iris
#

just trust me, editor 😦

loud wharf
heady iris
#

i swear i'll put the right thing in it

#

but yeah, that's not a half bad idea

#

the property smooths over the wrong type

loud wharf
#

Unity could just do interface fields as implicitly scriptable-objects/monobehaviour only but explicitly accepts any scripts that implements said interface.

#

Or maybe an attribute. UnityChanThink

#

🤷‍♀️

heady iris
#

yeah

celest iron
#

How do I change a tile based on it's neighbors?
Not talking about changing the sprite (this I know how to do), but changing this tile to another tile if all of the neighbors aren't this tile.
For example, if water tile is surrounded by 8 ground tiles, change this water tile to a ground tile
The solutions I find online only changes the sprite, which isn't what I want.

#

I didn't know where to ask this tho, I assume here because talking about scriptable tiles

runic granite
steady moat
runic granite
#

i tried using cloth system but can i attached it to other game obj?, i only know that it could be interacted by assignt collider on what obj that can be interacted with

#

oh,and this will be used in VR

steady moat
#

Make an animation

runic granite
#

i see, thanks for the suggestion

regal flame
#

genuine question, why would cloth in vr be a bad idea?

#

im guess GPU is already pushing limits being vr and all, never worked with cloth stuff before. is it that bad?

runic granite
#

and VR basically just glorified android phone

#

for quest 2 at least

regal flame
#

ah makes sense.

delicate zinc
#

bit of a question regarding marking a game object as static

If i where to instantiate the gameObject that's marked as Static at runtime, would that still conserve the usefulness of static game objects?

#

asking because i've been working on a dungeoncrawler and the time to make the dungeon generation has come, i've been thinking about multiple ways to approach this and i think the best one would be having rooms as Prefabs and instantiating said rooms at start to build an explorable dungeon

#

however, i dont know exactly if this still allows said prefabs to leverage the ability of being static, considering i'm spawning the rooms on dungeon creation

#

at least i know that i'd have to use bounding boxes to detemrine the sizes of rooms, thankfully i've already solved that issue by using the bounds.encapsulate method, pretty handy

green breach
#

From the unity docs: https://docs.unity3d.com/Manual/StaticObjects.html

if a GameObject
does not move at runtime, it is known as a static GameObject. if a GameObject moves at runtime, it is known as a dynamic GameObject.

Many systems in Unity can precompute information about static GameObjects in the Editor. Because the GameObjects do not move, the results of these calculations are still valid at runtime. This means that Unity can save on runtime calculations, and potentially improve performance.

swift falcon
#

i have a json file
which has some data in it,and i want to upload it into my c# script and put it inside a dictionary
what is the most straightforward method to do this

simple egret
swift falcon
#

{"Data":[{"Name":"name1","Job":"Job1"},{"Name":"name2","Job":"Job2"}]}

simple egret
#

That would map to a class containing a List<T> more than a Dictionary, but that's still doable

swift falcon
#

and how would i really approach it

simple egret
#

You need a class to contain individual { string Name, string Job } objects, and another class that stores a list of it (the outer object { List<TheClass> Data }

swift falcon
#

do i have to add [System.Serializable] over the classes ?

simple egret
#

No

swift falcon
#

public class EmployeeInfo
{
public string Name;
public string Job;
}
public class EmployeeList
{
public EmployeeInfo[] Data;
}

swift falcon
simple egret
#

Yes

swift falcon
#

and use json.fileutility ?

simple egret
#

JsonUtility.FromJson<EmployeeList>(str)

swift falcon
#

public TextAsset fileData;
public EmployeeList eL=new EmployeeList();
public class EmployeeInfo
{
public string Name;
public string Job;
}
public class EmployeeList
{
public EmployeeInfo[] Data;
}
private void Start()
{
eL = JsonUtility.FromJson<EmployeeList>(fileData.text);
}

#

good ?

simple egret
#

Yes, but you don't need to do new EmployeeList() in the field initializer, as you'll be replacing it anyway when Start runs

swift falcon
#

got it

simple egret
#

FromJson takes care of creating a new instance and filling it out for you

swift falcon
#

public TextAsset fileData;
public EmployeeList eL;
public class EmployeeInfo
{
public string Name;
public string Job;
}
public class EmployeeList
{
public EmployeeInfo[] Data;
}
private void Start()
{
eL = JsonUtility.FromJson<EmployeeList>(fileData.text);
Debug.Log(eL.Data.Length);
}

simple egret
#

Error on line 21, you tried to access something on a null reference

swift falcon
#

Debug.Log(eL.Data.Length); this

#

is line 21

simple egret
#

Either el was null (deserialization failed totally) or .Data was null (failed partially)

swift falcon
#

this works if I use [System.Serializable]

simple egret
#

I guess JsonUtility needs it to be serializable

swift falcon
simple egret
#

I use the Far Superior™️ Newtonsoft.json

swift falcon
#

yes

#

how to work with that

swift falcon
simple egret
#

More information in the stack trace, as always

delicate zinc
simple egret
#

Select the log to see more information in a box below the console

floral kiln
#

Anyone know how I can structure a class to be the deserialized version of this json object?

{
  "totalPages": 1,
  "data": [
    {
      "lastUpdate": 1694187564809,
      "targetName": "Black Box VR Global Feed",
      "actors": [
        {
          "name": "qatest"
        },
        {
          "name": "city_m"
        },
        {
          "name": "deejed"
        }
      ],
      "actorsCount": 58,
      "description": "qatest, city_m, deejed and 56 others posted in Black Box VR Global Feed"
    }
  ]
}
simple egret
#

Don't crosspost please

#

Keep the question in one channel

fervent furnace
#

dont cross post
{}=object
[]=array
so [{},{},{}...] array of some objects
and "key": value of this key, (the data type is implicitly stated here eg string is quoted, bounded by ")
eg the first field of this json will be

public int totalPages;//the value is 1 means it is an integer
floral kiln
#

Sorry about that guys, but selfishly so, I got help here and not there, so I'll delete it there.

This is what I had so far:

public class AmityNotificationPage
{
    public class Data
    {
        public long lastUpdate;
        public string targetType;
        public string verb;
        public string v_tarid_uid;
        public bool hasRead;
        public string imageUrl;
        public string avatarCustomUrl;
        public string targetName;
        public Dictionary<string, string> actors;
        public int actorsCount;
        public string parentTargetId;
        public string lastActionId;
        public string lastActionSegmentNo;
        public string targetId;
        public string description;
    }

    public int totalPages;
    public Data data;
}
#

so since [] = array, data should be an array?
But it has key and value pairs?

#

Ah so it's an array of <string, string> pairs

simple egret
#

actors is not in form of a Dictionary<T, T> in the JSON yeah

#

It would be more of a class containing a single name field of type string

floral kiln
#

I'll simplify the original json I sent here cause once I know how to do 1 of them, I can do the rest

heady iris
#

data would be a list of Data

#

notice how the json you posted above looks like this

#
data: [
  {
  
  }
]
floral kiln
#

The hard part is just how to structure data and then actors

heady iris
#

actors would also be a list of Actors

#

where Actor has just one field in it, yeah

floral kiln
#

List of type string?

heady iris
#

No. List<Data>

simple egret
#

List of string would be serialized as [ "a", "b", "c" ] so no

heady iris
#

your Data class is mostly correct, except that actors is wrong

#

because actors should be a List<Actor>

#

Every time you see a [ ], that means you need a List of whatever you see inside the square brackets.

floral kiln
#

hmmm why can data have its own class, but actors doesnt need to.
is it cause actors has the same key for each entry ("name")?

heady iris
#

actors does

#

actors is not a list of strings

#

it's a list of objects

floral kiln
#

but you're right... that's exactly it, true

heady iris
#

Indeed.

floral kiln
#

it just so happens we only have 1 here

heady iris
#

One way to do this is to work from the inside out

#

start at the innermost object or array you can find

#

if it's an object, make up a new class for it

#

if it's an array, then remember you need a List<T> (where T is whatever's in the brackets)

floral kiln
#
public class AmityNotificationPage
{
    public class Actor
    {
        public string name;
    }

    public class Data
    {
        public long lastUpdate;
        public string targetType;
        public string verb;
        public string v_tarid_uid;
        public bool hasRead;
        public string imageUrl;
        public string avatarCustomUrl;
        public string targetName;
        public List<Actor> actors;
        public int actorsCount;
        public string parentTargetId;
        public string lastActionId;
        public string lastActionSegmentNo;
        public string targetId;
        public string description;
    }

    public int totalPages;
    public List<Data> data;
}

This look better?

heady iris
#

so I might take these steps

#
{
  "totalPages": 1,
  "data": [
    {
      "lastUpdate": 1694187564809,
      "targetName": "Black Box VR Global Feed",
      "actors": [
        Actor,
        Actor,
        Actor
      ],
      "actorsCount": 58,
      "description": "qatest, city_m, deejed and 56 others posted in Black Box VR Global Feed"
    }
  ]
}
#
{
  "totalPages": 1,
  "data": [
     Data
  ]
}
#
AmityNotificationPage
#

and then we're done

floral kiln
#

Thank you @heady iris and @simple egret

heady iris
#

np!

swift falcon
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.IO;
public class EmployeeB : MonoBehaviour
{
    public TextAsset fileData;
    public EmployeeList eL;
    [System.Serializable]
    public class EmployeeInfo
    {
        public string Name;
        public int Wage;
        public int Number;
    }
    [System.Serializable]
    public class EmployeeList
    {
        public EmployeeInfo[] Data;
    }
    private void Awake()
    {
        
    }
    void LoadDataFromJson()
    {
        eL = JsonUtility.FromJson<EmployeeList>(fileData.text);
        
    }
    void SaveDataToJson()
    {
        string j=JsonUtility.ToJson(eL);
        File.WriteAllText(j,fileData.text);
    }
    public void BackButton()
    {
        LoadDataFromJson();
        eL.Data[0].Number += 1;
        SaveDataToJson();
    }
    private void Start()
    {
       
    }
}

#

here is my code

#

i can't seem to get the hang of writing the data into json file

#

please suggest me a better way to handle the json

gray mural
#

so in your code I don't see where you are supposed to get a path to your file

#

you should probabaly create a method for this ?

#
public string GetPath() => $@"{Application.dataPath}/Your/Desired/Json/Location/fileName.json";
#

so you get a string from a class and write is using a path

swift falcon
#

This smol registercallback invokes a StackOverFlow Exception. Any idea "why"?

#

Oh let me send you updateRotationCallback too

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

swift falcon
#
public override VisualElement CreatePropertyGUI(SerializedProperty property)
    {
        // Create a new VisualElement to be the root of our inspector UI
        VisualElement container = new();

        // Load and clone a visual tree from UXML for next values
        VisualTreeAsset visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Scripts/Addressables/Editor/InstantiationParametersSerializableUXML.uxml");
        visualTree.CloneTree(container);

        // Get Properties
        SerializedProperty rotProp = property.FindPropertyRelative("m_Rotation");
        SerializedProperty rotHintProp = property.FindPropertyRelative("m_RotationHint");

        // Bind Vector3 m_RotationHint property to Quaternion m_Rotation property with a callback
        var rotationHintElement = container.Q("RotationHint");
        
        // This is the callback causing the StackOverFlow
        Action<Vector3> updateRotationCallback =
        (value) =>
            {
                rotProp.quaternionValue = Quaternion.Euler(value);

                property.serializedObject.ApplyModifiedProperties();
            }
        ;

        // Initialize Rotation for first time only
        updateRotationCallback(rotHintProp.vector3Value);

        // Update current Rotation based on m_RotationHint's VisualElement value on change
        rotationHintElement.RegisterCallback<ChangeEvent<Vector3>>(
            (evt) =>
            {
                updateRotationCallback(evt.newValue);
            }
        );

        // Return the finished inspector UI
        return container;
    }
#

This works when you create the object of property drawer normally. But when you create an array of that object, it gets broken somehow.

gray mural
#

you trigger the same callback when you call updateRotationCallback and modify serialized property

#

so it leads to infinite while loop

swift falcon
#

What i first try is, putting property.serializedObject.Update(); which is aborts the unsaved properties and i got this error:

UnityEditor.RetainedMode:UpdateSchedulers ()```
#

Okey i am going to remove it

#

Gave me the same error notlikethis

gray mural
#

using mere bools

#
bool isUpdatingRot = false;

Action<Vector3> updateRotationCallback =
(value) =>
{
    if (!isUpdatingRot)
    {
        isUpdatingRot = true;

        rotProp.quaternionValue = Quaternion.Euler(value);
        property.serializedObject.ApplyModifiedProperties();

        isUpdatingRot = false;
    }
};
#

perhaps you should try it

swift falcon
#

Sure

#

No not works. Now i will try to edit the UXML

gray mural
# swift falcon No not works. Now i will try to edit the UXML

what if you check if they are not the same?

Action<Vector3> updateRotationCallback =
(value) =>
{
    Quaternion newRot = Quaternion.Euler(value);

    // Check if the new value is different from the existing one
    // They may be the same and this can cause an infinite while loop
    if (rotProp.quaternionValue != newRot)
    {
        rotProp.quaternionValue = newRot;
        property.serializedObject.ApplyModifiedProperties();
    }
};
swift falcon
#

Hm it does downgrade the exception to

UnityEditor.RetainedMode:UpdateSchedulers ()```
gray mural
#

it probably existed before, but was not send due to stack overflow

#

google doesn't have this error

swift falcon
#

Yep people usually face this issue with unity's packages lmao

#

I think i need to recreate this one

#

To solve

gray mural
#

I guess you have to make sure that all properties are set correctly

shell scarab
gray mural
#

@swift falcon also make sure that the path is correct

swift falcon
shell scarab
#

lol

#

can someone help me name my class? It just holds a few cancellation token sources and cancells them when needed. right now it's called AsyncApplicationCancellationManager but that's a bit unwieldy.

gray mural
ashen yoke
#

AsyncHandles

shell scarab
#

I like that one

gray mural
#

what is the best way to make a grid with 1x1 squares?

ashen yoke
#

what sort of grid

gray mural
#

to spawn my items

#

so I will drag them on that grid

#

I actually can do that via code

#

but it should be done with grid better?

ashen yoke
#

what are you asking, how to create the ui, visuals, underlying structure?

gray mural
#

is there are nice way to create a non-ui grid for GameObjects?

ashen yoke
#

its just a 2d array + positions snapping

shell scarab
#

nested for loop probably:

for(float a = startPoint.x; a <= endPoint.x; a += spacing) {
  for(float b = startPoint.y; b <= endPoint.y; b += spacing) {
    // grid stuff
    GameObject a = new();
    a.transform.position = new Vector2(a, b);
  }
}
#

for a vector3 just add another for loop.

shell scarab
#

oh, you're asking how to snap to a grid?

gray mural
#

I instantiate different items on an empty area, those items are not saved in any list now, they are then saved in the json file (from Transform _environment)

gray mural
#

if that's possibly

shell scarab
#
point *= Mathf.Pow(PointDistance, -1);
point.x = Mathf.Round(point.x);
point.y = Mathf.Round(point.y);
point /= Mathf.Pow(PointDistance, -1);
#

this is what I use currently.

#

where PointDistance is your grid size

ashen yoke
#
class Slot
{
    public GameObject value;
    public Vector3 position;
}

Slot[,] grid;

bool TryPlace(GameObject obj, Vector3 at)
{
    Slot slot = grid[(int)at.x, (int)at.z];
    if(slot.value != null)
        return false;
    slot.value = obj;
    obj.transform.position = slot.position;
    return true;
}
shell scarab
# shell scarab ```cs point *= Mathf.Pow(PointDistance, -1); point.x = Mathf.Round(point.x); poi...

I do the inverse power to get the denominator of the fraction that the decimal represents (essentially. Not actually what's happening but easier to understand). So if I make my grid size 0.25, it would correctly snap to 4 positions along a 1 unit line. If I did not do the inverse pow like i'm doing I would have to make my grid size 4 to snap to 4 positions per unit, which is a bit conter intuitive imo.

gray mural
#

I see, so there is no smth like build-in way to build a custom grid

gray mural
shell scarab
#

no but that's easy enough, it snaps a position to a point.

shell scarab
#

you could drop the pow, but then when you set your grid size it's a bit counter-intuitive. A grid size of 4 would not be 4 unity units per grid unit, it would be 4 grid units per unity unit. (if I don't pow it) If I do pow it, a grid size of 4 would be 4 unity units per grid unit.

robust dome
#

grid snapping exists in the editor but it is for non runtime

shell scarab
#

I hope that makes sense, it's a bit confusing to explain.

gray mural
#

it's quite confusing for me as well

shell scarab
#

let me draw something rq lmao

gray mural
#

I actually don't want to make a fixed size for it

#

I just want to to drag my items in grid

shell scarab
#

no there is no fixed size for my method. It just rounds the object's position to a point in space.

gray mural
#

so it's probably just manipulations with an item using mouse position

gray mural
ashen yoke
#

if you use mouse position, it will be the position from which you derive object position

#

mouse moves freely, object snaps

gray mural
#

oh, yeah, that makes sense

ashen yoke
#

should be some offset

gray mural
#

I will just have to make it snap just when the mouse is inside the 1x1

ashen yoke
#

initial click to object position, which is then added to current mouse position, from which you get the snapped position

#

i think we already had this discussion before

#

you can also lerp the object pos for juice 🙂

shell scarab
#

Each black square is a unity square unit. The left is with the gid's size powed to -1. The right is if it's not.

So if I put a grid size of 0.5 without powing it, the right is what I'd get. With powing it, the left is what I'd get.

If I put a grid size of 2 without powing it, the left is what I'd get. With powing it, the right is what I'd get.

#

I think. May be wrong on the right side one, but the left side one is correct. I hope this gets the point across.

ashen yoke
#

i think i use this for snapping/

#
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float RoundTo(float value, float to)
        {
            return Mathf.Round(value / to) * to;
        }```
#

i think it works, so far

shell scarab
#

that's what I do too, but for me it's easier to think that for example 0.5 grid size is a point every 0.5 units instead of a point every like 2 units or whatever it would be. So instead of passing in 2 as to, I would pass in 0.5 as to and then pow it with -1 (which gives 2)

gray mural
ashen yoke
#

yeah it works

    public static Vector3 RoundTo(Vector3 value, float to)
    {
        return new Vector3(
            RoundTo(value.x, to),
            RoundTo(value.y, to),
            RoundTo(value.z, to));
    }
gray mural
shell scarab
#

it depends on what your grid size/spacing is. If your grid size is 6 with my formula, then yes (I'm pretty sure at least. Not good at quick maths.).

gray mural
#

but why do we have to use grid size if it fully depends on it?

#

we can just round it actually?

shell scarab
#

Im just calling it grid size. it' just the grid spacing

#

I am rounding

gray mural
#

I think we can just round it without using grid size?

shell scarab
#

no

swift falcon
shell scarab
ashen yoke
shell scarab
#

@ashen yoke ik what it does but I was gonna ask why you thought it was needed?

ashen yoke
#

because those things tend to be hotpaths

#

im happily trading exe size over performance on hotpaths

gray mural
ashen yoke
#

most of my utils have this flag

gray mural
#

maybe I don't understand something

shell scarab
shell scarab
# ashen yoke most of my utils have this flag

according to the docs "Unnecessary use of this attribute can reduce performance. The attribute might cause implementation limits to be encountered that will result in slower generated code."

ashen yoke
#

but tests i did shown massive gains, generally

shell scarab
# gray mural yes.

as I said. It's easier for me to imagine a grid as spacing. So if my grid spacing is 0.25, I want my objects to be placed every 0.25 units, not ever 4 units.

shell scarab
#

because the whole round(number / to) * to moves towards smaller rounding increments the larger to is.

gray mural
#

but it's very strange ?

#

if you have 100x100 grid

#

you want to make small blocks .01x.01 ?

#

or by grid spacing you mean space between objects?

shell scarab
gray mural
#

not the size of objects?

gray mural
shell scarab
#

anyways @ashen yoke why not AggressiveOptimization then? or did you test it?

gray mural
#

I see, it probably will be possible to do with spaces, but it's not needed, because I don't want any spacings

shell scarab
#

no. I just trust the compiler to be smart enough.

ashen yoke
#

did you use AgressiveInlining?

shell scarab
#

no

gray mural
#

so I will try to round my mouse position and add a little offset if needed tomorrow, thank you both for your help ;D appreciate that

ashen yoke
#

its just that AggressiveOptimization is not available on 4.8

shell scarab
#

oh really?

#

well all it does is skip T0 compilation and does not do regular JIT on it.

ashen yoke
#

ill check it out when we move to unity version supporting new features

shell scarab
#

I wonder how many references/calls a method needs before [MethodImpl(MethodImplOptions.AggressiveInlining)] improves performance. I have 5 references but one is in a loop. I tried it but it did not change anything.

ashen yoke
#

how are you testing it?

shell scarab
#

I'm logging the time and subtracting the time for my existing code already. I just added that to two methods and it didn't change the time it took.

ashen yoke
#

about the JIT and trusting it, you know of the intrinsics initiative? core clr and so on, when it went open source and the amount of optimizations skyrocketed?

shell scarab
#

no i don't know of that

ashen yoke
#

well the jit is open source, people improve it all the time for years

#

problem for us is that this started after 4.8

#

when unity will finally introduce updated new .net i will have to relearn everything

ashen yoke
#

build or editor

shell scarab
ashen yoke
#

no

#

optimizations only apply to release mode

shell scarab
#

Why?

ashen yoke
#

thats how .net apps work afaik, a flag is set for compiler optimizations to be enabled or not

#

in debug mode they are not enabled

shell scarab
#

does unity run it in debug mode? I don't have debug mode enabled.

ashen yoke
#

yes its by default in debug build mode

#

editor itself

#

same as a new project in vs

#

defaults to debug build with pdb and disabled optimizations

shell scarab
#

what is the debug mode for unity then

ashen yoke
#

its .net terminology, unity uses it

shell scarab
#

i mean this little button

#

what's it do

ashen yoke
#

switches release/debug compilation mode

#

create new vs project for 4.8

shell scarab
#

and by default it's off so the optimization should affect it, no?

ashen yoke
#

open properties, see the build modes, see that release has optimizations enabled, debug doesnt

shell scarab
#

anyways, I tested it in a build. It's like .2 ms faster so i guess I'll keep it.

ashen yoke
#

yes, editor by default runs with disabled optimizations, builds have them enabled

#

release mode will compile assemblies as if it was a build, with all optimizations enabled

#

its still not indicative of build performance, but its closer

shell scarab
#

I thought I've been in release mode cus it's the bug crossed out.

ashen yoke
#

yes you were, didnt notice

shell scarab
#

I usually just stay in release mode unless I have errors leading me to the wrong lines, which can sometimes happen in release mode...

#

especially with the damn burst compiler lol

ashen yoke
#

just thought more about it, im basing my intuition about inline on the struct based ecs i did shortly after unity announced its own, and there inline in some cases improved performance x10 and more, mostly with granular small methods on hotpaths

#

i observed actual massive gains, and since barely anything changed since then in unity's .net im still relying on those observations

#

oh and unity seems to agree

shell scarab
#

?

ashen yoke
#
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public uint3x4(uint3 c0, uint3 c1, uint3 c2, uint3 c3)
        {
            this.c0 = c0;
            this.c1 = c1;
            this.c2 = c2;
            this.c3 = c3;
        }
shell scarab
#

ah lol

ashen yoke
#

all of Unity.Mathematics is covered by it

shell scarab
#

yea, hotpaths make sense for aggressive inlining.

#

I also have a question about assemblies. Is it just an organizational choice to split your project up?

ashen yoke
#

depends

#

if you have setup the asmb hierarchy properly you can save up on compile time, generally assemblies are treated as the main player in .net, everything is designed around it having a public and internal sides

swift falcon
#

does json files not work in android build ?

ashen yoke
#

unity takes away direct work with assemblies, linking them, chaining projects, with closest thing being asdefs

shell scarab
#

ah so the correct way to do it is to chain it one-way?

ashen yoke
#

thats the only way to do it, afaik from out of unity experience

shell scarab
#

does it give you an error if you try to reference an essembly that is referenced by the assembly you're trying to reference?

ashen yoke
#

yep

shell scarab
#

ah

#

also reminds me of a project I want to try. I want to make a c++ DLL with some stuff in it and call it in unity. Wonder if it'd make my pathfinding faster... I'd have to manage the threads myself tho...

rancid frost
#

I want to enable and disable those UI object(red line right side), on a certain animation keyframe. How do I do that?

shell scarab
#

this button I believe. It can let you trigger script execution on certain frames. So you can disable it without it being a child.

ashen yoke
#

press record, disable

#

they have to children of the object with animator on it

rancid frost
#

ahh I see

shell scarab
ashen yoke
#

you can do it without event if you make a script that relays state on Enable/Disable

rancid frost
#

Got it it works now!

ashen yoke
#

sounds dirty, but events are dirty to me themselves, how they are implemented

shell scarab
#

unity events or events in general

#

cus I'm biased towards events.

ashen yoke
#

unity anim events in particular

shell scarab
#

lol

ashen yoke
#

i mean..

#

lets find why animations broke, simple maintenance task - go through all animations and compare the strings in events to the method name

rancid frost
#

I used enums with those strings

#

much better

ashen yoke
#

i use animancer and custom events

rancid frost
#

is that a custom animator?

shell scarab
#

mine just has a dropdown of methods to select once I add it to an object.

rancid frost
#

that dropdown is actually anoying

#

no scrollbar?

#

like cmon

shell scarab
#

better than whatever that is

rancid frost
#

lmao

#

you can click on them individually @shell scarab

shell scarab
#

yea

#

hold on

#

@rancid frost

rancid frost
#

You guys ever feel guilty playing video games ever since u started making video games?
Now i get guilty knowing I oculd be making a game instead of playing it

rancid frost
#

Ahh, so its when u click on an animation object vs when you dont

simple egret
#

You get the dropdown version when you select the animation event while focused on an object in the scene (or prefab) that has your Animator attached

#

Else you get the generic "enter anything" version

rancid frost
#

if u click on the object(right) directly, u get that

ashen yoke
#

still, profoundly flawed approach in large projects

#

maintenance hell

shell scarab
#

idk, never had it break on me and I've been in a few large projects.

#

just don't ever rename the method haha

zealous dawn
#

I posted this the other day in #🏃┃animation but I have a feeling this problem is going to require a more… custom solution

I'm trying to record a specific texture and audio while in the production game, not in the editor, but I can't find a great tool for the job. Unity Recorder only works in the editor and is a non-option, sadly.

Right now I'm using Spout2 with OBS for the texture along with a window recorder also in OBS for the audio, but it has quality and desync issues that I'm trying to avoid, plus it's just an overall complex way of doing things.

Does anyone have any recommendations or ideas on how I could record all of this?

drowsy holly
#

quick question: I have a simple script that I attach to lamps from a prefab pack to change their material (from non-emissive to emissive). Is there a way to have defaults through the editor for every prefab that uses the script? (to avoid manually setting the on/off material on numerous lamp prefabs)

leaden ice
drowsy holly
drowsy holly
leaden ice
#

Yes

#

That's expected

#

Isn't that what you are doing

#

Adding this script to objects in edit mode?

drowsy holly
#

hmm, is the expected behavior that prefabs that have this script will have those materials by default?

leaden ice
#

The expected behavior is that if you attach the script to an object in the editor after setting the defaults, the references will be set

#

If you attached it before setting the defaults, nothing will happen

drowsy holly
#

OH

#

that's exactly what I did - I thought they'd update dynamically or something

leaden ice
#

No

drowsy holly
#

ok yeah, that works

#

thank you

green radish
#

would it be more performant to iterate through more small tilemaps, or less big tilemaps?

#

trying to decide how big each chunk of tiles should be for my sandbox game

steady moat
#

Usually, you want to have as few as "unused" tile activated.

#

With the least amount of chunk

green radish
#

so as few active tilemaps as possible in the project?

steady moat
#

So, if you have a game that use large amount of tile, larger chunks make more sense.

steady moat
#

The ideal scenario, is 1 tilemap that contains all the used tile and no non used tiles.

green radish
#

is it mainly just as few active tiles as possible or do tilemaps themselves have a considerable computational cost by existing?

steady moat
#

Without even knowing the cost of tilemaps, the only fact that you have more than necessary should be enough to you to know that you want to reduce them.

#

However, that being said, it is if you strives to have the best performance.

#

In most case, you can just profile and see for yourself.

#

Sometimes, inefficient method are not enough inefficient to matter.

green radish
#

I ask because the idea I had was for each chunk to be its own tilemap, then a 2D list/array storing the tiledata for that chunk

steady moat
#

Yeah, and you want the least amount of tilemap with the least amount of useless tiles.

#

It is a multiconstraint problem that varies on the type of game you are doing and the actual cost of having useless tile vs having more tilemaps

green radish
steady moat
#

Dont you want to have the tile to actual make that decision instead of iterating on every tiles to ask them ?

green radish
#

tiles in a tilemap cant store unique data though

shell scarab
#

Perhaps have each chunk saved as a hashset?

steady moat
green radish
steady moat
#

Instead of operating on the tilemap, use it only as a renderer

steady moat
shell scarab
#

Why do you need to loop them anyway? I read through everything, maybe i missed something

steady moat
green radish
#

for instance a sand tile shouldnt hover midair, it should start falling

#

so when checking a sand tile it should then check surrounding tiles to see if they are air, if so, spawn a fallingsand gameobject

steady moat
#

Yeah, and it makes more sense for the sand tile to do that than somebody else.

green radish
#

I plan to have upwards of roughly 6400 tiles on screen

steady moat
#

Personally, I think you are way better off using a C# representation of your game and only using the tilemap as renderer and initializer.

shell scarab
#

if you want to do that then maybe store it as a hashset and iterate through that as a 2D array and that would probably be quickest. You dont need to constantly loop, you can just signal whenever something happens to update that chunk.

green radish
shell scarab
#

like each chunk would just simply store the min x/y and max x/y, and a hashset for the state of all the tiles. Then you would just update the tilemap visually

steady moat
#

(And only those that needs to be updated)

green radish
#

so only reference the tile when it comes to creation or deletion

ashen yoke
#

im sorry im half afk

#

reading

green radish
#

sand tile

ashen yoke
#

that does not imply full iteration

#

to become mid air the tile state has to change

#

a change in state is an event

green radish
#

or it started midair for some reason

ashen yoke
#

still, initialization

#

one time event

shell scarab
#

if you want it to constantly be updating your best bet imo is to multithread it, otherwise you should use events

green radish
#

if a sand tile has adjacent tiles it would just be skipped, same applies to the logic of any dynamic tile

shell scarab
#

Usually sandbox games to my knowledge use different threads in some capacity to update the world

steady moat
#

Also, this can be done further down the line if needed.

shell scarab
ashen yoke
#

80*80?

green radish
#

Unity can multithread but when you do that the syntax of practically everything changes and you are forced to use the DOTS system to some level

ashen yoke
#

what format is the game in?

#

top down 2d rimworld like?

steady moat
shell scarab
#

Then don’t call unity API

steady moat
#

Unfortunatly, when you are doing a Unity game, you kinda need to call Unity function.

green radish
ashen yoke
#

pixel art?

shell scarab
#

constantly check if the chunk needs to be updated. If it does, notify the main thread and it would update it. That way you offload the checking loop to a different thread and the main loop can focus on rendering and other game logic.

ashen yoke
#

hard alpha?

green radish
ashen yoke
#

then you can use quad per chunk

#

rather per layer of the chunk

shell scarab
ashen yoke
#

draw tiles on the shader

#

one atlas per layer

#

256 tiles per atlas

#

to control you update pixel in the control tex

steady moat
ashen yoke
#

this will provide the best control/performance

#

for changes in the chunk you dont need to iterate everything, you need to collect modified tiles, and the batch process them

#

one modified tile = 9 tiles added to processing queue

#

if tile was added, ignore it, very fast

shell scarab
ashen yoke
#

whole thing screams Job system

shell scarab
#

I only dont use job system bc it wont let you use managed objects

#

and i like my queues and stacks

#

there is no NativeStack either.

ashen yoke
#

yeah it may not be necessary at all

#

terraria doesnt use jobs, works just fine

spring creek
green radish
#

the reason using the DOTS system is a problem for me is because last time I tried to use it I ran into the issue that it's an unfinished feature, and thus not fully functional

#

cant do everything gameobjects do

shell scarab
shell scarab
quartz folio
shell scarab
#

DOTS is a whole set of packages

quartz folio
#

Jobs, collections, and burst all function as they are designed, with limitations to get maximum speed

shell scarab
#

also dots is just… complicated (imo) for how you’re suppose to code things

#

using only the job system on the other hand, much more doable. And you can burst it too since it already wont let you use managed objects.

quartz folio
#

the job system is a part of DOTS. Do you mean Entities/ECS when you say complicated coding?

shell scarab
#

Yes

#

i feel like DOTS refers to all the dots packages, not only specific parts

quartz folio
#

Either way, you can multithread however you want, most of Unity's API can't be used in it, Jobs+Native Collections+Burst is really really fast if you're up for getting your data prepared correctly

#

Yes, it's Jobs/Burst/Collections/Entities/Entities packages in one big pile

shell scarab
#

Yea

#

i mean burst can get a bit complicated to program for me since I’m not used to or experienced with pointers, but ecs is just weird to me bc it’s data oriented not object oriented, with a separation of systems components and entities. At least in. Jobs/burst i can still pretend there’s objects.

quartz folio
#

You don't generally need to do anything with Burst apart from putting the [BurstCompile] attribute on a job that doesn't use anything managed

#

Anything pointers is just additional and irrelevant to getting most things done

shell scarab
quartz folio
#

Yes, and you don't have to deal with pointers directly, you just allocate a native collection type, pass it in, write to it in the job, read from it when it's done, and dispose of it.

shell scarab
shell scarab
quartz folio
#

I don't; it's just a struct with a reference to the backing array in it. Sure it uses pointers but you don't have to even know that