#archived-code-general

1 messages ยท Page 317 of 1

leaden ice
#

this isn't a code problem

simple ridge
#

Im writing this tool for the use of non-technical people. So I'd rather get these sort of things done automatically

#

This is for use as a university experiment, so the students who will be using this won't have a background in game dev or understand how the unity editor deals with docking windows.

I agree this seems like a silly thing to need to do, but for me its worth getting rid of as many potential issues as possible with this sort of thing

#

If its not possible then I know you can save and write specific layouts through code so I will do it that way, but just wanted to make sure I wasn't missing something in terms of accessing tab data from an already existing window.

steady oasis
#

how can i prevent this from happening?

basically i kept my gun too close to the camera and now it cuts itself and shows its inside.
pls ping me if u have an answer because i am going for lunch and will be seeing the replies after i come.

thanks,
MrcJoc

#

also idk where to post this problem i post in genrel

leaden ice
#

This is NOT a coding question

simple ridge
#

@leaden ice do you know if this remotely possible through script? if not then I will just do the other approach but I do mean this as a code based question for custom editor scripting.

simple ridge
#

Ah thanks, I had a look at this class for implementation but didn't see the list for desiredDockNextTo.

And yes, sorry I didn't realise there was a channel specific to editor extensions.

#

Ill use that in the future! Thanks ^-^

tired apex
#

I have conflict in the interface , I can't make an alias for each library so how to resolve it ?

#

error CS0433: The type 'IAsyncEnumerable<T>' exists in both 'Microsoft.Bcl.AsyncInterfaces, Version=8.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' and 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'

cold parrot
tired apex
#

how syntaxally

gray mural
tired apex
#

before the interface ?

gray mural
#

Or remove one of the namespaces you don't need

tired apex
#

I can't remove it ( Its needed for other snipppets )

gray mural
tired apex
#

supprise

gray mural
tired apex
#

locally yes

gray mural
#

Well, you cannot use it, so you haven't

tired apex
#

also Nuget package manger acting weird !

tired apex
gray mural
#

Are you suge you have placed the dll correctly?

tired apex
#

yes

gray mural
#

Well, it doesn't work, so, probably, no

tired apex
#

as it cause conflicts I need to build custom dll library which cast it to the correct namespace -alias

gray mural
#

Have you gone thru this post on Stack Overflow?

tired apex
#

I extract all nuget manually because Nuget for unity cloudn't decide which version so I extract all nuget-s that target 2.1 api {and all its decencies } and it seems work just fine in unity

gray mural
wintry gust
#

The issue is this is for an individual audio source. Meaning I'd have to go around multiple points in my code and stop each individual audio source. I was hoping for a way to stop all audio sources globally.

gray mural
indigo orchid
#

hello I want to make an attack I have 2 meshes for it and want to do it such that when Q is pressed the attack mesh is switched to from the standing mesh pls help

swift falcon
#

I have some problem... So generally I know how to communicate the scipts, get the components bla bla. but the real is issue is that I'm not able to create a system that works properly and effectively. So I learned that I should check it out the scriptable object lesson in unity but also I'm curious is there something that u should suggest me to learn before this subject?

oblique spoke
leaden ice
#

Seems really vague

#

I'd make sure you really have mastered references and prefabs and lists and things first

indigo orchid
swift falcon
thin hollow
#

[requirecomponent ()] attribute forcefully adds the specified component to the game obgect if it is not present. Is it possible to instead make it so that you can't add this script to the game object if the required component is missing, and not create it automatically? I want the script in question only be able to be added to specific object types, not turn any object into object type the script is intended to be used with.
IIRC some native Unity script don't allow to add itself to object with missing component, so I want to replicate that behavior.

remote scarab
#

I changed the execution order for a script in order to make it init before others however after doing so now the project always stalls on start. The editor freezes and doesn't allow any input through the ui or even the close/minimise/restore/maximise buttons or moving the window itself. Unity's RAM usage keeps going up until it maxes out around 80-90% (making my total ram usage about 90-100%). Then just sits there and can only be closed through task manager.

I've tried reverting the execution order changes, changing the order to something else, updating Unity Hub, and restarting my computer. Other projects seem to run just fine, it's just this one. I've attached the current execution order (underlined one is the one that I have tried removing and is the one I added in). The execution order UI seems a bit bugged (or just isn't working how I expect) as sometimes when I hit apply it'll revert or change the order before applying.

#

Apologies if this is the wrong place to ask, I'm unsure where to ;-v-

fervent furnace
#

dead loop in your script

#

changing execution order solves nothing, you need to figure it out

remote scarab
#

changing execution order was to solve a different issue, I'll check any loops that this fix would make accessed now.

#

yeah, it seems to have been a faulty while loop. my bad there, thank you @fervent furnace

static matrix
#

erm
what is this
why is it doing this

serene bolt
#

Hello,
I have a problem with the Time.deltaTime.
I have a project which is a board game inside unity and i need to be able to clear the board when starting a new game. I'm using the Time.deltaTime to move the pawns and animate the movement and its working perfectly.
But once i've cleared the board (by deleting all childs and making it back, with the same functions i use when creating it), the Time.deltaTime used in the animations does not grow anymore ๐Ÿค”
I have no idea where it can be broken so pls help me ๐Ÿคฃ

Screenshots :
1 - the code to move the pawn, its called in a subroutine
2 - the subroutine call
3 - console output when its working (before clearing the board)
4 - console output when its broken (the deltatime is not increasing anymore ๐Ÿค” )

mellow sigil
#

I'm guessing at some point you set timeScale to zero

knotty sun
serene bolt
#

oh, its a group project and i never heard of that ๐Ÿ’€

#

looks like i'm gonna ask some questions to my teamates ๐Ÿ‘€

#

thx i'll check that

#

i don't know where it was set to 0, but i just put it back to 1 when creating the board and its working ๐Ÿ‘€

#

if something else is broken in the code i will think about it later ๐Ÿคฃ

#

Thank you very much ๐Ÿซถ

mental rover
#

find where it's been used and why

serene bolt
#

yes good idea

#

i found it and i know who i need to kill ๐Ÿ‘€ ๐Ÿ˜ˆ
(i'm joking i'm not gonna beat my friends)

light surge
#

Hello there. If I have a code that place, move and create a ton of object (World creation). What is the best way to reduce the waiting time and enable the loading bar to move (not 25s between frames). Jobs system, System.Threading or Inumerator?

fervent furnace
fast dune
#

How can I unzip a .zip file?

light surge
fast dune
#

within a script, how can i unzip a .zip into a directory

light surge
#

oh, ok. More clear now.

leaden ice
light surge
light surge
leaden ice
#

In a Coroutine for example

light surge
rocky jackal
#

why can this code detect if theres no , but it cant replace it

fervent furnace
#

string is immutable

#

so any method does nothing on the orignal string, they return you a new string

cursive kestrel
#

hello, anyone knows how to make a circular button ?
when i use a round sprite, you can still click it as if it was a rectangle

daring plover
#

hey
i have this VERY nested list with lists and stuff inside... how can i get to Currency Code and Currency Price by item name and category name?

my brain is fried

wintry crescent
waxen blade
#

I have a scriptable object that is unable to use the GetComponent method because it requires monobehaviour, but my object is currently inheriting Scriptable Object, so I can't add it on. I have another script inheriting this object as well.

I'm guessing I could create yet another class that inherits monobehaviour for yet another layer of monobehaviour, but is there a better approach to being able to utilize GetComponent?

daring plover
#

but i forgor about scriptatbel obejcts so ty for remining

wintry crescent
#

have a list for editing stuff in editor, and a runtime-only dictionary for referencing it from code

daring plover
#

also blow my mind failed

#

this data is remote

#

afair s.o. is local

#

sory if me stupido its 12 am

wintry crescent
daring plover
wintry crescent
daring plover
#

ok by serevr i mean plafyab

wintry crescent
# daring plover hwo do i dio this tho

you either loop through the nested lists every time you want to access an element, and compare the data in the list (like name) with the data you wanna grab
or you create a dictionary at runtime, using the data from the list

waxen blade
wintry crescent
waxen blade
wintry crescent
#

it's best to just pass it as a reference, really

waxen blade
#

I only associate one object per tag, and it's also not being ran in an update method. But in that case I'll try to avoid using that when I can.

wintry crescent
spring creek
#

What you're doing is equivalent to C tier.

gilded sapphire
#

Hey everyone, how can i use the object the raycast had a collision with (interactable) in a future update cycle to disable a component of that object? I have tried a lot of different things, but nothing seems to work

spring creek
brazen totem
#

i am trying to make my enemy shoot in a parabola curve , someone knows how?

#

nothing on google...

vagrant blade
#

Copied your question word for word.

gilded sapphire
spring creek
gilded sapphire
#

Ok thanks, i will search around a some more

spring creek
gilded sapphire
#

It works, but the outline isnt cooperating, just have to fiddle some more. Thanks for the help

clever harbor
#

Does anyone know if its possible to set the cursor to the hand? Like the default OS cursor when you hover over a button

#

Without manually setting my own cursor icon of course

rigid island
late lion
light surge
dim latch
#

How can i get the object size of a probuilder mesh filter? i notice there's a read only property in the editor which would be super useful info in a script but i'm not sure the property name or how to access it, the tooltip or any buzzwords don't show up in a search on the ProBuilderMesh script

#

This is the property for reference

mossy snow
#

that code's in a custom editor (ProBuilderMeshEditor). It's merely reading mesh renderer bounds.size

dim latch
old sigil
#

anyone here any good with splatmaps i got a question?

#

im trying to get my terrain to update in the size of a collider. basically my player stands in the collider hits f and the terrain in the collider should be updated with a new texture. I've been debugging and i can tell its going through the function in its whole and im grabbing the correct layer in my terrain textures but it's not updating the terrain.

#

its just a flat terrain for a 2.5D game so nothing crazy is going on with the terrain at all i just dont know what im really looking at lol

knotty sun
tawny elkBOT
old sigil
#

I do know that it passes in the correct collider

knotty sun
old sigil
#

so index 0 is grass index 1 is soil

knotty sun
#

also you only appear to be changing the texture for one single point

old sigil
#

like one pixel?

knotty sun
#

yes

old sigil
#

you are absolutely correct i just saw that

knotty sun
#

this

float[,,] splatmapData = terrainData.GetAlphamaps(mapX, mapY, 1, 1);

get one point of width and height at the specified position

old sigil
#

i see now, apologies this is like week 1 of ever touching a game engine lol any ideas on how i could expand that to cover the amount of terrain a collider is covering?

knotty sun
old sigil
#

thank you very much for the help i've been on the struggle bus with this for a while! terrain has been a very daunting aspect for me when it comes to scripting it.

knotty sun
winter frost
#

currently having issues figuring out how to preserve some player data when transitioning between scenes - is it common practice to store player data in some singleton game manager rather then the player, or call DontDestroyOnLoad on the player and just move them/disable them when transitioning to scenes?

upper pilot
#

Hey, Input Controller gives me a Verctor2 for 8dir movement which can be: [1, 1] or [1, -1] or [0.67, 067](for diagonal) etc.
Is there a way to clamp Randomly generated values to fit the above?
What systems people use? I want to have Npc walk in a random direction without having to type clamp(value, 067, 1); or something similar.

#

do I convert angle to direction instead and move npc in a random angle?

#
Vector2 direction = Quaternion.AngleAxis(angle, Vector3.forward) * Vector3.right;
#

I can get random angle by getting random number 0-7 and multiply by 45

late lion
upper pilot
#

That was an estimate, but ye

late lion
#

Sorry, I missed that it's limited to 8 directions.

upper pilot
#

Yeah I am testing above code, for some reason it doesnt work exactly the same as player movement.

#

But its close

late lion
#

With 8 limited directions, I would just pre-calculate the directions into a lookup table/array.

knotty sun
# upper pilot I mean this

why not just calculate the 8 direction vectors you want and hold them in an array, then randomly select one of the entries in the array?

upper pilot
#

Even if player movement uses input system for its direction?

knotty sun
#

sure

upper pilot
#

Alright, I guess that sounds like a plan then haha, I will give it a go

#

ok I see the issue with my code

#

x = 5.960464E-08
y = 0.9999999

#

Guess I will just make a dictionary of vectors so I can use Enum for a direction too in case I want to create a path for npc later.

reef creek
#

Hello everyone, I'm having an issue with Unity: I'm creating a card game and working on a deck from which players can draw their cards. However, every time I actually draw a card, this error appears in my console, and since it doesn't give me much information, I really don't know where to go. My code doesn't have any string of the TYPE type, and when I checked my code, everything seemed to be working fine.

#

I know I didnt show any parts of my code, but it is because I dont know if this is the exactly place to put it or if I should create a post

leaden ice
#

Read the full error message

#

And the stack trace

reef creek
#

Its because theres nothing specific there, the error message is simply:

type is not a supported string value
UnityEditor.RetainedMode:UpdateSchedulers ()

leaden ice
#

However it's clear that this is an editor issue just from that piece

reef creek
#

Does it mean the error is in the inspector?

leaden ice
#

Could be

#

Not necessarily

#

But part of the editor for sure

reef creek
#

๐Ÿ˜ฆ

leaden ice
#

What are you hoping to find and where are you looking? It's likely a Unity bug. Report and research it, and move on

reef creek
#

Should I just continue my work like nothing happened then?

leaden ice
#

I made my recommendation

dusk apex
reef creek
dusk apex
#

Are you able to determine which object the error is related to?

reef creek
dusk apex
#

Maybe you ought to show the code that moves the card from deck to hand.

reef creek
#

Should I create a post to do so?

dusk apex
#

Also, does this occur with nothing else in the scene but the two objects?

#

You wouldn't want to be investigating something unrelated to the problem - XY problem.

reef creek
#

Hmmm... Somehow I just closed the program and oppenend it again and now it seems fine again

#

Idk what happened, but Ill just report it and move on

static matrix
#

is there a way to do like list.indexof but for a 2d array?

#

might just switch to a dictionary

knotty sun
static matrix
#

alright

#

what is the purpose of this function?????

robust elk
#

How to make the grid follow the object direction, instead pf the world direction???

knotty sun
#

to get a value from a Dictionary based on a key. Returns true if found, false if not

static matrix
#

I mean yeah
but can't you just do if(Dictionary[Key])?

knotty sun
#

no. you can do if (dictionary.Contains(key)). but that does not return the value for the key if found

static matrix
#

ah

simple egret
#

Your version will throw an exception if the key is not present in the Dictionary

static matrix
#

sorry for being stupid

knotty sun
static matrix
#

really? hasn't done that for me

#

oh because I used containskey ๐Ÿ’€

#

im just dumb
disregard everything I say

simple egret
#

A d.ContainsKey() followed by a d[] can indeed be simplified down to a single d.TryGetValue() call

static matrix
#

nice

#

although I was using containskey just for the bool

knotty sun
#

and the TryGet gives you that bool

#

2 for the price of 1, what's not to like?

static matrix
#

oh lol I think I am about to use tryget like rn
thats crazy
I shan't have questioned the unparalleled intellect of people who write programming languages

maiden heath
#

!learn

tawny elkBOT
#

:teacher: Unity Learn โ†—

Over 750 hours of free live and on-demand learning content for all levels of experience!

knotty sun
simple egret
#

It's used here and there, eg. TryGetComponent<T>(), int.TryParse(), etc.

simple egret
#

Attempt to do X and return a value whether that succeeded, and if it does, get another value as an out param

unique delta
#

Is there a way to get a unity event from another script in animation? (The animation is on a game object that dosen t have the script), without using another script

leaden ice
#

Use all the normal means of referencing things.

unique delta
#

i mean to use it in another animation

leaden ice
#

"use it" how?

#

invoke it?

#

Add a listener?

unique delta
#

so at a time in the animation something happens

leaden ice
#

Use an animation event

unique delta
#

that s correct

leaden ice
#

As for how to communicate with another script that's just a basic question of getting a reference to it

waxen blade
#

I am passing input parameters to an abstract class' method. Another class that is overriding the method is receiving the input parameter. However, none of the properties of the input parameter are showing up in intellisense. How do I pass an object via abstract class?

public abstract class EnemyLogic : ScriptableObject
{
    public abstract void Finish(FooClass foo);
}
public class Enemy : EnemyLogic
{
  public override void Finish(FooClass foo)
  {
    foo.??? //(None of the public properties in FooClass are visible or accessible here)
  }
}
leaden ice
#

if intellisense isn't working it could be a sign that your IDE is not configured properly?

waxen blade
#

It says it doesn't contain any definitions if I do foo.PropertyNamehere, even though I know for a fact the property is there.

    public class FooClass
    {
        public int Digit { get; set; }
        public Vector2 ObjectPosition { get; set; }
        public float YOffSet { get; set; }
        public bool CurrentlyAttackable { get; set; }
        public string ObjectType { get; set; }
        public bool IsSpawnable { get; set; }
        public GameObject SpawnedObject { get; set; }
        public int Health { get; set; }
        public Vector2 HammerPosition { get; set; }
        public Vector2 CurrentObjectPosition { get; set; }
        public Vector2 CurrentDirtPosition { get; set; }
        public GameObject DroppedLoot {get; set;}
        public Vector2 DroppedLootPosition { get; set; }
        public Enemy EnemyData { get; set; }
        public Hazard HazardData { get; set; }
        public TreasureChest TreasureChestData { get; set; }
    }
leaden ice
#

Is your IDE configured?

waxen blade
#

Yes, I only have issues with intellisense in this abstract class.

leaden ice
#

Also do you have any other syntax/compile errors in the code?

leaden ice
#

I don't see any reason why IntelliSense shouldn't be picking these properties up

#

I doubt it's related to the abstract/override thing

#

Anyway at worst this is an IntelliSense problem. The code you wrote is correct.

knotty sun
#

is FooClass recognised? Missing namespace?

rigid island
#

regen project files ?

waxen blade
leaden ice
#

Are you getting an error?

waxen blade
#

I can't build my code.

leaden ice
#

Why not?

#

What happens when you try?

waxen blade
#

foo.Digit = 1

FooClass does not contain a defnition for "Digit" and no accessible extension method 'Digit' accepting a first argument of type 'FooClass' cloud lnot be found (are you missing a using directive or an assembly reference?)

leaden ice
#

If you right click FooClass and click "go to definition" or "go to declaration" where does it take you?

waxen blade
#

It takes me to the class.

leaden ice
waxen blade
#

Both.

#

I do see some thing in foo, but none of my properties.

leaden ice
#

I would guess some combination of:

  • More than one FooClass defined
  • Assembly definitions are involved
  • Namespaces are involved
naive swallow
tawny elkBOT
naive swallow
#

For specifically the file that pops up under "Go To Definition"

waxen blade
#

I think I know what the issue is. I had tunnel vision and missed the fact that FooClass has another class wrapped around it. I'll report back soon.

leaden ice
#

ah then yes you need WrapperClass.FooClass

waxen blade
#

But your guess would be on point if this is the issue.

#

Yes, that was my problem.

I didn't realize that the IDE was trying to help me by automatically adding the wrapper class as a static using statement at the top. So I didn't realize there was a problem since I expected it to work without the wrapper class name.

#

The IDE has been trying to help me with this the whole time but in the end I think it just made me develop a bad habit. Oh well, now I acknowledge what's going on so I know what to look out for.

#

Thanks for the help!

hearty mortar
#

So, when it comes to input maps, I've been thinking of creating a combined maps system, where I have say a "Movement" input map, and a "Weapon Sheathed" and "Weapon Unsheathed" input map, and activate multiple at the same time. I do see that this can't be done with the "Player Input" component, but I have more of a theoretical question: does it make sense to represent input map sets as a FSM? It seems like a fairly logical approach. Has anyone tried doing it that way, and does anyone know of any packages (ideally FOSS but if not, asset store) for it?

leaden ice
hearty mortar
#

But more work to implement code-side haha

#

Since you actually need to keep track of whether edges cross a layer boundary, rather than using a simple graph

#

Another question, from what I've been reading, Unity's "SendMessage" and "BroadcastMessage" functions aren't great. Do people usually just use hardwired events, or do you roll your own message bus?

leaden ice
#

We usually just call methods normally

#

When possible and practical

pastel patio
#

How do you guys handle save&load usually?

#

Mine is a sandbox game which means that there's uh... A Lot to save

gray mural
pastel patio
#

My question's bit more like, if there's for example an undefined amount of varied enemies that needs to be saved, how do people normally go about it?

leaden ice
pastel patio
gray mural
lean sail
#

The same way you store anything in an undefined amount, a list of these objects

leaden ice
#

If there's information that can be stably derived from a source other than the save, use that. For example if the game involves a procedurally generated map, often you can get away with just saving the map generation seed, rather than all the generated map data.

#

If it's modifiable later, e.g. Minecraft, you could just save the modifications, rather than the whole world of blocks, for example.

pastel patio
leaden ice
#

This is all hypothetical and really depends on the specifics of your game

leaden ice
pastel patio
#

Well, I've got a terrain manager storing all the data and stuff

#

But not in a manner just so easily saveable, I believe

tired apex
leaden ice
#

in any case though you need to serialize it and write it to a file

pastel patio
#

Uh, okay I'll just ask on commentaries of how I did things so far ig

#

Uh, might seem quite insane, but I've basically made a whole system centered on structs I named SavedObjects, they basically contain:

A prefab id
An instance id (Index at which they're registered)
An instance code (Security against a new object taking the index of a destroyed object being mistaken as the old one still existing)
A position
A rotation
An array of strings to store extra data

#

All SaveableObjects are backed with a SavedObject, and persistent references (To bypass the loaded object being unloaded) basically is 2 int with the instance id and the instance code

swift falcon
#

Hey guys, is it possible to toy around with Input System UI Input Module's settings?

#

programatically

#

I'd like to temporarily disable ui navigation but i am not very sure how to

pastel patio
#

Y'all see why I'm asking about how you save stuff now? I just wanna fact check if what I did isn't simply insanity ๐Ÿ˜‚

leaden ice
#

presumably the prefab id is so you know which prefab to instantiate

lean sail
leaden ice
#

presumably each individual script would know what to do with the "extra data"

#

e.g. a flower script might know which type of flower had bloomed based on it

#

but an array of strings is quite freeform

pastel patio
#

Basically I keep a list of SavedObjects in 1 place

#

And destroying one only makes that place marked as free space

leaden ice
#

I guess I don't see what value that has

#

Does the order actually matter?

pastel patio
pastel patio
leaden ice
#

I would use a HashSet

pastel patio
#

Literally

lean sail
#

Trying to make just 1 generic save struct for this probably wont work nicely for this. Also using structs here for such a large amount of data is probably worse than just using classes. Also consider that for the string array, you need to parse that data manually into what it is, which can basically be seen as storing json inside a json. I would really just make separate types for each thing that needs to be saved. If it derives from a single thing to ensure it implements the prefab ID then that's easy too

#

Structs should really just be used with small data

leaden ice
pastel patio
leaden ice
#

Like even if all the object IDs get shuffled when you load, that's not a problem right?

pastel patio
#

Even though the savedobject system essentially already stripped it down to what needs to be saved

pastel patio
#

Since I keep them structs where references are via an instance id

#

And why structs, you may ask?

#

Uhm, I don't think that I'd know how to severe all references to a savedObject once it's destroyed if it's a class

#

It's a monobehaviour thing

leaden ice
#

Let's say we have:
Red Block at position 4, id 100
Blue block at position 5, id 101
Green block at position 6, id 102

If I save this as a list:
[red 4, green 5, blue 6]

It doesn't matter what order that list is in right? As long as when I reload the game there's a red block and position 4, a green block at 6, and a blue block at 5 right?

#

And if the new red block's id is 200 instead of 100 that's not an issue right?

pastel patio
#

It has a problem, cus if blue block references red block via his id in the list

#

You can't legitamately reference a struct, unless if I'm wrong

leaden ice
#

I see, so your objects are actually using this id as a reference somewhere

pastel patio
#

Even if you can reference a struct, it'd likely become the same issue as using a class

#

Which basically is, if blue references red, but red gets destroyed, then blue keeps red alive via it's reference

leaden ice
#

list order, as you know, is quite annoying to deal with

#

you can convert to a list and save the id number with the object in the save file, but use a Dictionary at runtime

#

they are fast for adding and removing objects too

pastel patio
leaden ice
#

sort of like a malloc/free thing

pastel patio
#

Yeah

#

It just have the issue when something takes another's space and gets regarded as the older thing at that registry

latent latch
#

c# hashset and dictionary can be iterated over as it implements IEnumerable

leaden ice
pastel patio
#

I don't think there's any other choice than references being integers pointing to the index

leaden ice
# pastel patio How would you circumvent that kinda issue?

It kinda depends. There's several options and the best one depends on the specific circumstances. You could:

  • always make sure that any object referencing any other object gets notified if the thing it's referencing is destroyed, so it can forget about it
  • use tombstone objects which are basically never actually destroyed (e.g. just mark it as isDestroyed = true)
#

Your generic object struct here could implement an OnDestroyed event that referencers can/should subscribe to for the first option.

pastel patio
#

I don't exactly see how either of those can work, in fact, I thought about the first one buuut... It's not gonna work, wanna know why?

latent latch
#

I honestly prefer malloc over automatic* garbage collection as I prefer having errors to things for when I am supposed to have cleaned those up. I feel like it's harder to catch those dangling references otherwise

pastel patio
#

If the referencer gets unloaded first, so the reference becomes merely an integer in data, and then you destroy the one being referenced

latent latch
#

Heck, you do extra work in unity having to make sure you destroy scene objects too, so you're working over time when it comes to making sure you deload your stuff, haha

pastel patio
#

Well, to be honest me and Unity, in that project it's a bit of a love/hate situation

#

I have to fight unity often times, remaking systems on top of theirs to do what I want

#

Buuuuut not using Unity is gonna be very troublesome as well

pastel patio
#

Which is tbh pretty weird, cus in the end you'd nearly assume Unity's system actually has all I need, but maybe hidden away in the depth of the engine

#

Whelp, ig that I got something out of this, first, I'm not insane nor dumb to have made this system.

Second, the only alternative possible that I avoided is that all SavedObjects are classes, and subscribe to OnDestroy events.

#

In which case, there's currently 330000+ objects on the surface world, soooo.... 330000 classes each with an ondestroy event......?

lament gale
#

I am trying to dynamically make a "catalog" for the structures in my game. Ive so far instantiated all of the ui elements onto a panel and I want to change another variable depending on the button you press. My issue is that all of the buttons give me 15 instead of the current value of "i" inside of the for loop.
Any fix?

Thanks in advance

lament gale
#

Ill try this, thanks alot!!

rocky basalt
#

Can someone tell me how I should format the listener method to get rid of this error?

#

i'm bad with generics

somber nacelle
#

your OnGrabbed method does not accept a PointerEvent parameter like the delegate expects

rocky basalt
#

Damn, it was that simple. Thank you

#

I still often get thrown off and confused by stuff in angle brackets haha

somber nacelle
#

it's not even a matter of understanding generics, it's understanding that the UnityAction with a generic type parameter will be passing an object of that type to the methods subscribed

#

Just like System.Action UnityAction has generic and non-generic versions where the generic versions are basically exactly the same, except they pass one or more parameters

rocky basalt
#

Makes sense. Wish the error message dumbed it down a bit like "arguments requires a PointerEvent type"

rain minnow
#

It kinda does . . .

rocky basalt
#

yea, yeah ๐Ÿ˜‚

rain minnow
#

๐Ÿ˜„

slim gate
#

So, is this worth it in terms of performance or is there no difference at all:

public bool CanItemFitInInventory(ItemInstance itemInstance, int amount)
{
    // Yes if empty slot available
    foreach (var slot in ItemSlots) { if (slot.Amount <= 0) { return true; } }

    foreach (var slot in ItemSlots)
    {
        if (slot.Amount <= 0) continue;

        if (slot.ItemInstance.Item.Id == itemInstance.Item.Id && (slot.Amount + amount) <= itemInstance.Item.StackSize)
        {
            return true;
        }
    }

    return false;
}
 public bool CanItemFitInInventory(ItemInstance itemInstance, int amount)
 {
     // Yes if empty slot available
     if (ItemSlots.Any(slot => slot.Amount <= 0))
     {
         return true;
     }

     return ItemSlots.Where(slot => slot.Amount > 0).Any(slot => slot.ItemInstance.Item.Id == itemInstance.Item.Id && (slot.Amount + amount) <= itemInstance.Item.StackSize);
 }

I have no idea about LINQ-expressions and dont really understand them too much but my IDE is suggesting this change by itself. Its a method that potentially can get called very often if the player stands on a pile of items so performance would be important here. Not sure if there is any difference between these though? I assume that if the IDE can change these by itself then so would the compiler into the most efficient one.

mental rover
chilly surge
#

LINQ allocates, GC pauses might be a bigger concern.

stable quest
#

Hey folks -- I need a quick sanity check. This operation should do nothing, right? Do I have the order correct here?

newAverageRotation = newAverageRotation * Quaternion.Inverse(x);
newAverageRotation = newAverageRotation * x;

(newAverageRotation is a quaternion)

leaden ice
#

What you've got here is basically:

a = a - x;
a = a + x;```
stable quest
#

Thanks, that's what I thought. I can't imagine I'm running into precision issues, but maybe. Something funky is going on.

leaden ice
#

or just like

#

slightly off

#

I would expect you to have a small amount of error for basically any value here due to precision errors

stable quest
#

it's slightly off at first, but then it compounds a few times and gets ENORMOUSLY off very fast

leaden ice
#

how many times are you doing this calculation

#

like once per frame or something?

#

the errors could compound pretty quickly

stable quest
#

yeah this is an editor script, so once per scene update

leaden ice
#

Could you show the real code here? I imagine the real operation is some more complex thing

stable quest
#

sure, one sec

leaden ice
#

And maybe there's a better way to do this

#

For example - just storing the original rotation and restoring it afterwards

stable quest
#

so, this is the end result of a lot of debugging: basically, I'm trying to implement some rotation handles in this editor, but in order to do that with multi-select I need to get the difference in rotation and apply it to each selected "viewpoint." for simplicity I've worked out this, which is the simplest thing I can do that still creates the problem. for this example, I'm just applying the rotation to a single viewpoint to see if I can get that to work.

EditorGUI.BeginChangeCheck();
Quaternion newAverageRotation = Handles.RotationHandle(firstSelectedViewpoint.localRotation, averageSelectedPosition);

if (EditorGUI.EndChangeCheck()) {

    Quaternion rotationOffset            = newAverageRotation * Quaternion.Inverse(firstSelectedViewpoint.localRotation);
    firstSelectedViewpoint.localRotation = firstSelectedViewpoint.localRotation * rotationOffset;

    Debug.Log(firstSelectedViewpoint.localRotation);
}

If I set the rotation of the viewpoint to the handle output directly, it works fine

#

Here's the log output when I start rotating the handle in the editor:

#

obviously a quaternion shouldn't look like that!

#

@leaden ice pinging just to make sure you saw this

leaden ice
stable quest
leaden ice
#
Quaternion rotationOffset = newAverageRotation * Quaternion.Inverse(firstSelectedViewpoint.localRotation);```
leaden ice
#

nvm

#

it's not

stable quest
#

maybe i just have to handle this in a different way. storing vectors or something instead of quaternions. cause this is wild

leaden ice
leaden ice
#

what happens if you use world space rotations

#

instead of local

stable quest
#

yeah that is a good idea but these are actually worldspace

leaden ice
#

no parents?

stable quest
#

i just didn't want to rename my variable just for debugging haha. these aren't transforms, just a barebones class that holds a position and rotation

leaden ice
#
Quaternion rotationOffset = Quaternion.Inverse(firstSelectedViewpoint.localRotation) * newAverageRotation;```
#

order of operations does matter here

stable quest
#

I'll give that a shot

leaden ice
#

My napkin algebra gives them in that order:

newRot = fsv + diff
newRot - diff = fsv
-diff = fsv - newRot
diff = -fsv + newRot```
But I'm not sure if I did the algebra right given the non-commutability of + here
stable quest
#

huhhhh still broken.

#

Oh wait a second

#

okay if I do that AND normalize the diff that seems to work!

leaden ice
#

awesome!

stable quest
#

phew! Thanks so much!

hearty mortar
#

Do we need to manually integrate quantities in our code, or is there a way to piggyback off the integrator Unity uses for physics?

hearty mortar
#

E.g. applying gravity to a Character controller

leaden ice
#

The way the physics engine integrates is to just use a fixed timestep

#

No this is not completely physically accurate, and that's ok

hearty mortar
#

Yeah, but I assume the physics engine isn't doing explicit Euler the way the sample assets player script does it

leaden ice
#

it's pretty much just doing this every fixed timestep

velocity += Time.fixedDeltaTime * gravity;
position += Time.fixedDeltaTime * velocity;```
#

You can verify this yourself

hearty mortar
#

And not open source?

leaden ice
#

Unity uses PhysX

#

which is an open source physics engine

hearty mortar
#

Ah

hearty mortar
#

But yeah, it's just semi-implicit Euler

#

... Wait

#

No

#

Damn, my numerical analysis is rusty

#

No, you were right, it's velocity first then position

#

Well. Huh, I was expecting some higher order integrator

tall veldt
#

Iโ€™m trying to make a instantiated object shopt forward and when i set the velocity to vector2(1,0) it moves but when i set it to transform.forward it stays still, anyone know what the issue could be

dusk apex
#

The forward of an object in 2d by default would be the z axis.

#

You'd probably want to move relative to the object's right (assuming this is 2d)

leaden ice
pastel viper
#

anyone knows why input field doesnt work on mobile? The keyboard doesnt pop up to allow me to type

pastel viper
#

yea

pastel viper
#

@rigid island u know a fix?

spring creek
rigid island
# pastel viper is that the issue?

No itโ€™s not an issue. Not sure what it is then , try googling to see if you need to force keyboard idk I recall it works for me out the box

#

How are testing mobile exactly?

pastel viper
tall scroll
#

Is it apk or webgl?

pastel viper
#

WEBGL

tall scroll
#

Could be a webgl thing then

#

I know sometimes itโ€™s a bit buggy

pastel viper
#

is there a workaround?

#

like how can I implement a game without it breaking like that on mobile?

#

cuz I was also thinking about adding a virtual keyboard

rigid island
fickle moth
#

Anyone got any wise tips on how to achieve a tidal lock?

the Moon is tidally locked to the Earth because it rotates in exactly the same time as it takes to orbit the Earth.

I would preferably like to be able to tick a bool which would take into account the moons orbit Speed and distance from planet to moon to always have rotation locked regardless of its speed or distance!

rigid island
pastel viper
#

oh ty

fickle moth
#
private IEnumerator RotateAroundPlanet()
{
    while (true)
    {
        if (planet != null)
        {
            float angle = 0f;
            float rotationAngle = 0f;

            while (angle < 360f)
            {
                // Calculate the position of the moon around the planet
                Vector3 orbitPosition = planet.transform.position + Quaternion.Euler(0, 0, angle) * new Vector3(moonData.orbitRadius, 0, 0);

                // Set the moon's position to the calculated orbit position
                transform.position = orbitPosition;

                // Increment angle based on orbit speed
                angle += moonData.orbitSpeed * Time.deltaTime;

                // Rotate the moon around its own axis
                if (!moonData.isTidalLocked)
                {
                    // If not tidal locked, rotate at the specified rotation speed
                    rotationAngle += moonData.rotationSpeed * Time.deltaTime;
                }
                else
                {
                    // If tidal locked, calculate rotation speed based on orbit speed
                    float orbitalPeriod = 360f / moonData.orbitSpeed; // Time for one orbit
                    float rotationSpeed = 360f / orbitalPeriod; // Rotation speed for tidal locking
                    rotationAngle += rotationSpeed * Time.deltaTime;
                }

                // Apply rotation
                transform.rotation = Quaternion.Euler(0, 0, rotationAngle);

                yield return null;
            }
        }
        yield return null;
    }
}

Nevermind i got it working , heres the coroutine if anyone is interested in it

rigid island
#

// Apply rotation
transform.rotation
nice comments

fickle moth
#

lol im not saying make it code everything lol

somber nacelle
#

comments really shouldn't be just stating the obvious though, making that Apply rotation comment pretty useless

somber nacelle
#

and that's one of the many reasons to not use it

fickle moth
#

lol gotta learn somewhere!

makes my life easier , no need for me to add comments or completely restructure something simple when it can do it for me

#

in the end it still needs human input to be useful

spring creek
#

It will actively hold you back, lie to you, hallucinate, and teach you very bad habits

#

It could be argued to be ok when you have already learned to tell when it is wrong (i would argue the opposite), but it is HORRIFICALLY BAD for beginners

fickle moth
spring creek
rigid island
#

what will you do if GPT stops working ?

#

or server is down

fickle moth
fickle moth
spring creek
fickle moth
#

the ease of being able to have it explain things to me when i ask is amazing

mental rover
fickle moth
spring creek
#

The "hatred" is mostly born from the constant flood of garbage people get from it that they expect us to fix here

#

Spend enough time teaching and helping and you will see it

fickle moth
#

i can see that!

spring creek
#

There is a reason it is against the rules to use it for helping people or to ask for help with code from it

mental rover
fickle moth
#

lol i can see if the code hasnt been vetted by the user first

rigid island
spring creek
fickle moth
#

lol it should just be a pinned message that you are not allowed to post questions related to chat gpt if it needs over 3 references!

its okay with simple things , trying to get it to implement XOR encryption or A* is just not gonna happen

mental rover
#

it's utterly bizarre how much some people want to hate everything about it - not sure if it's fear or insecurity or what

spring creek
#

I just think it is realism

rigid island
#

yeah dont think ive seen any forthing at the mount hate for it

spring creek
#

And frustration over people suggesting it to beginners, who it WILL harm

fickle moth
#

especially if you use it correctly!

ask it hey what's an interface or what does abstract mean , goes a huge way

rigid island
#

nothing google can't answer though..

#

and more accurate because you learn critical thinking skills

spring creek
rigid island
#

rather than being sure the Spam generator is being legit

fickle moth
#

forsure but i can talk to it like a person... maybe i dont understand a key point of it

rigid island
somber nacelle
# mental rover there's definitely some knee-jerk and unfounded hate for it, see it all the time...

the problem is that most people don't use it that way. rather than using it as a supplement to help them understand concepts that they have been introduced to or as a tool to figure out what they should be learning, they use it as the primary source of learning. so they learn incorrect things because the AI doesn't know anything. it's just a very advanced text predictor like your phone's keyboard has

spring creek
#

Also when people ask for help and someone rolls in and says "i dunno, ask gpt"
Like, if you don't want to help, then don't help
We are here, and willing. No need to send people away

mental rover
# somber nacelle the problem is that most people don't use it that way. rather than using it as a...

I'm not sure that's actually true at all, I think that's a perception people have to "other" people who use it, and ultimately to undermine it itself. I understand why it's frustrating to try to help someone who hasn't engaged with a problem they want to solve, but it's little different from the countless other people that ask questions who didn't even bother to google it or look at the unity documentation

spring creek
cosmic rain
#

The issue is the way you use it. You can also google "complete script that does x" and when it doesn't work copy paste it in discord and ask why it doesn't work without any understanding of the code.

#

It's just easier to do such a thing with ai

somber nacelle
# mental rover I'm not sure that's actually true at all, I think that's a perception people hav...

it absolutely is true. i don't think you understand just how many times people have come in here trying to get help with AI generated code because they don't understand the code that was given to them and it doesn't work the way they expect. and there are a number of reasons that happens, mostly because people make the assumption that the AI somehow understands anything and expects it to be a good resource to learn from.
it's not. like i said before, it's basically just an advanced text predictor. literally all it is doing is predicting what the next most likely text would be based on its training input. this makes it a terrible tool to learn from, and the best it can be used for is to basically just rephrase other information in a way that (hopefully) makes sense to the people using it, but quite often, especially when it comes to unity stuff, it just makes things up. and then someone who doesn't actually understand the concepts they are trying to learn ends up internalizing that made up info or they come running to here because they heard they need to do something a certain way.

using text generators as a learning supplement is okay provided you already know what you are doing. but of course to already know what you are doing you need to learn from a decent source

mental rover
cosmic rain
fickle moth
cosmic rain
#

No one blames them for using ai specifically. We blame them for using it to cut corners. Important corners.

fickle moth
#

you cant even ask questions unless you understand the basics

mental rover
spring creek
#

That seems exactly like what boxfriend and I are saying at least
Just that it isn't the norm that we see

somber nacelle
#

it's only a balanced take if you agree with them

cosmic rain
fickle moth
#

i think we all have a deep hatred for machines

mental rover
# spring creek That seems exactly like what boxfriend and I are saying at least Just that it is...

That's the thing - you see a bunch of people that are using AI in an unproductive way, and you've made the leap to saying most people/99.9% of people are wasting everyones time, learning incorrectly, AI bad, etc, etc

Someone could come in here and ask a simple question and get a load of useful help. A different person could come in and ask the same question, but also mention they tried to ask ChatGPT first, and they'll get 5 people jumping down their throat like clockwork over how useless AI is and how it should never be used

#

but it's whatever, you do you I guess

spring creek
#

And I disagree about the part at the end. I see people mention it all the time and get help just fine

#

as long as they aren't asking for help correcting THAT code, which is against the rules. Which if they are, yeah, people point that out

#

I should say that I am on every day and scroll back to see what I missed, so maybe I just see the balance more?

mental rover
spring creek
mental rover
#

I mean you can literally scroll up and read it if you like

#

it's still there

#

good talk though, I think this conversation has run its course

spring creek
#

And THEY brought up gpt, and people just had a good chat. Mostly until you came and started making it hostile.
Hellfire was doing great and we were just having a friendly discussion, but you called it "frothing hatred" lmfao

But yeah, I'm done

cosmic rain
spring creek
#

@fickle moth
One last thing I DO want to say. Deynai obviously misunderstood the tone of what was being said at the beginning. I want to make sure you didn't feel that way too.

In my opinion, you have clearly been putting in the effort, you even resolved your issue before anyone could respond.
Don't want you to feel pushed away or put down. My comments in the beginning were true to how I feel, but also tongue-in-cheek. I thought that was clear, but clearly not haha.

Anyways. Apologies if you felt insulted or anything. Please do feel comfortable coming back for help whenever you need

fickle moth
#

appreciate you for the kind words!

spring creek
#

Awesome. Glad that is the case!

fickle moth
#

"Some men just want to watch the world burn"

quartz folio
#

Every time some company sends me a survey about their AI products I spend half an hour writing out all the reasons. They keep sending me surveys!

fickle moth
#

thinksmart print them out and use as toilet paper

quartz folio
#

Some poor engineer collecting reasons to get back to implementing something solid instead of massaging a pile of statistics until it blurts out the right thing

keen lantern
#

How should I approach plane physics. Someone told me the current way Im doing things is just reinventing the wheels and such. The hiearchy of my plane is an empty gameobject, with plane parts as the children. In this scenario, Im working on implementing a thruster, yet is the thruster is asymmetrical to the plane, torque would make it rotate. How can I, through code (the script is placed on the empty parent), place a force at the position of the thruster, and have torque apply, rather than the whole plane moving perfectly forward when asymetrically placed.

keen lantern
#

Does that have torque physics built into it

somber nacelle
#

did you bother reading the page?

keen lantern
#

*guess I can just cl-

#

was boutta say that lol

#

ah, literally the first line

#

If .AddForceAtPosition has torque built into it, then what the point of having a .Torque function in the first place

somber nacelle
#

because they do different things? AddTorque adds only torque to the rigidbody. AddForceAtPosition adds a force at a specified position which also results in torque being applied because the force is not being applied directly in the center of the rb

keen lantern
#

aight

broken light
#

ive not done source gen before in c# is it possible to use source generation so i can create enums on the fly in custom editors ?

#

im using strings at the moment but not a fan of it

thick terrace
broken light
#

how would my ide know ive created these enums so i can use them in code without errors of undefined all over the place though

chilly surge
chilly surge
#

The best use case of source generator is to "use existing code to generate more code," but it sounds like you want to generate code from assets/editor actions, so it's better to just use a regular editor script that creates and writes to .cs files.

broken light
#

we can edit cs files from editor?

#

because i need the bit flags of enums which strings dont provide but i need to be able to add / remove enums

#

but typically enums are hard coded

chilly surge
broken light
#

i see

swift falcon
#

Hi there, i have added this models of a mannequin, and i wanted to add a feature to them but idk how i do it, i wanted to them to make a random audio, but only when i am a little far away, if i am to close then them don't make any sound, but if i am far from them, it would make a random audio.
Does anyone know how to add that feature?

tired hearth
#

Do you guys get angry if I say that I program my game with AI? Lmao

trim schooner
#

Angry? No.
Point out that it's against server rules to ask for help with AI generated code? Yes.

wide dock
#

I couldn't care less, unless you'd come with AI generated code, not understanding what any of it does, and asked us to fix it.

tired hearth
#

Ahhh like that. My issue is, I suck at programming, did try many times. I know how to build the code technically and how methods should communicate etc, I'm just a total 0 IQ when it comes to remembering it etc.

#

I make up the methods and what they should do and contain and all that. How different methods or even scripts communicate with eachother. I just need help getting the actual code down

wide dock
#

Well, try harder, there's nothing else you can really do. Using AI generated code will just hold you back even more, and with enough practice you'll eventually be good enough to not suck at it

#

Practice, practice and once again practice

tired hearth
#

Maybe one day

knotty sun
tired hearth
trim schooner
#

You get better at programming by doing, keep doing.. more and more, do different things, etc

#

You're not expected to remember everything, even experienced devs google simple things because they've not used it in ages and have forgotten

thick terrace
#

yeah, the sign of getting better at programming is being able to find and use more info, not being able to memorize more code

knotty sun
latent latch
#

hey, ive read some terrible books before

thick terrace
#

and some of the best games have terrible code style, lol

latent latch
#

yet you'd still consider those who wrote them novelist

swift falcon
#

What's the fix for unity packages/libraries not being recognized by VS? I've tried regenerating csproj files, deleting Library, restarting VS, restarting Unity
No errors from within Unity it's just a VS issue. Other usings not recognized are:
UnityEngine.UI
NaughtyAttributes

thin aurora
swift falcon
thin aurora
#

IF you have those you'd have to reference Cinemachine in your assembly definition since it doesn't recognise it otherwise

swift falcon
#

Ok I don't think that's the issue afaik

knotty sun
swift falcon
knotty sun
swift falcon
#

The reason I don't think it's the issue is that Unity doesn't complain and compiles fine. Also other people on the project don't seem to have this issue although they are using different IDEs I think

knotty sun
#

Then you may need to ReGen your projects

swift falcon
#

Right now I'm updating VS in case that forces something to fix itself. After that I'll try deleting the .sln file and see if that does something

knotty sun
#

Or just Edit->Preferences->External Tools->Regenerate project files

swift falcon
#

Yeah I've pressed that a good few times

knotty sun
#

which IDE ?

swift falcon
#

VS 17.2.4

#

Updating rn to VS 17.9.6

knotty sun
#

which Unity version?

trim schooner
swift falcon
knotty sun
#

I think you should install at least VS 2019

swift falcon
#

I have VS 2022 sorry should have mentioned that

knotty sun
#

can you screenshot your external tools window

swift falcon
knotty sun
#

Ah, turn off all the checkboxes except Embedded packages and Regenerate

#

you might want to delete the .sln and all of the .csproj file before doing this

swift falcon
#

Ah that worked thanks! Do you know why you have to uncheck the other boxes?

knotty sun
#

because Unity is absolutely crap at generating working .csproj files

swift falcon
#

Brilliant thanks lol

hardy tendon
#

hi someone have some experience with assetsBundle ? i'm trying to download a scene and the materials are all purple and missing , the BuildTarget is Webgl and my build is in android is that the problem?

gusty aurora
#

Is there any way to know when a particle system is done emitting ?

thick siren
#

Hello guys, i have a small problem about repainting a property,
i a using a custom editor to draw a property, but the repaint is doing only if I move my mouse.
i have try InternalEditorUtility.RepaintAllViews(); but this is using too much performance (5 fps)...
do you have a solution to repaint my property every 0.5sec, so i keep my fps ?

thick siren
#

thanks you

fringe ridge
#

I make a duplicate of a 3d object, scale it up 10-20 percent, and i need to make sure, that the Y pivots are at the same point. I.e. the Y scale is bigger the same amount on top and on bottom

tall scroll
fringe ridge
#

programatically

#

tried with Bounds.size, cant get reliable results somewhy

tall scroll
#

Ohhh so the origin isnโ€™t actually the middle?

rigid island
fringe ridge
#

never in the actual middle

tall scroll
rigid island
#

So the original pivot is not center ?

tall scroll
#

Mhm

rigid island
#

could make parent object and scale that after offsetting child properly

#

or just fix the pivot in blender first

fringe ridge
#

there's 30+ objects, I really dont wanna do that in blender ๐Ÿ˜„

tall scroll
hexed pecan
#

So you basically want to 'scale around a point'?

tall scroll
#

Do you know the size of them before being resized? If so the maths shouldnโ€™t be too hard to work out, idk how fucked up your objects are though lol

fringe ridge
#

I actually made it work with the same scale, it looks even better what i was doing, but now i'm kinda interested on what would be the solution

fringe ridge
fringe ridge
tall scroll
#

I think thatโ€™s easier at the shader level tbh

hexed pecan
#

Unless it has hard edges, then it will look off

#

What I mean is basically adding normal * someScalar to the vertex position

fringe ridge
#

I'll try that, im kinda new to shaders. The objects do have a lot of hard edges

tall scroll
#

How does a normal work on a vertex? Is it an average of the faces around it?

hexed pecan
#

But yeah hard edges are probably an issue here. They are actually separate faces in unity so it would leave some gaps

leaden ice
vapid lynx
#

how do i fix that error?

leaden ice
# vapid lynx

Stop trying to use System.Text.Json unless you install it as a DLL in Unity

vapid lynx
#

Do i use Newtonsoft json thing?

leaden ice
#

You can

#

Or unity's JSONUtility

#

Either one

sharp root
#

Hello

#

Im want to make my raycast bigger , i saw that Spherecast is the way to do it

#

`void LateUpdate()
{
// Check if we are grounded now.
bool isGroundedNow = Physics.Raycast(RaycastOrigin, Vector3.down, distanceThreshold * 2);

    // Call event if we were in the air and we are now touching the ground.
    if (isGroundedNow && !isGrounded)
    {
        Grounded?.Invoke();
    }

    // Update isGrounded.
    isGrounded = isGroundedNow;
}`
#

What do i change here?

latent latch
#

You probably want overlapsphere, not spherecast

#

also why LateUpdate

leaden ice
sharp root
#

Well the problem is , my character (or the fps controller) cant jump when on the edge of an object, basicaly gets stuck on the edge. I know this is a common problem and i think i can fix mine if i just make the raycast bigger

leaden ice
#

Wdym

#

Get used to looking up the documentation for any function you're not familiar with. That's how the rest of us do it. That's what documentation is for.

vapid lynx
#

idk why itsn ot writing to the file?

knotty sun
vapid lynx
#

but i have the object and jsonutility thing

knotty sun
#

so what is it classes need to be before you can serialize them?

vapid lynx
#

huh?

knotty sun
#

you don't know what you are doing do you?

vapid lynx
#

i mean its my first time using json

knotty sun
#

ok, you are trying to serialize your object using json. In order for a class to be serialized is need to be marked as Serializable

vapid lynx
#

this right

knotty sun
#

yep

vapid lynx
#

I alr had the serilaoziable thing

knotty sun
vapid lynx
#

oh i just added it

#

but like

#

after i did it still didnt work

knotty sun
#

ok, and where are you expecting the file to be?

vapid lynx
#

in assets

#

the file is there

#

its just empty

#

after i run the code

knotty sun
#

ok, next lesson. JsonUtility does not serialize properties

vapid lynx
#

do i have any?

rigid island
#

uh yea

knotty sun
vapid lynx
#

oh mb โ˜ ๏ธ

#

i mean i was just following the unity documentation

#

and thats what they had

rigid island
rigid island
#

those are fields tho

#

hugee difference (exaggeration)

#

where do you see they added get and set accessors

vapid lynx
#

ohhhh

#

i get it

#

tyy

rigid island
ebon silo
#

which API Compatability level shoudl I be using in the "latest" unity? (I'm on 2022.3*). The docs are really confusing. This page says to "use the .NET Standard" compatibility level, but that is not an option in my Unity. I only see two options, ".NET Framework" and ".NET Standard 2.1". Am I to assume that what they are referring to is the ".NET Standard 2.1"?

#

And what exactly then is ".NET Framework"? that's also not described in the help pages

leaden ice
placid valve
#

Not sure if this goes here or not, but I have a piece of code for my interaction layers and thereโ€™s a bug in it, I just canโ€™t figure out where. For some reason, for only some of the layers, when I click to activate that layer, it also activates a layer at towards to top of the list as well. I can show screenshots of what that looks like as well as what the code looks like

#

Code is too long to send here

#

This is the error tho

#

Left foot phalanges later and default layer activate, and thatโ€™s not what I want to happen. I want it to be only left foot phalanges

leaden ice
tawny elkBOT
placid valve
#

Can also be viewed here

#

Please ping me if youโ€™re able to help out, thank you

obsidian forum
#

yo how do i import mesh from blender with animations and camera shake that i made in blender ?

vagrant chasm
# obsidian forum yo how do i import mesh from blender with animations and camera shake that i mad...

Unity Tutorial - Importing Animations From Blender / Blender to Unity

In this unity tutorial number seventeen of the Lost in the Sea series, we import animations from blender to Unity. This includes importing the animations we created of the Octopus to Unity.
From Blender to Unity import animations correctly and fix problems with location, rot...

โ–ถ Play video
reef garnet
#

Why can I not use await with LoadSceneAsync?

[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static async void Init()
{
    DontDestroyOnLoad(Instantiate(Resources.Load("Systems")));

    await SceneManager.LoadSceneAsync(0, LoadSceneMode.Single);
}```
#

Here is the error
AsyncOperation' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'AsyncOperation' could be found (are you missing a using directive or an assembly reference?)

reef garnet
#

damn ok, what would you do here then?

#

this is to load a Bootstrapper as default scene

rigid island
reef garnet
#

just had a look will get to it, thanks

rigid island
reef garnet
#

yeah I gathered that one

#

thanks for the quick help

ebon silo
reef garnet
#

I seem to have stumbled on something like that

ebon silo
#

use UniTask too

broken light
#
#if UNITY_EDITOR
        DestroyImmediate(gameObject);
#elif UNITY_RUNTIME
        Destroy(gameObject);
#endif

why cant unity determine the difference for us so we don't have to keep writing this every where -_-

dusk apex
broken light
#

i have just think unity should've done it from the start

cosmic rain
broken light
mild coyote
broken light
#

well it can be destroyed at run time by a user but i also have an editor script that deletes them

mild coyote
#

ah, that makes sense now

broken light
#

yeah but if unity editor is still possible at run time thats not good

mild coyote
#

although maybe you should have separate script between editor script and runtime script

broken light
#

ah okay thanks

cosmic rain
broken light
#

so what does the if unity_editor even mean compared to unity_runtime?

#

ive seen a lot of people use if defs i guess they don't even realise it either

cosmic rain
#

No clue what unity_runtime is. Can't find it in Google either. It probably doesn't exist at all.
As for the editor define it's to distinguish builds from the editor.

cosmic rain
broken light
#

ah i see

#

does seem _runtime is not defined or not documented

#

would it normally not compile if its not defined

#

or just never occur

somber nacelle
#

yeah the point of a conditional compilation symbol is to only compile code when that symbol is defined. if it is not defined, then the check returns false so it does not compile that code

cosmic rain
broken light
#

ah okay fair enough, i think i figured out a new work around ill have the editor script call the destroy immediate then clean up in OnDestroy, rather than call a delete function on the object im trying to delete

vapid lynx
#

I cant find the read input for some reason

leaden ice
somber nacelle
swift falcon
#

I'm trying to implement individual post processing for multiple cinemachine cameras but for some reason the volume profiles always seem to be connected somehow. Even if I create new volume profiles for each camera at runtime whenever I change a value on one volume component it always changes the post processing of both cameras. What could be happening here?

    private void Awake()
    {
        m_cameraFreeLook = GetComponent<CinemachineFreeLook>();

        m_cameraPostProcessingVolume = GetComponent<CinemachineVolumeSettings>();
        CloneProfile();

        m_cameraPostProcessingVolume.m_Profile.TryGet(out m_vignette); 
        m_cameraPostProcessingVolume.m_Profile.TryGet(out m_bloom); 
        m_cameraPostProcessingVolume.m_Profile.TryGet(out m_chromaticAberration); 
    }

    void CloneProfile()
    {
        VolumeProfile clonedProfile = Instantiate(m_cameraPostProcessingVolume.m_Profile);
        for (int i = 0; i < clonedProfile.components.Count; i++)
        {
            clonedProfile.components[i] = Instantiate(clonedProfile.components[i]);
        }
        m_cameraPostProcessingVolume.m_Profile = clonedProfile;
    }```
amber wigeon
#

Hello, I am also making a puzzle game, and I have about 25 levels, however I can not find the perfect way to save the level on which the player is so that when he presses play he goes to that level, can anyone please help me?

mellow hill
wide dock
upper pilot
#

How can I make a callback in 1 line without creating delegates?
I.e. I want to pass callback into a function.

In my case a Transition effect is supposed to call a function after its finished(my callback function)

Transition.Instance.FadeIn(() => DoThis());
chilly surge
#

Does DoThis have any parameters? If not, you can just .FadeIn(DoThis).

upper pilot
#

Yeah but what is the type of "DoThis"?

#
public void FadeIn(Callback callback)
chilly surge
#

Are you implementing FadeIn and you are asking about what type the parameter should be?

upper pilot
#

yeah

chilly surge
#

That would be Action.

upper pilot
#

Thanks

high trail
#

Unity is refusing to acknowledge collision and I am about to fail a class because of it

upper pilot
#

What about 2d matrix?

high trail
#

yes

#

wtf is a 2d matric

upper pilot
#

Is any one of them set to "IsTrigger"?

high trail
#

no

upper pilot
#

Then show some code

#

Do they have rigidbodies?

#

I am pretty sure rigidbody2d is required

#

If its 2d game, then you should use colliders2D + rigidbody2D

high trail
#

they do

upper pilot
#

Not sure what is sleeping mode in rigidbody, but check if its not "start asleep"

knotty sun
# high trail they do

this is not 20 questions, screenshot the inspectors of both objects and show your !code

tawny elkBOT
high trail
#

the top one is not working

knotty sun
high trail
#

I have no idea how to do any of this I am trying to not get an F in a class that ends in 56 minutes

#

I don't give a rat's ass about debugging I want to pass

knotty sun
#

then you deserve an F if not lower

upper pilot
#

I thought F is lowest?

#

Sounds weird when someone say "I want F to pass" lol

knotty sun
#

in my day it was U - Unclasified

high trail
#

That's not what I said

upper pilot
#

Tbh even if it doesnt work, I assume you'd get more than an F for trying?

high trail
#

nah

sleek bough
upper pilot
#

If they taught you basics of debugging then this should be few minutes of going through code step by step in debug mode.

high trail
#

I don't even know how debug mode would be activated

upper pilot
#

I can assume that your objects dont have proper tags so your script is not detecting them.
Also OnCollisionEnter2D should be on a weapon or an enemy, so I dont know why you'd check for tag weapon and name of enemy.
I could be wrong tho.

sleek bough
knotty sun
upper pilot
#

Yeah tbh why do I care more than he does, good luck ๐Ÿ˜„

high trail
knotty sun
#

it doesn't take months, it takes 5 minutes

#

and you still have not provided the requested screenshots

high trail
#

what screenshots?

#

debugger will not even allow me to place a breakpoint

high trail
leaden ice
knotty sun
leaden ice
high trail
#

not originally

#

that got changed

leaden ice
#

Oh the gremlins changed it!

#

Pesky gremlins

high trail
#

it was changed as troubleshooting ie it was already not working

#

<@&502884371011731486> these people are being incredibly condesending

leaden ice
#

Do you want the mods to castigate us or didn't you have a class you were about to fail in 34 minutes?

vagrant blade
tall scroll
#

Back in my day we didnโ€™t have access to discord during our finals

upper pilot
#

Tbh for his use case, he needs a trigger I think ๐Ÿ˜›

high trail
#

Back in your day people were decent. I guess you aren't like your generation then.

thin aurora
#

Bugfixing is one thing, but having to make your game even playable in general an hour before the deadline just reeks of improper planning

high trail
#

Nobody asked you

#

Literally nobody

#

Not one person

tall scroll
vagrant blade
#

Issue is solved, everyone can go about their day now.

high trail
#

"solved"

#

I guess you just allow people to act like animals in your server

upper pilot
#

Nobody asked

sleek bough
#

@high trail If you don't have a Unity related question don't post off-topic here

high trail
#

Wow.

quartz folio
#

Just entitlement from the start and you wonder why you're getting this response

sleek bough
vagrant blade
#

Well, only 20 more minutes before their supposed class ends. Good luck to them. ๐Ÿ‘

tall scroll
upper pilot
#

I have a general code question about booleans.
I have a Transition screen script and I store few booleans:

    public bool isFadingIn { get; private set; }
    public bool isFadingOut { get; private set; }
    public bool isFadedIn { get; private set; }
    public bool isFading { get { return isFadingIn || isFadingOut; } }

That 3rd boolean "isFadedIn" is a state between fadedIn and fadedOut which means that screen is black.
I use this state to change a scene.

Should I just use enums for a state?
i.e.

public enum
{
  None, // After faded out it goes back to this initial state
  FadingIn,// progressing through fading in
  FadedIn, // finished fading in
  FadingOut, // progressthrough through fading out
  FadedOut, // Finished fading out
}
latent latch
#

either way

#

well, I mean you could only be in one state so enum would make sense

upper pilot
#

I'd still keep isFading probably

upper pilot
high trail
#

Excuses

quartz folio
#

!mute 428784312834326529 24h come back tomorrow without wasting other's time

tawny elkBOT
#

dynoSuccess pk_spartan was muted.

tall scroll
#

Sometimes I do feel like programmers gatekeep

#

And other times people learn to code mid-final

gray mural
thin aurora
upper pilot
#

Actually I just realized...in my script I don't always move from fadeIn to fadeOut

#

for example, I can fadeIn(screen is black) then do nothing until my other script decides to fadeOut

#

so a state would have to know when to wait.

#

its just changing alpha lol

upper pilot
#

!code

tawny elkBOT
upper pilot
#

Posted a link instead, for something so basic like changing alpha you'd expect less code right? ๐Ÿ˜„

#

I can probably move a variable for tempColor outside the if statement

chilly surge
#

Personally these are the types of stuffs that work really well if you wrap them in async/await.

quartz folio
#

And/or using a tweening library

upper pilot
#

I havent gotten to tweening library yet, but I have it bought for my personal project so I will start using it soon ๐Ÿ˜„

trim schooner
#

DOTween has extensions for it all

chilly surge
#

Once you have them wrapped up, usage becomes extremely simple:

async UniTask TransitionToNextLevel()
{
    await FadeIn();
    await LoadNextLevelOrSomething();
    await FadeOut();
}

And if you want to start loading right away without waiting for fade in so that the loading time is shorter for the player? Also easy to express:

async UniTask TransitionToNextLevel()
{
    // Loading starts right away in the background
    var task = LoadNextLevelOrSomething();

    await FadeIn();
    await task; // Make sure loading finishes by this point
    await FadeOut();
}
trim schooner
#

you'd just do myImage.DOColour(); and the 2 or 3 params it needs

upper pilot
#

How do you make sure that loading is finished tho?

#

scene loading I mean

chilly surge
#

Because you await it, so it must finish before moving to the next line of code.

latent latch
#
public class Fade : MonoBehaviour
{
    public enum States
    {
        FadingIn,// progressing through fading in
        FadedIn, // finished fading in
        FadingOut, // progressthrough through fading out
        FadedOut, // Finished fading out
    }

    private Dictionary<States, Action> stateDict;
    private States currentState;

    private void Start()
    {
        stateDict = new()
        {
            {States.FadingIn, () => FadingIn()},
            {States.FadedIn, () => FadedIn()},
            {States.FadingOut, () => FadingOut()},
            {States.FadedOut, () => FadedOut()},
        };
    }

    public void Update()
    {
        stateDict[currentState].Invoke();
    }

    private void FadingIn() { }
    private void FadedIn() { }
    private void FadingOut() { }
    private void FadedOut() { }
}```
#

that's my idea

upper pilot
latent latch
#

just having a general fading tween sounds good

hexed pecan
#

Which is async/await but with coroutine-like functionality (afaik)

knotty sun
latent latch
#

yeah that sounds good too

#

but dictionary is love

upper pilot
#

oh UniTask is not built in Unity

chilly surge
latent latch
#

is there difference between a switch and pattern matching

upper pilot
latent latch
#

ide always recommends me to change them into a pattern matching state

upper pilot
#

    private void OnSceneLoad(Scene arg0, LoadSceneMode arg1)
    {
        if (TransitionScreen.Instance.isFadedIn) TransitionScreen.Instance.FadeOut();
    }
#

I check if the screen is black then I fade out on scene load

gray mural
upper pilot
#

Is that await idea possible without installing packages?

gray mural
#

So you can always make a normal switch out of the short one, but not otherwise

chilly surge
upper pilot
#

so I can do:


await FadeIn();
await ChangeScene();
await FadeOut();//after new scene is loaded
#

Does code run during scene switch? Should I do async scene load(I think there is such a thing, but it might have a different use case?)

thick terrace
chilly surge
#

async/await is built into C# as well.

upper pilot
#
    IEnumerator LoadYourAsyncScene()
    {
        AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("Scene2");

        // Wait until the asynchronous scene fully loads
        while (!asyncLoad.isDone)
        {
            yield return null;
        }
    }
#

Seems like something I might want to use for my case?

chilly surge
#

Enumerator based coroutine is basically a caveman version of async/await.

hexed pecan
#

Such as waiting for a frame

upper pilot
#

But your example uses UniTask which seems to not be part of Unity?

chilly surge
thick terrace
hexed pecan
thick terrace
#

Task.Yield works fine for that

upper pilot
#

Is UniTask in asset store? I only found some github page and I am not a fan of installing packages outside of Unity or in general as I will have to remember it for all of my projects if I want to keep using it.

latent latch
#

git

thick terrace
hexed pecan
thick terrace
#

the unity sync context updates once per frame like coroutines do

#

i believe some time between Update and LateUpdate

upper pilot
#

Any recommended (game related) examples of async/await to learn from?
I never use those nor do I use IEnumerator in my games and I am probably losing on a lot.

#

I used a bit of those in the past, but it didnt stick with me.

thick terrace
chilly surge
gusty aurora
gusty aurora
#

If not, which one is faster / better practice ?

knotty sun
#

they are the same

chilly surge
quartz folio
hexed pecan
# thick terrace try it and see!

I believed you, but tested it anyway, and yeah you right ๐Ÿ‘ Maybe I had been lied to or I'm mixing it up with something else

thick terrace
hexed pecan
#

Yeah I'll use Awaitable once I go 2023

thick terrace
# hexed pecan This message is probably what originally confused me ๐Ÿ˜„

iirc there actually is a very minor difference depending on when you await, because it can return control to you on the same same frame you started from if you await before the point in the loop the sync context updates... but most of the time i use Task.Yield it's in a loop waiting for something, so it's not a huge difference

#

and you can write a small wrapper checking the frame number if it does matter

novel bough
#

Hi friends, I am generating a grid of objects at runtime and deleting them at runtime by clicking on them, and I want to show the number of tiles available on each side and also on the cut like showing in the image all sides (6 - 4 - 4 - 6) and on the cut (2 - 2). so how can I easily do this. thanks!

leaden ice
vagrant blade
#

Might be easier to do something like going through each row, and then iterating through the spots on the row before and the row after. When you find an empty space, count it and keep going until you don't find another empty space. Take that number and put the number half way between the number of spaces you found.

#

Then rinse repeat for the columns

magic harness
#

Hey guys, im having some trouble dealing with my scene management system.

For some reason my MainMenu scene is not unloading whenever i call the startGame function

as you can see, i've tried some things already

 public IEnumerator StartGame()
    {
        SceneManager.SetActiveScene(bootstrap.LoadedScene);
        UnloadScene(mainMenu.BuildIndex);
        yield return UnloadScene(mainMenu.BuildIndex);
        AsyncOperationExtensions.AsTask(SceneManager.LoadSceneAsync(HUDScene.BuildIndex, LoadSceneMode.Additive));
        yield return LoadAsActiveScene(gameplayScene.BuildIndex);
        
        isGameStarted = true;
    }


 public IEnumerator UnloadScene(int index)
    {
        AsyncOperation asyncUnload = SceneManager.UnloadSceneAsync(index);
        while (!asyncUnload.isDone)
        {
            yield return null;
        }
    }

Would appreciate some help, it is not my only loaded scene neighter it is the active scene whenever i unload it

leaden ice
#

Also this will do nothing on its own
UnloadScene(mainMenu.BuildIndex);

magic harness
#

ok.. but the coroutine will, wont it?

leaden ice
#

yes

magic harness
#

im calling it from an object in the MainMenu

leaden ice
#

show the code for that

dusk apex
#

You need to start coroutines the proper way: StartCoroutine

trim schooner
#

I've not used AsyncOperation .. doesn't this also need calling?

leaden ice
#

But yeah what's with AsyncOperationExtensions.AsTask(SceneManager.LoadSceneAsync(HUDScene.BuildIndex, LoadSceneMode.Additive));

magic harness
magic harness
leaden ice
#

SceneManager.LoadSceneAsync does that already

#

anyway have you tried adding logs here?

#

TO make sure all the code is running as expected?

magic harness
#

i mean, the HUD and the gameplay scene load as expected

#

its just the main menu not unloading for some reason

leaden ice
#

soo add some logs to the unload scene coroutine?

#

make sure it's fully executing as expected

#

I mean presumably the coroutine is finishing if it's getting to those lines

#

do you perhaps have multiple main menu scenes open?

magic harness
#

thanks!

fervent furnace
# novel bough Hi friends, I am generating a grid of objects at runtime and deleting them at ru...

extend from Osteel solution a little bit, you need to make one look up tables with size = AABB of the shape extend by one row and column for different size eg if the AABB is 4x8 then the look up tables should be 6x10, then perform the scanning
eg if you have a shape and scan row by row
XXXXXXXXX
XAAAXXXAX
XAAAXXAAX
XAAAXXAAX
XAAAXAAAX
XXXAAAAXX
XXXXXXXXX (X means empty and A means there is a tile)
then your look up tables when finding the left perimeter should be
000000000
100000100
200001000
300002000
400010000
000100000
000000000
and your look up tables when finding the right perimeter should be
000000000
000010001
000020002
000030003
000040004
000000010
000000000
basically for the left size, table[r][c]=table[r-1][c]+1 if grid[r][c+1] (right cell) is not empty and grid[r][c] is empty else 0, the look up tables is filled with 0 first, after assigning the perimeter for one side, reuse the look up table
your next task is getting back the perimeter from the look up tables and assign the perimeter back
your problem not that difficult, but many edge cases
(the size of look up table can be smaller btw)

candid coral
#

Greetings, I am struggeling with an issue, if anyone has time to look at. Using Vuforia, I want to make so that when both ImageTargets/Objects are within the ARCamera View, they rotate. So when one is not within the scope of the Camera, then the other one that is, does not rotate.
As shown in the images, this should do the job. However, this does not work. What's even more strange, I have tried making logs and finding unusual feedback.

Situation 1: Without changing anything. Cube and Cylinder alternates between true and false, when it should be always true since they are within the scop of ARCamera, so they should always behave like "OnTargetFound".

Situation 2: In the imageTarget's inspector, I checked onTargetLost box, so now when the object is not within ARCamera View, it also returns true. But the log is still returning false somehow.

Situation 3: I changed the code to be:

public class ObjectRotationManager : MonoBehaviour
{
    private GameObject cylinderObject;
    private GameObject cubeObject;

    private bool cylinderInTargetView = true;
    private bool cubeInTargetView = true;

    void Start() {
        cylinderObject = GameObject.Find("Cylinder");
        cubeObject = GameObject.Find("Cube");

    }

And I am still getting falses.
However, if I put this

cylinderInTargetView = true;
cubeInTargetView = true;

inside void Start(), now it returns true always. However, it always returns true, even when the object is out of ARCamera view.

I am rather disoriented and would appreciate any feedback on this topic.