#archived-code-general

1 messages ยท Page 177 of 1

west pelican
#

i used a debug log to figure out if the color is changing and it says it is

#

its changing between red and white but it isn't showing it

quartz folio
west pelican
#

ok

wispy raptor
#

i have a question, is there a way to use something like c#'s Func<T> but serializable?

#

like a unityevent but that returns something

leaden solstice
#

You can make a function ID or enum that you define and call function based on it

lean sail
#

Unity events are already somewhat limited so I dont think this would be too easy to get working

delicate zinc
#

bump (apologies if this isnt allowed lul)

lean sail
# delicate zinc bump (apologies if this isnt allowed lul)

if it works in 1 case and not the other, id just start debugging everything related to the code youve posted and make sure the values match what they should be.
Try to even recreate it without the moving objects, and see if the raycast hits in the same position

worn stirrup
#

I'm trying to figure out how to make a single manager check a random number, attempt to spawn that number's object, and if it fails, re-attempt other types, but I can't come up with a clean way to put it together and it's getting pretty jumbled right now, does anybody have any pointers for something that handles this?

#

I can't really figure out how to google for this specific of a spawning behavior

leaden ice
#

Have you somehow associated numbers with objects?

#

"if it fails" < what could/would cause it to fail?

lean sail
#

sounds like the numbers are IDs, and not everything can spawn in some areas?

worn stirrup
#

Uhhh good questions okay

dusk apex
#

If you're simply trying to not repeat selections or have invalid selections, perhaps remove those selections from the possible choices to be selected.

worn stirrup
#

I'd like for it to have a set of object categories, and it attempts to spawn from each category at random (being able to weight those would be nice, like some categories are still more likely than others), but if it finds out the max limit of that object is in play, or the max for that level has been spawned already, it skips and attempts another

#

That way the spawner is always consistently trickling in what's necessary until it's done, and it doesn't skip 2 or 3 attempts because it keeps trying to spawn a maxed category already

leaden ice
#

there shouldn't be any retries necessary

#

because you should remove invalid choices from the pool before picking

dusk apex
#

When you spawn the object, if max has been reached for that object remove it from the list.

worn stirrup
#

Except the list of spawnables is just a range of a resource.load pull e.e I pulled that from a tutorial for spawning random objects of a category

leaden ice
#

and yes weighted random selection is pretty well trod ground

worn stirrup
#

But like

#

I don't immediately see a better way to do it that fixes this problem

leaden ice
#

You don't have to stick with what a tutorial taught. In fact tutorial solutions are often suboptimal and not easy to maintain and expand

dusk apex
#

Retrying is not preferable

leaden ice
#

anyway i have to get some sleep

#

see ya

worn stirrup
#

My issue with ScriptableObjects is being able to pull and use their data at runtime, because I end up having to generate something that clones the SO's data into an empty GO in the scene to be referenced

#

I've never figured out how to put a bunch of data in a ScriptableObject and reference that data from an object in-scene without cloning each varaint of the ScriptableObject into an in-scene reference, and that feels like a junky way to get around it

#

So I'm trying to avoid the ScriptableObject problem, and I think I'm just hitting that block

#

It's all too hard-coded now

dusk apex
#

Either way, retrying is not preferred

worn stirrup
#

What exaclty do you mean by retrying?

worn stirrup
#

Yeah no I definitely want to get around that

#

But this is going to take a lot more forethought than I have available tonight ๐Ÿ˜…

#

So I'll think and plan that out and come back later when I'm implementing

dusk apex
#

Instead of trying to not generate the invalid number, consider changing the collection to not have invalid entries

worn stirrup
#

Yeah that makes sense, that's what Praetor had said too at some point, that's a good appraoch

#

Thank you :3

leaden ice
#

Just reference it directly

#

especially if it's not mutable

#

like in this case

#

but yes think of them as data stores

#

they don't need to be the final runtime data structure you're dealing with

#

just a basis for static information to build that with

worn stirrup
#

Yeah that's exactly how I'd use them, I have a lot of intermingling physics and objects that should come from others, so I need to set up all the relationships of what each thing has, their mass ranges, speeds, and resources provided when obtained

elder flax
#

im having an issue with textmesh pro

#

it was working fine earlier but I built my mac version to Intel instead of Intel+silicon and now all my tmp text is invisible in the build

#

the thing is, the text is only invisible if it was active on the scene start

#

if it was inactive or instantiated after scene start its fine

#

and it only happens when i enter my play scene, my mainmenu scene is fine

#

should i reinstall tmpro or something

#

the only thing i did that might have affected it is add standard (specular) to the included shaders

wicked cape
leaden ice
trim spoke
#

Hi guys , upon uploading my unity android build to google play i get a warning
"Androidx.fragment:fragment has reported version 1.0.0 as outdated" has anyone seen this error? How to resolve?

bleak thorn
bleak thorn
prime sinew
void remnant
#

Hello, is there any difference between StopCoroutine(IEnumerator) and StopCoroutine(Coroutine)? If yes, then what's better to use?

prime sinew
#

@void remnant
I personally only use the Coroutine one, because most times I want to stop a specific instance of a Coroutine

#

I dont know if the IEnumerator version lets you do that

tired elk
#

It may stop the first or all coroutine which comes from the IEnumerator since it can be linked to multiple Coroutine instances.

#

I prefer the 3rd option too since it's an instance and you have better control of where and when it's assigned

void remnant
#

Ok, thank you very much

cinder oriole
#

Hello guys i have a bug currently ongoing in my game and i've been trying to find out whats wrong for the past 4 hours,

so basically i instantiated a bunch of items from a list of an item scriptableobject, and then i destroy it via script, and the next time i instantiate a new set of items, for some reason the old destroyed items appeared once again in the scrollview please help

#

also for some reason my game has invalid AABB errors idk what that means

tired elk
cinder oriole
tired elk
#

OK. What can happen is you're disabling the object that holds all instances before the destruction method runs.

cinder oriole
tired elk
#

FindGameObjectsWithTag() only work fork active objects

cinder oriole
#

i call destroy from here

cinder oriole
#

if u watch the video, u see then i click 'continue' button, all the gameobjects inside the panel gets destroyed

#

but for some reason the next time i instantiate new items, the old ones magically reappear

tired elk
#

You're right, my bad. currentItemScene.itemsSO is fed at some point ?

regal flame
#

are you never removing the items from currentItemScene.itemSO?

tired elk
#

Like, is there something that fill this list/array ?

cinder oriole
cinder oriole
#

oh should i try and remove everything from the list and see if thatworks?

#

so destroy the game objects and remove everything from the list

tired elk
#

Well, you could try. The foreach may run longer than you think.

cinder oriole
#

hmm alright, thanks so much for the help guys, i'll get back here if it didnt work

regal flame
#

set a debug.log in the foreach with the gameobjects name (or any unique identifier) and you should see that you are instantiating more than you intend on, probably atleast

cinder oriole
#

so somehow they just ghosted their way through the debug.log and just reappeared in the scrollview

tired elk
#

Now this is weird

cinder oriole
#

sorry, how do i remove all elements from a list via script?

#

can i use RemoveAll()?

regal flame
#

List<> list; list.clear();

cinder oriole
#

okay thanks

#

OMG IT WORKS

#

thank you brother

#

i had this going for 5 hours

#

i love u guys

regal flame
#

glad you solved it ๐Ÿ˜„

tired elk
#

Nice ! Well played ๐Ÿ™‚

tired elk
cinder oriole
#

oh right..

#

but anyways i guess i'll stick with the clearing list for now

#

but yea i did try to run the old code again without a collapsed console, and did Debug.Log(item.name) on the foreach loop, and turns out it did instantiate the old items @tired elk

#

but thats weird, can you think of any workaround if i dont want to clear the list but instead just destroy the gameobjects?

#

i mean yea clearing the list solved my problem but what if i wanted to revisit it in the future

tired elk
#

The list is fed with new stuff at some point in your code. You should find where this happens.

#

If the inspector was the only place, it wouldn't do this.

regal flame
#

you probably just don't want to instantiate it all from the same list, separate into different collections, or just be mindful of what you populate that list with

tired elk
#

Do you have like a "Get current item scene" method ?

cinder oriole
#

its not from the same list, just from different instances of a single Item script

tired elk
#

If you're unsure, you could right click itemsSO in your IDE, click "Find all references" and check if you have Add() or AddRange() called on it somewhere in your code

cinder oriole
#

hmm

#

okay

#

let me chcek

#

whatever i'll just stick with this for now im too tired for this

idle stratus
#

I'm trying to refer to a canvas gameObject inside a prefab, but whenever i turn it into a prefab, it clears the field and when I try to reassign it it shows this

#

inside the script Game Logic is marked as a GameObject

#

should I just use Find()?

prime sinew
idle stratus
#

drag it in the assets folder

prime sinew
#

where is this canvas gameobject

idle stratus
#

Scene>EmptyGameobject>canvas

#

the empty gameobject is to organise stuff

prime sinew
#

so just to be clear, you have another object in the scene(let's call this ObjectA) that has a reference to this canvas object

#

and you want to turn ObjectA into a prefab

idle stratus
#

yes

prime sinew
#

prefabs cannot have references to scene objects

idle stratus
#

oh well that clears it

prime sinew
#

you need to assign it at runtime

idle stratus
prime sinew
#

usually the spawner of the object should hold a reference to this canvas object

#

then it passes this reference to the spawned prefab instance

idle stratus
#

the spawner is the canvas

prime sinew
#

okay, so pass itself into the spawned object

#

using a function or something

#

see Dependency injection

meager wasp
#

Hello, I'm currently trying to get dual monitors to work. I read https://docs.unity3d.com/Manual/MultiDisplay.html on how to activate the screen and that works just fine but it activates on my main monitor and I can't get the normal Window options to. Move it to 2. Monitor. Is there some way to activate it on 2. Monitor directly or get the normal window options back to. Move it myself?

idle stratus
cinder oriole
#

does anyone know what this error is and if it'll ruin my build if i decide to go on with it

prime sinew
agile temple
#

Hello, I have issue with gun hitting my enemies. Main problem is I look for enemies through box collider but I have there some spread of bullets to make my game little bit random but I deal damage only if I hit in the collider and if I do bigger collider it will damage too many enemies. Also I cant use bullet trail beacuse it has problem with gameobject and my enemies are some different type. Here is my code https://pastebin.com/qFHqJf3Y

prime sinew
idle stratus
#

will the program recognize that the prefab has this variable?

prime sinew
#

... if you access the component of the prefab.. sure?

idle stratus
#

aah okay i get it

#

thanks

rocky helm
#

If I am going to be calling GetComponent<T>() a lot in a frame, would it be faster to have a single script already holding public variables for those components, or would it have the same effect as just calling GetComponent for each of the components I need?

regal flame
#

If you can avoid GetComponent then do so in my book

#

especially if doing it often

tired elk
lethal plank
#

guys will List.AddRange(AnotherList); affect to "AnotherList"?

hexed coral
lethal plank
#

ok thank you

#

mine are somehow affect to "AnotherList"

hexed coral
#

If that's happening it's not on that line of code, you should consider showing us how the rest of your code looks like

lethal plank
#

i will figure it out first

#

if i cant find any then i will ask

rigid island
lethal plank
#

hmm its happening just like i let List = AnotherList but only affect the part i added

hexed coral
#

Oh

lethal plank
#

when i add something in List it not add to AnotherList

hexed coral
#

You are mutating the same object

lethal plank
#

ah

hexed coral
#

List = AnotherList makes both point to the same reference

oblique spoke
hexed coral
#

If you want to clone a list:
List = new List(AnotherList)

oblique spoke
#

AddRange should also be fine

lethal plank
#

one is for working and on is based

hexed coral
lethal plank
#

oh sorry

oblique spoke
#

Structs and other value types are cloned, but class references will still point to the objects living elsewhere

lethal plank
#

"List" is a list im using it for working
"AnotherList" is the object i use it for reference

#

if i using right word

hexed coral
lethal plank
#

if you could understand it xd

#

here

#

when i delete line 31 it will not affect data.AttachmentSlots

sudden meadow
#

How do I make unity cease adding tons of namespaces automatically?

lethal plank
#

bro too lazy XD

gray thunder
#

It either adds the basic namespaces

#

Or requires you to add the ones you need

sudden meadow
#

it doesn't. it adds tons of things it thinks i need all the time

#

for example probuilder for "Sprite"

oblique spoke
#

Unintended includes are probably coming from typos that you aren't undoing

sudden meadow
#

well, regardless, no way to make it less aggressive when it comes to this? it likes making edits to shader code too without asking

lethal plank
rigid island
hexed coral
gray thunder
#

afaik you can right click them and click on something like 'remove all unused namespaces'

#

something along those lines

sudden meadow
#

@rigid island i wouldn't mind adding a few namespaces

rigid island
#

also its not unity adding it, and its VS

oblique spoke
late lion
oblique spoke
#

Yea pretty sure this is a feature in VS

rigid island
lethal plank
#

alright

lethal plank
#

i see
so there are no way to clone or copy it?

rigid island
#

see this

lethal plank
#

ok

carmine prism
#

I'm using the following script to move a rigidbody player, but when checking velocity.magnitude of the rigidbody, it looks like the rigidbody has higher velocity whenever it goes up a slope.
Any ideas what i'm doing wrong?

private void MovePlayer()
{
    moveValues = playerControls.Move.ReadValue<Vector2>();
    if (isGrounded && moveValues == Vector2.zero) { EnableFriction(); }
    else { DisableFriction(); }



    float calcedMovementSpeed = walkSpeed;
    if (isSprinting && moveValues.x == 0 && moveValues.y > 0) { calcedMovementSpeed = sprintSpeed; } // SPRINT IF GOING FORWARD AND NOT GOING SIDEWAYS
    if (isCrouching) { calcedMovementSpeed *= crouchSpeedModifier; }

    Vector3 movement = (transform.right * moveValues.x) + (transform.forward * moveValues.y);

    movement *= calcedMovementSpeed;
    movement.y = rigidbody.velocity.y;

    rigidbody.velocity = movement;
}
#

specifically: higher the slope angle, higher the velocity

hexed coral
# lethal plank thanks

Also, if you're cloning a class all the time there's a good chance it should be a struct instead, though be careful dealing with structs, they have a lot of small rules that might not be intuitive at first glance

static matrix
#

is it possible to do occlusion culling if I cant do any baking?

#

like is there a builtin way to do it

swift falcon
#

My breakpoints don't seem to be working, anyone know why?
I feel like I remember getting more feedback that I activated a breakpoint, more things going red or something

I am in debug mode in Unity

knotty sun
#

you are either not attached or not in play mode.
Notice 'Attach to Unity' at the top

swift falcon
#

Ah right that worked thanks

glossy ledge
#

So if anyone has run into a similar issue, this is how I solved it.

First I added this to the Android Manifest :
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES"/>

And I used this code to get the Android version and depending on the os version do one thing or another:
https://pastebin.com/qGikWUEi

round creek
#

anyone have any idea as to why my trail flickers at the end? for context, player moves and camera follows.

round creek
#

rb.moveposition

leaden ice
#

Update? FixedUpdate?

rigid island
round creek
leaden ice
round creek
#

no

leaden ice
#

turn it on

round creek
#

k

#

still the same

#

btw the trail renderer is attached to a child object of the player

leaden ice
#

should be fine

rigid island
#

the greens look also choppy but hard to tell on a 1 sec video

#

maybe its the cam parenting

leaden ice
#

how is the camera moving

round creek
leaden ice
#

Once you have rigidbody interpolation enabled, the camera should be following in LateUpdate

#

(or ideally with Cinemachine)

round creek
leaden ice
#

use the transform position

#

rb position is not interpolated

#

transform position is

#

also yes move to LateUpdate

round creek
leaden ice
#

yes the physics updates are not in sync with the frame updates

#

hence the need for interpolation

#

and once interpolation is on you need to just make sure your camera is following the interpolated position

round creek
leaden ice
#

That's my recommendation yes

#

lmk if it helps

rocky helm
#

So, I'm doing rigidbody.position = ...; but there seems to be a chance of this sometimes not moving the rigidbody at all which is quite odd. The rigidbody is CollisionDetectionMode.ContinuousSpeculative; and RigidbodyInterpolation.Extrapolate;. I am also changing rigidbody.rotation and transform.parent on the same frame, in case that matters. Also, I used to do this with around 100 objects in one frame and when it happened, it happened to all of them and it is still like that. I am unable to give logs of the rigidbody position after setting it when it glitches, because every god damn time I put a Debug.Log() anywhere it just completely stops happening, but I can ensure you that the position it is being set to is static and definentely not 0,0,0 where the pieces are being set to.

#

I have a theory that this could maybe be related to Update and FixedUpdate firing in a certain sequence which makes this happen for some reason??

#

Also google hasn't been of much help for me in this and this has been a problem for more than a week now

round creek
#

lmk if it helps

leaden ice
#

those only apply when using velocity or adding forces

rocky helm
#

Yeah, I just added them in case they help, since I am not sure what is causing my problem

leaden ice
#

perhaps an animator? Or some other code setting the position, or the physics simulation fighting with you?

rocky helm
modern creek
#

When I use a TileMap and Grid, I don't see any gameobjects for each of the sprites. If I wanted there to be some sort of underlying data structure or game object.. do I have to use the GemBrush or something else to create the tiles programmatically..?

#

Or am I approaching this the wrong way - should I create my underlying data structure and optionally my game objects, then render the tilemap as a "view" of those objects? The tutorials I see look like they do something like create an int[,] and populate it, then populate a tilemap based on the values in their array

#

(And I'm assuming then that user input is "collected" by unity but then I'll have to flow it back to my objects - ie, by overriding TileBase and implementing click handlers)

twilit canyon
#

Hello, I made a question in unity forums but didn't got help, only one person answered without even bothering to read the post, then i made a post in stack overflow, got 2 comments of people that didn't bother to see everything and a downvote, last time i got a downvote no one answered after, if anyone can help me i would appreciate it, all of the info about my problem is here: https://pastebin.com/4U0YcDJW

leaden ice
twilit canyon
#

but that works fine

leaden ice
#

I mean it's a custom script of yours, that's not a built in part of the input system.

#

can you show the code for it

twilit canyon
#

ok

leaden ice
#

also whatever other components you have

#

also AddForce should not be used in Update

twilit canyon
#

ik

leaden ice
#

it belongs in FixedUpdate

twilit canyon
#

i changed it and didn't work

elfin quest
#

I'd change the movement to movement = rawmovement * speed * Time.fixedDeltaTime

rocky helm
# leaden ice can you show your code?
private GameObject ConvertConvexPolygon2DToShard(Vector2[] polygon, Transform relativeTo){
        if(emptyShardsIn.childCount == 0){
            CreateEmptyShards();
        }
        GameObject shatterPiece = emptyShardsIn.transform.GetChild(0).gameObject; //Grabs a pooled object
        shatterPiece.SetActive(true);
        GlassInfo glassInfo = shatterPiece.transform.GetComponent<GlassInfo>();
        Rigidbody rigidbody = glassInfo.m_rigidbody; //So I don't have to call GetComponent<T>() a lot
        rigidbody.rotation = relativeTo.rotation;
        MeshFilter meshFilter = glassInfo.meshFilter;
        MeshRenderer meshRenderer = glassInfo.meshRenderer;
        shatterPiece.transform.name = "GlassShard" + glassPieces.childCount;
        shatterPiece.transform.parent = glassPieces; //Maybe plays a role in this somehow?
        meshRenderer.material = brokenGlassMaterial;
        shatterPiece.layer = 7; //IgnorePickUp layer
        Mesh newMesh = new Mesh();
        Vector3[] vertices = new Vector3[polygon.Length];
        int[] triangles = new int[(vertices.Length-2)*3];
        Vector2 addedPoints = new Vector2(0,0);
        for(int i = 0; i < polygon.Length; i++){
            Vector2 point = polygon[i];
            addedPoints += point;
        }
        Vector2 medianCenter = addedPoints/polygon.Length;
        rigidbody.position = relativeTo.position + relativeTo.right * medianCenter.x + relativeTo.up * medianCenter.y; // <--
        // relativeTo is the transform where I want to create the shard
        Debug.Log(rigidbody.position); //Adding BOTH of these makes the glitch stop happening
        Debug.Log(relativeTo.position);
        //The script goes on for a bit from here, but I believe nothing it does has to do with setting the position, it just creates a mesh and assigns it to the mesh filter of the object
twilit canyon
elfin quest
#

I have never worked with addForce, but whould you not be multiplying by the fixedDeltaTime (when using it on FixedUpdate)

leaden ice
#

no

#

you should never multiply forces by deltaTime or fixedDeltaTime

#

nor should you call it in Update

leaden ice
#

notice that when you make it huge it goes way out of the world

#

just set it somewhere in between

#

and put it in FixedUpdate so it's consistent

twilit canyon
#

but if i decrease friction or make the force too big the object no clips or goes flying to narnia

leaden ice
#

make it bigger, but not too big

#

mama bear force

twilit canyon
#

i tried making it bigger

#

there is no somewhere in between

#

or is too big or is too small

elfin quest
leaden ice
#

otherwise it will be very inconsistent

twilit canyon
#

1

twilit canyon
#

someone already told me

#

is not working

leaden ice
twilit canyon
leaden ice
#

is it uses any custom physic materials etc

twilit canyon
#

(i'm using probuilder)

leaden ice
#

idk something is definitely odd in your scene

#

can you make a new scene

twilit canyon
#

ok

leaden ice
#

put just the player object in it

#

and a simple floor

#

and see how it behaves

twilit canyon
#

i made a new scene

#

it works fine

#

it has the movement i'm looking for

#

but why is the other scene failing?

leaden ice
#

some other script or something

twilit canyon
#

i have 3 other scripts

leaden ice
#

maybe on the MatchManager or CameraLimits or something

twilit canyon
#

camera limits?

#

oh

leaden ice
#

just pointing out objects in your scene that might have scripts on them

twilit canyon
#

match manager only has score values

#

i'll add it to the new scene

#

nothing

#

is the camera limits

#

that's causing it

rocky helm
candid forge
#

do any of you know how i could go about generating terrain like this from perlin noise?

rocky helm
# candid forge

https://www.youtube.com/watch?v=vFvwyu_ZKfU&t=478s Perhaps this video will be of help

In this video we create a terrain in Unity using Perlin Noise.

More on procedural generation:
โ— Sebastian Lague: http://bit.ly/2qR3Y3P
โ— Catlike Coding: http://bit.ly/11pMR7O

โ™ฅ Support my videos on Patreon: http://patreon.com/brackeys/

ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท

โ™ฅ Donate: http://brack...

โ–ถ Play video
candid forge
#

i've been racking my brain on how to generate procedural meshes from points but i'm wondering if i'm looking in the wrong place

candid forge
rocky helm
#

actually doesnt matter much

#

You could set up what was shown in the video, but snap those points on a grid on the y axis

candid forge
#

yeah, if i think about it, i can make it go down 90 degrees at certain points

#

i will try thank you

leaden ice
rocky helm
#

Please don't tell me this is a god damn Unity bug again. I already had to work with one of those I found before.

#

Let it be my stupidity or something else

bleak abyss
#

anyone plz help

rocky helm
bleak abyss
#

which instructions

rocky helm
#

!vscode

tawny elkBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

rocky helm
#

wait what

#

!vs

tawny elkBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

โ€ข Visual Studio (Installed via Unity Hub)
โ€ข Visual Studio (Installed manually)

rocky helm
#

I don't remember which of these, if these are correct aaaa

bleak abyss
#

do you know what the error is?

rocky helm
rocky helm
bleak abyss
rocky helm
bleak abyss
#

ok thanks

brittle haven
#

In the foreach loop, I need to return a string for a string variable inside the class I created. What should I add to foreach (string s in thisLevel.AllObjects[number].objectname)

leaden ice
#

Do you mean return or just that you want to iterate over them?

#

e.g.

foreach (var obj in thisLevel.AllObjects) {
  string name = obj.objectname;
}``` ??
brittle haven
#

'objectname' is a class and it has a string in it. I want to return a string for the string inside it in foreach loop

modern creek
#

I have a 100x100 flat-top hex tile, and when I create and use a tilemap with the default swizzle (YXZ) it looks correct, but changing it to XYZ breaks it. I'd like to use XYZ because it makes more sense to my programmer brain. Any idea what I'm doing wrong? Do I need my assets to be "pointy top" even though they're flat top when swizzled to XYZ?

lapis ruin
#

Currently I have a whole Rigidbody based first person movement system, and the only problem with it is that it struggles to go up any drastic change in height such as a stair. To counter this, I want to make the player sort of always keep a .5 unit offset from the closest ground to their feet (so floating, pretty much) with the use of a Raycast detecting the ground below them. The way to do this would be to continuously change the Y of the player from the Y of the point of raycast collision plus that .5 unit offset mentioned previously by changing the player's transform. So I did this, it works fine. But is there any way I can fix the jittering?

lucid valley
#

are you trying to add them all together?

#

or do you only need one of them?

leaden ice
#

simply access the thing you want to access with .whateverTheVariableNameIs

brittle haven
#

foreach (string s in thisLevel.AllObjects[number].objectname)
I want to return a string in [System.Serializable] public class ObjectName { public string objectNameName; public float delay; } for 'objectNameName' here

somber nacelle
#

is objectname a variable of type ObjectName

brittle haven
#

AllObjects has ObjectName inside

lucid wigeon
#

[SerializeField] InventoryItem? selected;
Are nullable types like this OK or not? I cant even assign NULL in the Editor. But I can via code. How else would you store such variable? selected = null; makes sense when nothing is selected...

somber nacelle
leaden ice
somber nacelle
#

but your loop should be ObjectName s in whatever, not string s

leaden ice
#

I don't know why you have such a ridiculously named class and variable but here we are

brittle haven
#

but objectname is list

sage latch
#

dont serialize it

leaden ice
sage latch
#

if you really need to, then instead have a bool that tracks if you have a selected item

somber nacelle
lucid wigeon
leaden ice
#

anyway if you have all these variables with different types and you want us to answer a question about them you'd have to actually show us the code that defines the variables otherwise we're just guessing

sage latch
lucid wigeon
sage latch
#

just the default value works fine

lucid wigeon
#

Ok

brittle haven
somber nacelle
lucid wigeon
#

I suppose I could make a default item like "hand" in my case, and check for item.type == hand instead of item == null

lucid wigeon
sage latch
#

Feels over-complicated, a nullable field works fine with just a bit of extra work

brittle haven
# somber nacelle you've not really described your problem in a way that seems clear. you also are...
[System.Serializable]
public class LevelSettings
{
    public string LevelName, LevelAuthor;
    public float MusicBpm, IntroTime;
    public int LevelDifficulty;
    public List<Object> AllObjects;
}
[System.Serializable]
public class ObjectName
{
    public string objectNameName;
    public float delay;
}
[System.Serializable]
public class Object
{
    public float time;
    public ObjectSettings objectSettings = new();
    public List<ObjectName> objectname = new();
    public Add add = new();
    public Vector3Change vector3Change = new();
}```
thislevel is a LevelSettings
```cs
foreach (string s in thisLevel.AllObjects[number].objectname)```
how can i fix this
#

objectname was a string but now it's a class

sage latch
#

Also easy to mess up. Accidentally set an item's type to hand? Now everything about that item is broken and you have a hard issue to debug

#

And its not obvious what "hand" means. You could name it None or something but that might be mistaken for a generic item without a category

somber nacelle
#

then, as has already been pointed out, you can access one of the ObjectName's public members using the . operator

brittle haven
knotty sun
#
foreach (ObjectName objName in thisLevel.AllObjects[number].objectname) string s = objName.objectNameName;
hollow hound
#

Why objects have different behaviour dependent of the SerializedField and how to "fix" this?
Simple example:

Component on the prefab in prefab explorer

public class MyPrefab : MonoBehaviour
{
  [SerializeField] List<int> _nums = new();

  public void Add()
  {
    _nums.Add(1);
  }

  public void Log()
  {
    Debug.Log(_nums.Count);
  }
}

Component on the object at the scene

public class Spawner : MonoBehaviour
{
  [SerializeField] MyPrefab _prefab;
  MyPrefab _prefabInstance;

  void Start()
  {
    _prefabInstance = Instantiate(_prefab, transform);
    _prefabInstance.Add();
  }

  void Update()
  {
    if (!Input.GetKeyDown(KeyCode.Q)) return;

    var secondPrefab = Instantiate(_prefabInstance, transform);
    secondPrefab.Log();
  }
}

If _nums is SerializeField, I'm getting 1 after pressing Q. If it isn't, I'm getting 0.
Why?
Seems like SerializeField shouldn't change the behaviour that way.
The result is also 1 if _nums is public or [HideInInspector] public. But it's 0 if _nums is private without SerializeField.

earnest gyro
#

Merging two custom Memory objects

leaden ice
#

that's one of the main points of serialization

somber nacelle
leaden ice
#

[NonSerialized] would prevent it from being serialized

#

if you wanted that

hollow hound
hollow hound
somber nacelle
#

and SerializeField

leaden ice
#

yeah mb forgot about SerializeField

hollow hound
lucid wigeon
#

Is private required? I thought that was the default

hexed geode
#

How do I let my players choose a file from their computer without using EditorUtility?

#

string path = EditorUtility.OpenFilePanel("Select image", "", "png");

leaden ice
somber nacelle
leaden ice
hexed geode
#

alright i'll look on the asset store

gritty hazel
#

Does anyone have high latency when running Microphone.Start() on Oculus?

hexed geode
somber nacelle
#

if you don't see any errors in the unity console after saving this then you need to regenerate project files

hexed geode
somber nacelle
#

in the external tools settings in preferences

#

might also need to restart visual studio after regenerating

jolly stratus
#

Can anyone here who uses photon pun2 public sever for testing tell me how much ping they were getting? I am in one of the server countries and I am getting like 200ms, is it always this bad in public and gets better when you buy premium or what?

#

Well okay, if anyone answers me, please tag so I can see it later

wild bane
#

Guys. I'm trying to save a few assets created at runtime, and link them to a GameObject as a prefab, but every time I exit the play mode and place the prefab at my scene, all references are broken. This is the code I'm using:

        [MenuItem("ACKNEX/Generate Lightmap")]
        private static void GenerateLightmap()
        {
            var meshFilters = new List<MeshFilter>();
            foreach (var group in World.Instance.AllWallsByName)
            {
                foreach (var wall in group.Value)
                {
                    meshFilters.Add(wall.WallMeshFilter);
                    meshFilters.Add(wall.GapMeshFilter);
                }
            }
            foreach (var group in World.Instance.AllRegionsByName)
            {
                foreach (var region in group.Value)
                {
                    meshFilters.Add(region.CeilMeshFilter);
                    meshFilters.Add(region.FloorMeshFilter);
                }
            }
            var prefab = new GameObject("Prefab");
            prefab.hideFlags = HideFlags.DontUnloadUnusedAsset;
            for (var i = 0; i < meshFilters.Count; i++)
            {
                var meshFilter = meshFilters[i];
                var newGameObject = Instantiate(meshFilter.gameObject);
                newGameObject.transform.SetParent(prefab.transform, true);
                meshFilters[i] = newGameObject.GetComponent<MeshFilter>();
            }
            for (var i = 0; i < meshFilters.Count; i++)
            {
                var meshFilter = meshFilters[i];
                if (meshFilter.mesh.vertexCount == 0 || meshFilter.mesh.triangles == null || meshFilter.mesh.triangles.Length == 0)
                {
                    continue;
                }
                // some geometry is made up of quads, this is needed to unwrap them
                var triangles = new List<int>();
                for (var j = 0; j < meshFilter.mesh.subMeshCount; j++)
                {
                    meshFilter.mesh.GetTriangles(triangles, j);
                    meshFilter.mesh.SetTriangles(triangles, j);
                }
                if (!Unwrapping.GenerateSecondaryUVSet(
                        meshFilter.mesh, new UnwrapParam()
                        {
                            hardAngle = 88f,
                            angleError = 8f / 75f,
                            areaError = 15f / 75f,
                            packMargin = (float)Padding / (float)Resolution
                        }
                    ))
                {
                    Debug.Log(meshFilter.gameObject.name + " failed");
                }
                meshFilter.gameObject.isStatic = true;
            }
            AssetDatabase.StartAssetEditing();
            foreach (var obj in World.Instance.CreatedObjects)
            {
                string ext = null;
                if (obj.GetType() == typeof(UnityEngine.Material))
                {
                    ext = "mat";
                }
                else if (obj.GetType() == typeof(UnityEngine.Texture2D))
                {
                    ext = "texture2D";
                } else if (obj.GetType() == typeof(UnityEngine.Texture2DArray))
                {
                    ext = "texture2D";
                }
                else if (obj.GetType() == typeof(UnityEngine.Mesh))
                {
                    ext = "mesh";
                }
                if (ext != null)
                {
                    AssetDatabase.CreateAsset(obj, $"Assets/Lightmap/{obj.GetInstanceID()}.{ext}");
                }
            }
            AssetDatabase.StopAssetEditing();
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            PrefabUtility.SaveAsPrefabAsset(prefab, "Assets/Lightmap/Prefab.prefab");
        }
#

Do I have to save the Prefab before the Assets, or am I doing something wrong?

naive swallow
#

Is there a decent way to get the viewport position of a UI element on an overlay canvas without needing to manually un-transform all the parents' positions?

slim gate
#
protected virtual void Start()
    {
        ...
        if (x) return;
        ...
    }

protected override void Start()
    {
        base.Start();
        
        Debug.Log("X")
    }

Probably a stupid question but just to make sure: Will the Debug.Log be called in the inheriting class if the base returns or no? I assume it will still be called

naive swallow
robust dome
#
Collider2D[] results = Physics2D.OverlapCircle(transform.position, circleCollider.radius, yourLayerMask);
Debug.Log(results.Length);

naive swallow
#

There isn't a form of this one that has a list of colliders as the third parameter

#

Took me an astonishingly long time to figure that out as well

#

I had to actually plug the code into VS and see what it suggested to realize it wasn't the same

robust dome
#

good catch

lean brook
#

how to reach a canvas' child object's position in script? i've tried plenty of things but none of them worked.

void sundial
#

Has anyone here experience with mlagent scripting?

#

If so do dm me.

robust dome
#

@lean brook GetChild(index) then GetComponent<RectTransform>()

rigid island
#

sounds ominous

rigid island
naive swallow
#

I am trying to draw a line renderer pointing from one UI element to a specific spot in the scene. This test version should be drawing a line from that gear button's pivot to some arbitrary position. I'm doing a ScreenToWorldPoint on the gear button's position and it's giving me that offset. It seems to be following a point a bit to the right of the button's pivot. What can I do to get the actual world space position of a UI element?

The canvas is a camera space overlay (of an overlay camera) and scales to screen size. I've tried eliminating the overlay camera from the equation by using it to get screen point to viewport, then viewport to world on the real camera. No dice, same offset.

naive swallow
#

At the right size it does point to the spot I want, but not at any other zoom

naive swallow
#

I am disgusted looking at this line and I hate myself but it works. Such is programming

lean brook
leaden ice
river kelp
#

Are there any good books that go a bit more in-depth into netcode for gameobjects architecture?

#

I was hoping for something that went a bit more in-depth about your options than the basic youtube videos I've found

#

Or, a book that taught you useful patterns for multiplayer games where you feel the knowledge is applicable to network for game objects would be cool too.

steady moat
# river kelp Are there any good books that go a bit more in-depth into netcode for gameobject...

Netcode for GameObjects have decent example and some conceptual knowledge. You could start there.
Otherwise, your option is to either look into youtube tutorial for Netcode for GameObjects, or too look for a book for multiplayer solution, not necessary with Netcode for GameObjects/Unity.

https://docs-multiplayer.unity3d.com/netcode/current/learn/ticks-and-update-rates/
https://docs-multiplayer.unity3d.com/netcode/current/learn/bossroom/bossroom/

Tutorial:
https://unitycodemonkey.com/video.php?v=7glCsF9fv3s

Books:
Mirror: https://www.amazon.ca/Unity-Multiplayer-Intermediate-Coding-Networking-ebook/dp/B0C3W6JJTZ
Photon: https://www.amazon.ca/Unity-Multiplayer-Games-Alan-Stagner-ebook/dp/B00HL2GOD2

river kelp
void basalt
steady moat
modern creek
#

why is the default cell swizzle for hexagon flat tops YXZ instead of XYZ? and why can't I get this to work? I have flat top assets, and I want a flat top grid with XYZ swizzling (ie, "no" swizzling).. but setting the swizzle of a hexagon flat top tilemap to XYZ rotates the tiles 90 degrees..

#

"flat top" hexagon with XYZ swizzling has the point on top

#

but point on top hexagon with XYZ swizzling ..... has the point on top

somber nacelle
#

this is a code channel

modern creek
#

Fine..

Why does

TileMap.SetTile(new(1,0,0), TileBase); 

of a hexagon flat top XYZ tilemap place the hexagon at 0,1 instead of 1,0?

somber nacelle
modern creek
#

Indeed.. and my question is.. for a Hexagonal Flat top tilemap - why is the default swizzle YXZ? the tile on top of the origin tile should be 0,1,0 - otherwise I have to mirror literally everything else in the Unity ecosystem to find the tile I care about - mouse position, world position, etc

#

Or in other words - How can I create a flat tile hexagon tilemap with XYZ swizzling - since my attempt at doing so yields this:

somber nacelle
#

why don't you go ask in #๐Ÿ–ผ๏ธโ”ƒ2d-tools where this question belongs? i'm sure the folks that hang out there might have more info about how the 2d tools, including tilemaps work.

mystic ferry
#

I'm using DrawLine to...well, draw lines in a grid system I'm working on, but the lines are extremely thin and even disappear at times when I move the camera. Is there a way to prevent this?

dusk apex
#

Gizmo or LineRenderer?

mystic ferry
#

gizmo

dusk apex
#

They shouldn't disappear if you're still drawing them UnityChanThink Maybe provide code relative to the unwanted behavior.

heady iris
#

gizmos are editor-only

#

the lines are incredibly thin because they're intended exclusively for use as a visualization aid in the editor

sleek bough
#

you can turn on gizmo view in game window in editor, also make sure you've set time to display them, otherwise they will disappear instantly

mystic ferry
mystic ferry
#
public BuildGrid(int length, int height, float cellSize, Vector2 gridOffset = default(Vector2))
    {
        this._length = length;
        this._height = height;
        this._cellSize = cellSize;

        GameObject _parent = new GameObject("GridParent");

        _grid = new int[length, height];
        _textArray = new TextMesh[length, height];

        for (int x = 0; x < _grid.GetLength(0); x++)
        {
            for (int y = 0; y < _grid.GetLength(1); y++)
            {
                _textArray[x, y] = GridUtilities.CreateWorldText(_grid[x, y].ToString(), _parent.transform, GetWorldPosition(x, y) 
                    + new Vector2(cellSize, cellSize) * 0.5f + gridOffset, 10, Color.white, TextAnchor.MiddleCenter); //grid values
                
                Debug.DrawLine(GetWorldPosition(x, y) + gridOffset, GetWorldPosition(x, y + 1) + gridOffset, Color.white, 100); // bottom left upward
                Debug.DrawLine(GetWorldPosition(x, y) + gridOffset, GetWorldPosition(x + 1, y) + gridOffset, Color.white, 100); // bottom left rightward
            }
        }
        Debug.DrawLine(GetWorldPosition(0, height) + gridOffset, GetWorldPosition(length, height) + gridOffset, Color.white, 100); //top horizontal 
        Debug.DrawLine(GetWorldPosition(length, 0) + gridOffset, GetWorldPosition(length, height) + gridOffset, Color.white, 100); //right vertical
        ```
#

an example

quartz folio
#

But also, why does it matter, it's a debug line, it's not gonna end up in the final product

mystic ferry
#

I guess it doesn't but it's bothersome eitherway, I just figured I'd ask if there was a solution I missed

#

and it turns out I was right, I wasn't zoomed at 1x

#

I just like when my tools look pretty is that too much to ask ๐Ÿ˜”

idle flare
void basalt
upper pilot
#

How can I use enum on a button onclick function?

#

It works with SO, but not with enums.

#

I want to pass enum as an argument to the function.

cosmic rain
upper pilot
#

yeah but I have to remember what each int is.

lean sail
#

something like

    void Start()
    {
        button.onClick.AddListener(() => TakesAnEnum(TestEnum.a));
    }

    public void TakesAnEnum(TestEnum someEnum) {}

Unless you're dynamically spawning buttons, this should be sufficient

floral geyser
#

I've had this issue twice in my project now, in two different scenes, and I can't figure out why it's happening:

#

When I disable, then enable a UI element during runtime, it becomes unclickable.

#

Does anybody have any clue why?

#

It's clickable before it's disabled

#

It seems to be that disabling it is what causes the problem, because if it starts disabled, then becomes active, then it is clickable

#

But if it is active, then is disabled, then becomes active again, then it's unclickable

upper pilot
lean sail
#

sounds like an extra layer for no reason tbh, unless you REALLLY want to set this up in inspector

cosmic rain
upper pilot
#

I set them up manually.

#

In theory I could have an SO to store all possible upgrades, but that would still use enum or something similar since it upgrades different things such as Units/buildings/player

#

But it uses same UI.

cosmic rain
#

I never use the button component for global notifications or passing any kind of custom data. It should always invoke a method on a custom component on the same object that would take care of the actual logic.

lean sail
#

i generally prefer to setup buttons via some script, to keep them more in 1 place and because unity events are limited/hard to kinda go through your whole canvas to see whats linked.

upper pilot
#

yes I have UpgradeManager and the idea was to pass an enum so the manager could do the logic.

lean sail
upper pilot
#

don't you need to create all buttons through code then?

#

Or do you mean to get reference to all buttons and set listeners that way?

lean sail
#

U just get the reference and add a listener

cosmic rain
upper pilot
#

yeah so what I need to do is when u click a button it doesnt upgrade anything, but update another UI with actual info.
That UI will have actual listener that "Upgrades" when you click another button.
So there is an extra step there.
Not sure if that matters tho.

cosmic rain
#

My position is that unity buttons should only handle the act of clicking it and not bear any additional context.

upper pilot
#

What do you mean by additional context?

cosmic rain
#

Like your enums

upper pilot
#

The button needs to have some sort of data right?

cosmic rain
#

No

upper pilot
#

Otherwise how is your script going to see the difference between buttons?

cosmic rain
#

It should only notify that something is clicked. No more, no less.

upper pilot
#

What is "something"?

lean sail
cosmic rain
cosmic rain
lean sail
#
// assign upgrade 1 and upgrade 2 in inspector
    void Start()
    {
        upgrade1.onClick.AddListener(() => TakesAnEnum(TestEnum.a));
        upgrade2.onClick.AddListener(() => TakesAnEnum(TestEnum.b));
    }

    public void TakesAnEnum(TestEnum someEnum) {}
upper pilot
#

So the UI element is storing data? I am confused, what is the difference then?

#

Yes so the above is basically the same, but done via code

#

it is still storing data on a button, but you cant see it in the inspector.

cosmic rain
upper pilot
#

right

lean sail
upper pilot
#

So is it any different to having a regular onClick event on a button and adding a Scriptable Object as an argument?

#

Or does it have to be done via code?

floral geyser
upper pilot
#

I know this was about enums, but in general is this bad practice to have any sort of arguments in onclick event on a button?(in the inspector)

lean sail
#

you could do it anyway you wanted. but in the version ive shown, its just referencing a button and adding a listener which is all done in 1 script. yours would involve making a unique SO for every different button

cosmic rain
upper pilot
#

Alright, I will see into it tomorrow when I get back to this.

#

I do feel like having any logic on my canvas is a pain to handle and I barely started with it ๐Ÿ˜„

lean sail
upper pilot
#

since I jump around between my script that handles logic and UI.

cosmic rain
floral geyser
#

Nothing at all, I made sure to test without any other images or overlays, just the buttons themselves

upper pilot
#

Do you tend to have 1 Game manager that stores all SO data + make copies of it?
When I want to upgrade an Unit I have an UnitSO(asset file/not copy) which then I can use to compare in a List unitList.Get(unitSO).damage += 5
What would be a good way to handle this type of thing?
Do I just use SO as a way to identify an object, but only change data on a class/not SO(even if its a copy)?

cosmic rain
void sundial
swift falcon
#

how can i give a FPS character arms as a sort of viewmodel? i legit have no idea where to start with this haha

cosmic rain
misty drum
#

how would i go about dispersing a various number of objects headed towards a single vector?

swift falcon
#

wdym dispersing

misty drum
#

so that they dotn stack like this

swift falcon
#

i am not sure i understand the problem. they are all heading to a single point and yes they will eventually converge

misty drum
#

ive tried a few ways and they all look uggo

#

ik, i want them to head to a general location, but the more head to the same spot, the less accurate they are to that exact point

lean sail
upper pilot
cosmic rain
swift falcon
#

then add a random amount to each target point

misty drum
#

boids?

swift falcon
#

so each one goes a slightly different location in the same general area

upper pilot
swift falcon
cosmic rain
lean sail
mystic kiln
#

How would i go about initialising a list, which stores an array of values which arent all the same datatype e.g. the list may look like this

[ [Vector2, Vector2, float, float] , [Vector2, Vector2, float, float] ]

upper pilot
soft shard
# mystic kiln How would i go about initialising a list, which stores an array of values which ...

You could use a List<object> but then youd have to know the order of your types and cast it to access the data, other options could be a Dictionary if you have unique keys, or a List<SomeClass> or List<ISomeInterface> where you could use a base class or interface for each type to derive from, or possibly ScriptableObjects though some (or possibly all) of these approaches might only make sense in specific cases, what exactly is your usecase where you need 1 list to hold multiple types?

cosmic rain
misty drum
mystic kiln
mystic kiln
hushed notch
#

You should define Node objects with the stats you want

#

Then it's just a List<CustomNode> etc

#

You probably understand Object Oriented more than you think, at least in this case with just properties and no methods, it's creating a custom object that has those properties and so you can reference them instead of having an unnamed array

mystic kiln
misty drum
#

you create a class that stores specific variables. then when you make a list of thsi class, each list index can call all the variable sins aid class. so you could so something like

public List<ListTypes> ListyMcListyList;
public void Update()
{
  float x = ListyMcListyList(1).FirstFloat;
}
hushed notch
soft shard
mystic kiln
misty drum
#

youre makign a class into a pseudo "superVariable" that can contain any number of variable,s or even functions

mystic kiln
misty drum
#

its sort of the same thing for classes, im not an expert, someoen else cna explain better, but it allows the class using your variable class to actually see it, and in your inspector int he editor it allows you to intrerract with it

#

you can also put custom methods and stuff in there like its own class

soft shard
#

The attribute [System.Serializable] will let that class become serialized, so yes a bonus is it can be seen and drawn by the inspector (though only public types in that class the inspector supports, without editor scripting), and also means it can be saved by JSON or any other serialization method as well, its a good way to think about your data, most of the time, classes that use System.Serializable dont derive from anything, or derive from a class that doesnt derive from anything, so its good for pure data in most cases

misty drum
#
public class ListTypes
{
    public Vector2 FirstVector;
    public Vector2 SecondVector;
    public float FirstFloat;
    public float SecondFloat;

    public void FirstMethod()
    {
        FirstFloat = 69420f;
        Debug.Log(FirstFloat);
    }
}

public class ExampleClass : MonoBehavior
{
    public List<ListTypes> ListyMcListyList;
    public void Update()
    {
        ListyMcListyList(1).FirstMethod();
    }
}
#

basicly, youre making a list of a specific class, and that class is used as a glorified variable or method store-r

mystic kiln
#

right thats pretty cool

misty drum
#

that stored class cna do anythign a regular class can

mystic kiln
#

although any idea why its erroring?

misty drum
#

[System.Serializable]

#

use this

#

my bad

mystic kiln
#

oh okay thanks

mystic kiln
#

im not super good with c# i learned programming with lua...

misty drum
#

i leanred programming by understanding how google spreadsheet functions worked, so, to each their own

hushed notch
#

in terms of structure and general guidelines for first time devs; are there any major pitfalls to avoid? I've heard a lot about singleton's; what's the alternative? INstantiating certain things with constructors? Or does everything find its dependencies, etc?

cosmic rain
#

I really recommend going over C# basics. You're not gonna get far without knowing object oriented programming, since C# is object oriented language.

night harness
hushed notch
#

Dealing with nodes is actually probably a really good way to start understanding Object Oriented Programming; can you think of some helpful things those nodes can do themselves, if you really needed to?

misty drum
#

In my Part 1 of my "C# beginner tutorial series" for #Unity will show you the basics of day-to-day programming in Unity. This will include common variable types, setting up scripts, common methods formally known as functions in JavaScript. This will help beginners get to grips with the future of C# programming in Unity!

ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท...

โ–ถ Play video
cosmic rain
hushed notch
#

I'm intermediate; done a ton of Leetcode / Project Euler but haven' tmade a game, familiar with Python, javascript, Java, some C#

floral geyser
night harness
#

My GameManager has storied refs to all my other managers and such so just having my gamemanager as a singleton lets me get pretty much anything i need

mystic kiln
soft shard
# hushed notch in terms of structure and general guidelines for first time devs; are there any ...

If you have a general understanding of C#, I would suggest "Infallible Code" on YouTube, to help you get familiar with code architecture and design patterns, (I also found "Medium" blogs good references for some patterns you can use in Unity) - singletons have their purpose and there are cases where there are better alternatives, but it largely comes down to why your using a certain thing, and that may be largely affected by the architecture you decide to use in your project

misty drum
# cosmic rain Singletons are not bad, there's just good and bad use cases for them. The altern...

theres no such thing really as a giant pitfall, cuz everything has its uses. the main thing is just try to make it so its easy to understand whats happening in your code, if you use 10 if statements in a row for example, youre gonna confuse yourself. and learn to use less repetative code when really necessary, if youre seing yourself make a script for each unit type that does 90% of the things the same, theres room to minimalize somewhere

cosmic rain
misty drum
#

prob the biggest annoying bug you will find yourself onc ein a while is making infinite loops with code, usually dealign with while statements and coroutines, when it happens your editor might crash and some stuf fmight not be saved, can be annoying

hushed notch
#

Yeah I figure the question was sort of "how long is a piece of string" in that it sort of depends

mystic kiln
hushed notch
#

I guess I'll try to make a game and figure out what went wrong after ๐Ÿ˜†

cosmic rain
misty drum
#

its eaiser to give peopel tips than to tell them what to avoid tbh

mystic kiln
soft shard
# hushed notch I guess I'll try to make a game and figure out what went wrong after ๐Ÿ˜†

I think thats actually a pretty good way to learn, if your more of a hands-on learner and learn better from experience, and not just reading/watching stuff and assuming its all accurate, I like to make "sandbox" projects to just isolate and test out ideas and game mechanics, AI, algorithms etc, and super small game-jam-sized projects to find where I ask myself "theres gotta be a better way to do this..." or where I get confused in my own logic, then I know what I likely should study (and usually make a "sandbox" for, to learn it)

hushed notch
#

Yeah i'm trying to return to some roots of a project I did in college in java; I had a 2D planetary gravity simulator that I could fly a ship around. Didn't even know Kerbal existed lol

#

But I like gravitational physics, I think I'm going to try to do some super mario galaxy esque space walking mechanics

misty drum
#

if you liek to learn vicariously, i would recommend finding youtube series where they show you how to make a specific small game, and follow allong with your own project doing the exact same thing, watching somethign vs doing the same thign while you watch it is exponentially more helpful long run

#

theres a whole onlien course series based on this idea if yourw willing to pay some money lol

soft shard
#

One thing I found with watching videos, its a big help to actually NOT copy the code verbatim, and change things up, change the variable names, the values, maybe how you prefer to structure code (if they have everything in Update, maybe you like putting it all in different functions, if they use if-else, maybe you like switch-case, etc), I find you learn more and most importantly understand why they chose to write the words they did in the specific way they did, and see if there are other ways to do the exact same thing, then the question might become "why are there multiple ways? Which one is better? Whats the pros and cons of each? And is it a micro difference I should care about right now?", at least from my experience watching tutorials

hushed notch
#

I've just started instantiating ragdolls that I can drop into a big pile, so these are all good resources for when I get going, thanks

mystic kiln
misty drum
#

depends ont he use case

mystic kiln
#

id need to make a new "ListType"

hushed notch
#

customlist.add(customobject)

misty drum
#

you could copy, or instantiate, or make a new one

mystic kiln
#

i mean like to make the object how do i set the values of it

#

so in my case

misty drum
#

list.add(new ListType);

mystic kiln
#

would i need to do that seperately?

hushed notch
#

lookup constructors and the basics of OOP

misty drum
#

list(ListType).value

mystic kiln
misty drum
#

list(ListType).Variable = x;

hushed notch
#

I'm not sure if you're asking about how to manipulate the List or how to manipulate your CustomNode

mystic kiln
soft shard
night harness
#

Looking to set the BoxCollider.center of one component to another components values but its making my objects fly haha. I think I need to do some localposition converting? but im not sure what im missing

leaden solstice
elder flax
#

I have a big issue with my Text Mesh Pro text, basically it seems to not be working (completely invisible) when i build my game to Intel on Mac, but it does work when I build it to Intel+Silicon on Mac. Nothing in console is out of the ordinary, it can't load some dylib files but then it loads them later along the line. Additionally, some of the text appears to be unaffected.

gray mural
#

Hello, I have been struggling on it for quite a long now. How can it possibly be that SelectOption is printed twice when I click on the button? I call it like SelectOption(true) in Start method
void SaveCreateLevel
OptionSelectionField.cs

#

the strangest thing is that it's sometimes called once when I add a delay in start and call it in a few seconds

#

Ok, well, who knew that AddOptionSelectListeners(options) is called also in Start of OptionSelectField.cs. It adds a listener to all children, also adding it to the button that was created in Start method of another script. It is added multiple times when the gameObject with OptionSelectField script is set to active when I click on the button.

#

The most stupid issue,

visual pollen
#

Hey, was wondering if someone could point me in the right direction regarding something I am attempting to do. Such as a forum or key words to look up.

What I would like to do is generate a list of objects, eg OriginalList [1, 2, 3, 4, 5, 6, 7, 8, 9]

I then want to split this list up but not have any double ups, eg;
Player1 [1, 3, 4]
Player2 [2, 7, 9]
Player3 [5, 6, 8]

If anyone could help! That would be awesome, thanks!

gray mural
cosmic rain
#

Just loop the list and add the desired elements to other new lists.

visual pollen
#

Appreciate the help! Will try do that and get cracking with it, thank you

neat herald
#

I have a issue about modify meshInfo in the same frame in which TMP_Text is created. We can modify the meshInfo of the textInfo property of TextMeshProโ€™s TMP_Text to change properties like vertex colors of existing meshes. However, Iโ€™m currently facing an issue where if I place the creation of the TMP_Text and the code to modify the mesh within the same frame, the changes to the mesh get reverted. ```cs
Button button;
void Awake() {
button = GetComponent<Button>();
button.onClick.AddListener(CreateText);
}

void CreateText() {
    TMP_Text tmp = new GameObject("TMP_Text").AddComponent<TextMeshProUGUI>();
    tmp.transform.SetParent(FindObjectOfType<Canvas>().transform);
    tmp.SetText("This is a test sentence");

    tmp.ForceMeshUpdate();
    TMP_TextInfo textInfo = tmp.textInfo;
    TMP_MeshInfo[] meshInfos = tmp.textInfo.meshInfo;
    foreach (var info in meshInfos) {
        for (int index = 0; index < info.colors32.Length; index++) {
            info.colors32[index] = new Color32(255, 0, 0, 255);
        }
    }
    
    tmp.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32);
}```While debugging with breakpoints, Iโ€™ve confirmed that meshInfo.colors32 is indeed being modified. But as the execution continues, at some point, meshInfo.colors32 seems to revert back to its original state (the TextMeshPro codebase is quite extensive, and I donโ€™t have the capacity to identify the exact issue). My only assumption is that there might be a refresh operation on meshInfo at the end of the frame after the creation of TMP_Text, causing the reset.

Is there any way I can prevent this reset from happening or, in other words, what approach should I take to immediately modify meshInfo in the same frame in which TMP_Text is created?

#

If I modify the mesh in the frame immediately following the creation of the TextMeshProUGUI component, it will not be reset. However, writing it this way is a bit cumbersome and is causing me some trouble.

dense vessel
#

(But by the way isn't there a color property?
Why don't you do tmp.color = Color.red ?
But both ways work for me.)

neat herald
#

By the way, here I used modifying the color as an example, but modifying the meshInfo can achieve many impressive animation effects. However, for the sake of asking questions, I won't include such complex examples.

cosmic ermine
#

trying to do some marching squares, and for some reason my mesh just isn't rendering. Guessing I'm messing up my indices or vertices somehow. Is there a way I can debug view vertices or indices in a mesh?

main shuttle
main shuttle
#

Regarding the original question, I don't know. I probably would just DrawLine/DrawRay from your indices towards each other and see if they are what you think they are.
You could also put your Scene view in WireFrame mode and see if you did something wrong there probably.

cosmic ermine
#

Thanks!

gray mural
#

Does someone know why the same listener is added 4 times here? The bool unique is set to true when method is called.

// private List<UnityAction> _listeners = new();

public void AddListener(UnityAction call, bool unique = false)
{
    if (!unique || !_listeners.Contains(call))
    {
        if (!_button)
            _button = GetComponent<Button>();

        _button.onClick.AddListener(call);
        _listeners.Add(call);
    }
}
private void AddOptionSelectListener(OptionSelectButton option, bool unique = false)
{
    option.AddListener(() => InvokeOptionSelect(option), unique);
    option.AddListener(() => InvokeOptionSelect(option), unique);
    option.AddListener(() => InvokeOptionSelect(option), unique);
    option.AddListener(() => InvokeOptionSelect(option), unique);
    option.SetActive(false);
}
#

those UnityActions have to be the same, but _listeners.Contains(call) is false

cosmic rain
#

Anonymous methods are all unique instances. They're not gonna be equal.

gray mural
cosmic rain
#

Pass in a normal method instead.

#

But it really feels like you're over engineering something.

gray mural
#

what does it mean?

cosmic rain
gray mural
#

I don't think it's possible..

simple egret
#

If these events are not meant to be linked from the Inspector, use pure C# events instead. Allows more control since you can specify the return type and arguments

gray mural
#

I will try, thank you both

cosmic rain
#

Ok, maybe not. But it still feels like you're doing something forcefully wrong.

#

Maybe explain what you're trying to do and we might provide a better solution?

heady bronze
cosmic rain
heady bronze
heady bronze
#

Seems like its caused by a Capsule Collider in one of the children... Weird, I'm not sure why that'd be.

regal gyro
#

I wanna make the bool to false when the raycast is not hitting an object with a tag "Chest" but it seems that when it hits one, it stays to true while the raycast is no longer hitting the object

if (Physics.Raycast(theRay, it RaycastHit hit, range))
{
       if (hit.collider.tag == "Chest)
{
       colHit = true;
}
else
{
       colHit = false;
}
}
#

oh god editing this in mobile is a pain in the ars

dense vessel
regal gyro
#

that's what I did though

dense vessel
# regal gyro that's what I did though

No I mean like that :

if (Physics.Raycast(theRay, out RaycastHit hit, range))
{
  if (hit.collider.tag == "Chest")
  {
    colHit = true;
  }
  else
  {
    colHit = false;
  }
}
else colHit = false;
regal gyro
#

oh!

spring flame
#

I come back to unity after a long break and I got a bit rusty :P
How do I make a function that assigns variables to my component when I add a script to a game object or when it recompiles*?

wicked cape
#

how i can get which button clicked from list of button in unity through button.onclick event

spring flame
#

why do you need to check what button was it?

brazen garden
#

@wicked cape could u pass it through as an argument (Button this) from the button?

wicked cape
#

its always print last variable

fervent furnace
#

maybe you can try

for(int i=0;xxx;xxx){
  int j=i;
  buttons[i].onXXX.adXXX(()=>Method(j));
}
wicked cape
#

or what you want to say

dusk apex
#

Show your code

wicked cape
dusk apex
#

How to post !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.

fervent furnace
#

this is not the same as me.....

wicked cape
#

sorry for that

fervent furnace
#

your code likes:

int j;
for(int i=0;XXXXX){
  j=i;
  btn.onXXXXXXXX.adXXX(()=>Method(j));
}
dusk apex
#

So the lambda only caches the final result of the class variable

#

Make a new local variable and assign it the reference. Use that variable in the lambda instead

simple egret
#

It's important that the copy variable is declared inside the loop for it to work correctly

#

Else it'll be the exact same as i

fervent furnace
#

idk why it works actually i d even know how c# compiler compile lambda experssion
(maybe it creates an object which stores the start address of il and the pointer to arguments)

simple egret
#

The body of the lambda is translated into a full method, stored in that same class so the captured variables as fields can be accessed

fervent furnace
#

thanks

rose basin
#

Hi, I'm doing a project in Unity in which I need to record a video with the webcam, and I wanted to check if the webcam is available or is being used by some other application, does anyone know if there is a way to do it? I've been searching the internet and can't find any way. Thanks ๐Ÿ™‚

rose basin
#

I just tried it and it always gives me false, but the laptop's webcam works. I don't know why ๐Ÿ˜ฆ

unreal sonnet
#

Hey guys how do you export the json files into the build of the game?

#

i have a saving system set up but it only works in the editor for some reason

dense vessel
unreal sonnet
#

oh!

#

this is how my save path looks right now

#

do i just change it to Application.persistentDataPath + "/" + folder + "/" + fileName + ".json";

simple egret
#

Please use Path.Combine() to join paths!!!

dense vessel
unreal sonnet
#

thanks!

#

how do you see where persistentdatapath actually points to?

glass ridge
#

where can i ask for mate

cunning kestrel
#

tinder?

dark cairn
#

Hi, I'm trying to change animation rigging components via script in visual studio, but it says that the library UnityEngine.Animations.Rigging doesnt work, maybe there is no assembly reference for the library, but there is one, i already regenerated projet files so that it got the new package libraries, but it still says the library is not working. Can anyone help me with this? Thanks

glass ridge
steady moat
tawny elkBOT
glass ridge
#

how i can creatte post ?

tired elk
glass ridge
#

ok

#

i know but post dont work in unity

simple egret
#

Questions about the Forums do not belong in a code channel.

#

Check that your title is not breaking any rules (check for rules post at the top).
If that still doesn't work, ask in #๐Ÿ’ปโ”ƒunity-talk

heady iris
#

I have some singleton objects with event members. Other objects in the scene want to add and remove themselves from the event when they're enabled and disabled.

This causes errors when I stop the game. The singletons are getting destroyed before the other objects, so they're throwing errors when they try to use the singleton instance.

Two things here:

  • I thought destruction only happened at the end of the frame. Do objects get destroyed instantly when a scene is unloading?
  • Is there anything I can do to make these singletons die last, or do I just need to check if the instance is null before attempting to use it?
#

It's mostly a moot point because the scene is getting thrown out anyway, and failing to unregister doesn't have any consequences

#

it's not like this is a static event

tired elk
heady iris
#

I was just surprised by the ordering

#

if you destroy something in Update, the actual destruction only happens after the end of the update loop

#

but I guess it's different here

tired elk
#

I suppose it somewhat work like awake does

#

A specific function is called on every loaded object

#

But you have no guarantee of order

heady iris
#

right, and since the destruction appears to happen immediately, that becomes a problem

#

I could just make the event static.

tired elk
#

You could consider reverting the responsibility here

heady iris
#

it just feels weird to do that when everything else about the singletons are non-static

tired elk
#

And make your singleton release all of its listeners in OnDestroy/OnDisable

#

OR

heady iris
#

The individual listeners will be getting destroyed throughout a gameplay session.

tired elk
#

Unsub your listeners in OnDisable, which should be called before the singleton is destroyed

heady iris
#

nope, OnDisable and OnDestroy go off on the singleton before the listener's OnDisable is getting called

#

(destroying an enabled monobehaviour runs OnDisable and OnDestroy in sequence)

tired elk
heady iris
#

i checked with some log messages

tired elk
#

IIRC, if it's not a static event, the subscription lives with the object that holds the event. So you could simply check if the instance is null.

#

If instance is not null, manually unsubscribe. If it is, it should be handled automatically.

heady iris
#

Right, that's what I'll do

#

I was just hoping I could avoid having to check if the singleton is valid every time

late lion
# heady iris I *could* just make the event static.

You could make a static wrapper of the event, that checks if the instance is destroyed:

private Action _myEvent;

public static event Action MyEvent
{
    add
    {
        if (Instance == null) return;
        _myEvent += value;
    }
    remove
    {
        if (Instance == null) return;
        _myEvent -= value;
    }
}
#

Or doesn't need to be static necessarily

heady iris
#

also, huh, I'm a little surprised by the error I'm getting

#

I was expecting to be told the object was destroyed

#

not that it's null

#

oh, right: my singleton class is trying to find the object in the scene

tired elk
heady iris
#
using UnityEngine;

public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
    private static T _instance;
    public static T Instance 
    {
        get
        {
            if (_instance == null)
            {
                _instance = FindAnyObjectByType<T>();
            }

            return _instance;
        }
    }
}
#

so it's calling FindAnyObjectByType<T>() again and failing

#

I still thought that returned a "dummy object" that threw errors when you tried to use it

#

i swear GetComponent did that for sure, but neither is doing that

late lion
heady iris
#

That's what's confusing me -- calling GetHashCode() or accessing any non-unity member throws the NRE

late lion
heady iris
tired elk
heady iris
#

also, I threw this into the if (_instance == null) block:

_instance?.What();

where What() just logs "WHAT?" to the console

#

it never runs

#

this implies that I never attempt to read the Instance property whilst _instance isn't literally null

#

oh

#

nvm that was because other code I wrote was throwing an exception before I could try to read it, haha

#

okay, yes, there is some instant where it's a destroyed object, not literally null

#

and then FindAnyObjectByType literally returns null

#

okay, so one idea here:

#

if the FindAnyObjectByType fails, don't do anything

#

everyone else can then happily unregister their events from the singleton's dead body ๐Ÿ˜ฌ

#

This could cause problems if I load a scene containing objects that want to use that singleton that doesn't exist in that scene

#

however, I would simply not make mistakes

#

๐Ÿ™‚

#

Works like a charm. I will be judged for my sins.

obtuse hemlock
#

hello, is there anyone here who could help me to generate a txt file with Windows (CRLF) and UTF-16 LE. I only managed to get UTF-16 LE working, but when it comes to the first requirement, my file keeps getting out as Macintosh (CR) for some reason.

This is my current code - https://sourceb.in/KkK8kDSZ3J

heady iris
#

silly thought, but what happens if you do "\r\n\n"

rocky helm
#

Holy mother of jesus what is a 'tuple literal expression'?

rigidbodyChanges.Add(new (Rigidbody, Vector3, Quaternion)(rb, relativeTo.position, relativeTo.rotation));
error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead.

rigidbodyChanges.Add((Rigidbody, Vector3, Quaternion)(rb, relativeTo.position, relativeTo.rotation));
error CS0119: 'Rigidbody' is a type, which is not valid in the given context

rigidbodyChanges.Add(new (Rigidbody rigidbody, Vector3 position, Quaternion rotation)(rb, relativeTo.position, relativeTo.rotation));
error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead

rigidbodyChanges.Add((Rigidbody rigidbody, Vector3 position, Quaternion rotation)(rb, relativeTo.position, relativeTo.rotation));
error CS8185: A declaration is not allowed in this context.

tired elk
#

(Rigidbody, Vector3, Quaternion) is a tuple

#

And you're trying to do new (Rigibody, Vector3, Quaternion)

rocky helm
rocky helm
#

I want a tuple

tired elk
#

I'm not even sure of what you're trying to do with this syntax

late lion
#

You don't need to specify the types beforehand:

rigidbodyChanges.Add((rb, relativeTo.position, relativeTo.rotation));
rocky helm
#

I want to add a tuple to a list

hushed notch
#

It's like an array but less flexible

#

typically it can be hashed and is not mutable, unlike an array

#

Useful because you can use a tuple as a key, or as part of a set, unlike a regular array

rocky helm
rain minnow
static matrix
#

I presume using a script such as this:

void Update()
    {
        if(Vector3.Distance(transform.position, Player.transform.position) >= 60)
        {
            GetComponent<MeshRenderer>().enabled = false;
        }
        else
        {
            GetComponent<MeshRenderer>().enabled = true;
        }
    }

(lots of objects using this)
will save perf more than not using it
like the lag caused by this script will be less than the lag of rendering

knotty sun
static matrix
#

good idea

#

I need to break the habit of using get so much
ive gotten a lot better at not using Find in update

knotty sun
#

GetComponent is fine in Start just not in Update

static matrix
#

yes exactly
im incrediably stupid I had even already got meshrenderer for a different part of the script

knotty sun
static matrix
#

ok cool

lean sail
static matrix
#

this will be more helpful than clipping planes bcause sometimes I need to render far geometry for immersion
but a lot of the far geometry in this area is covered so I can de-render some of it

static matrix
knotty sun
lean sail
deep path
#

yoo
does it make sense to use Symbolic Link at cmd
just to change the Cache directory from drive C to D ?

static matrix
knotty sun
hoary dune
knotty sun
static matrix
#

oh duh I can just dubtract

swift falcon
static matrix
#

is this in 2d?

#

because if its in 2d and you made the sprite you might have to rotate the sprite in whatever you made the sprite in

obtuse hemlock
static matrix
#

to try and optimize more, imma add a script that gives objects rigidbodies only when they collide
so they arent eating up process power

obtuse hemlock
heady iris
obtuse hemlock
#

if it helps, asked in another channel about plain c# and the guy said my code works outside unity

#

he said it can be something with the compiler

heady iris
#

how are you checking the result?

rocky helm
static matrix
#

thats.... a very good idea

obtuse hemlock
# heady iris how are you checking the result?

like this, plus this file represents a DB table, which I need to import using another app, my generated file returns a error, so I start to investigate and this format thing was the only difference I could find

heady iris
#

i'm not sure i'd trust Notepad's interpretation

#

can you send an example of a broken file?

obtuse hemlock
obtuse hemlock
#

wait a sec

#

may I send you a dm with it? or I can add it here?

heady iris
#

you can just drop it in here if it doesn't have anything sensitive in it

obtuse hemlock
#

no, it doesn't

#

wait a sec and thanks for your help

#

I'll remove your suggestion, I'll add one generated with my original code...

#

they're big

heady iris
#

I wonder if it's actually turning "\n" into "\r\n"

static matrix
#

is /r remove in regex?

obtuse hemlock
static matrix
#

yeah it was for you

obtuse hemlock
#

first time generating txt stuff with specific requirements

static matrix
#

bcause /n is line break and obviously you dont want "\n" everywhere so it might be trying to remove it but something is going wrong somewhere?

#

just a wild guess

heady iris
#

Your bad files contain the following hex sequences at the end of each line

#

0D 00 0D 00 0A 00

#

UTF-16 encoded \r\r\n

#

Your good files contain 0D 00 0A 00

#

that's \r\n

#

I wonder if using '\n' -- the character -- will make it behave differently

heady iris
obtuse hemlock
heady iris
#

no, specifically writing '\n' instead of "\n"

#

'a' is a single character

#

however, you can also just try joining with "\n"

#

since that appears to be becoming "\r\n"

heady iris
#

but I don't know where this magic change is happening...

obtuse hemlock
#

ok, I'll test it again

heady iris
#

oh, you know

#

this might also just be because a \r got left behind by the splitting

obtuse hemlock
#

my man, you're awesome hahah

#

it worked

heady iris
#

That sounds more plausible to me.

#

So the last entry would be something like

#

5000\r

#

then you add \r\n at the end and get \r\r\n

obtuse hemlock
#

you think only the last entry has the additional \r which made the format wrong?

#

only a curiosity anyway

heady iris
#

well yeah, because that's where the \r lives

#

at the end of the line

obtuse hemlock
#

hmm

heady iris
#

try doing .Trim() before splitting each line

obtuse hemlock
#

got it

#

nah, I prefer to stick with this functional version lol

#

unless you really wanna know this, in this case, it's least I can do considering your help

bleak thorn
gray mural
broken light
#

any one know why in my editor script i keep losing the reference to the object field when i lose focus on the gameobject

gray mural
broken light
#

in my editor script i have:

        [SerializeField]
        GameObject _prefab;

with this line of code in my OnInspectorGUI()

_prefab = EditorGUILayout.ObjectField(_prefab, typeof(GameObject), false) as GameObject;
gray mural
gray mural
steady moat
broken light
#

their example is using properties from the monobehaviour though

#

this particular reference is only in the editor script

steady moat
broken light
#

in the editor script

steady moat
#

Then when are you losing data ?

broken light
#

when i lose focus on the object in question

#

if i then click back to it the fields are blank

steady moat
#

It lives only when you inspect it.

broken light
#

ah i see

#

so i would have to put it in the monobehaviour for it to stay alive

broken light
#

thats frustrating

steady moat
broken light
#

since its editor tool only not scene objects

steady moat
#

There is other option

steady moat
broken light
#

i see, i'll look into it

#

i read about it but didnt opt to use it

gray mural
#

you can also use SerializedObject

broken light
#

i guess i could use a SO

#

ill try both see which one makes more sense

steady moat
#

If you want your information to persist through multiple session you would need a Scriptable Object

gray mural
#

Is there a method that is called when a field is changed in the script? Like OnValidate, but it is called when a field is changed in the inspector

#

or do I have to use custom properties and/or methods?

#

I see, I'ma just call the method after assigning fields I need

light rock
#

thats exactly what onvalidate does

proven epoch
#

Hi! I have worked with unity for a while but I am not an expert by any means.

How do you guys go about writing scripts and building tools for your game development that you can then use accross multiple projects (so you don't have to keep reinventing the wheel or copy paste code from other projects?)

light rock
#

c# properties, to be specific

#

if in the inspector, use OnValidate

gray mural
gray mural
#

it's just very uncomfortable.

#

making a property for every field..

light rock
#

you can use auto-propeties

#

public int x {get; set;}

#

and only implement the set; function

gray mural
light rock
#

i think theres a way. hang on

gray mural
#

yes, there is

#

by making generic class

light rock
#

well, anyway those are the ways that you can do it. in c# a property is basically a field with a way to run code whenever it changes