#archived-code-general

1 messages ยท Page 32 of 1

main token
#

it still casts it back to an int

#

the performance gain/loss is negligible tbh

woeful leaf
#

probably yeah

#

I don't use either now though because I realised I just needed to use - lol

#

I was overcomplicating it

thin aurora
mental rover
#

division by 2 is extremely quick - same as int >> 1

whole yew
#

this is a little bit off topic but where can I find good artwork for the background of my game?

#

kinda just looking for anything

#

multiplying by 0.5 could probably be even slower lol

#

since a divison by 2 is just 1 right binary shift and tits super fast

#

if you divinding by like 3.14159265 then division becomes slower, but dividing anything by a power of 2 is super fast

#

you doing that just makes it slower and makes the code look bad

woeful leaf
#

True

#

I changed it afterwards back to division

woeful leaf
hidden kindle
#

How would I make my A* enemy jump over gaps?

#

Or is there a way I can use Unity's NavMesh in 2D?

woeful leaf
#

If it's a certain weight, then jump?

hidden kindle
#

I'm trying to figure out a method for it to detect gaps, but the ones I come up with are a hit or miss

woeful leaf
#

The latter is probably the easiest

pulsar elm
#

Yo, any way to check for objects being rendered by a specific camera?

woeful leaf
#

Probably, google1google2google3

pulsar elm
#

I mostly check unity docs

#

and I quite did but I also added in "without raycasts" so I only got results about raycasts

main token
hidden kindle
#

But for now, I'll look into the weight thing

neat lagoon
woeful leaf
#

It depends how optimally and realistic you want to have it

neat lagoon
#

if the gap can be more than 1 tile wide, and you need to be able to jump to any tile across the gap (not necessarily just cardinal directions), then good luck lol

woeful leaf
#

Because I assumed that the character can jump any gap, but that's probably not what you want

#

Pathing isn't that easy

neat lagoon
hidden kindle
neat lagoon
#

what do you mean?

#

shouldn't that happen automatically since it would, by default, path around gaps?

hidden kindle
neat lagoon
#

this makes it seem like you have an A* enemy

hidden kindle
neat lagoon
#

so gaps are considered walkable right now?

#

is this your own A* code?

hidden kindle
hidden kindle
#

I used it because when I used the AILerp script, my enemy would just float to the player

#

But I want it to be a grounded enemy

neat lagoon
#

well then, I will say that it would be very difficult to make enemies jump over gaps + include that in the pathfinding if it's not a completely custom pathfinding solution

#

I think the easiest way would be to fake it, like Wumpie said

#

you should be able to automatically tag "edges" around gaps with something

#

and if you encounter those edges, you step through the path via nodes and find the first non-gap node in the remaining path

#

then you play a jump animation from the start edge to the end edge, on the other side of the gap

#

you would leave gaps as walkable for this to work

#

but this also means you don't have much control over the length of gaps that can be jumped over, etc

#

they would be able to jump over a gap of any length

balmy radish
#

Hello
i have player which moves Top Left down and right (2D Topdown withought diagonal).
So the Problem is that i have also a Tilemap and i want the Player to kind of Snaps on Middle X and Y of the Tiles in the TileMap.
My code:
private void updateMovement()
{
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");

    if (Mathf.Abs(horizontal) > Mathf.Abs(vertical))
    {
        vertical = 0f;
    }
    else
    {
        horizontal = 0f;
    }
    animator.SetFloat("hori", horizontal);
    animator.SetFloat("vert", vertical);
    Vector2 direction = new Vector2(horizontal, vertical);
    transform.position += (Vector3)(direction * maxSpeed * Time.deltaTime);
    //updateHookPos();
}

lets Say we have a Tile 32 x 32 and i move the player to the left then he has kind of snap softly to the middle Of Y-Axe
Any Idea?

#

Kind of like this:

#

Xd

hidden kindle
#

And then maybe I could have a raycast coming out from the ground to see if another ground is within a certain distance

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.

balmy radish
#

outch sry

whole yew
#

you can just check the position of the player and set it to the closest value with is a multiple of 32, if that's what you want

balmy radish
#
rivate void updateMovement()
    {
        horizontal = Input.GetAxis("Horizontal");
        vertical = Input.GetAxis("Vertical");
        
        if (Mathf.Abs(horizontal) > Mathf.Abs(vertical))
        {
            vertical = 0f;
        }
        else
        {
            horizontal = 0f;
        }
        animator.SetFloat("hori", horizontal);
        animator.SetFloat("vert", vertical);
        Vector2 direction = new Vector2(horizontal, vertical);
        transform.position += (Vector3)(direction * maxSpeed * Time.deltaTime);
        //updateHookPos();
    }
balmy radish
tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
whole yew
#

you want it to snap only on vertical?

balmy radish
#

no and Horizontal depends on the mOvement like when u go to left and right it snap vertically and top and down snaps horizonatly

whole yew
#

this should work

#

change result instead to your x or y position

balmy radish
#

wait can u modify the code with that? ^^

whole yew
#

this will snap the value to the closest 32

#

wait

balmy radish
#

ok thx ^^ iw8

whole yew
#

do you want it always snapped on the grid

#

or what

#

i dont 100% understand what you want to fully do

balmy radish
#

like softly snapping while moving? is it possiable

#

like with time.delta time while moving u k

#

^^

whole yew
#

after you stop moving?

balmy radish
#

no while moving

#

wait

whole yew
#

hmm

#

so you dont want it to hard snap, you want it to slowly shift to the nearest grid and not instantly

balmy radish
#

example:
u r not snapping and u r on the 10pixel so while moving it incress to 16 because u k is the middle

#

exactly ^^

whole yew
#

can u answer my question

balmy radish
#

which one ^^

balmy radish
whole yew
#

both x and y?

balmy radish
#

depends on the movement u go right or left then its snaps on Y and top or down it snaps to X

whole yew
#

you said y 2 times

#

k

#

i understand

balmy radish
#

sry Xd the problem when u use a German Layout Xd

lofty barn
#

How do I simulate user input in unity?

whole yew
#

I made u a little function

#

if you give it a float of your position, it will return a next position you should be for that axis

#
        transform.position += (Vector3)(direction * maxSpeed * Time.deltaTime);
        if (verticalMove)
        {
            // Snap horizontally
            transform.position += new Vector3(NextSnapPos(transform.position.x), 0);
        }
        else if (horizontalMove)
        {
            // Snap vertically
            transform.position += new Vector3(0, NextSnapPos(transform.position.y));
        }
#

@balmy radish and then something like this maybe

#

I havn't tested it but you can play around and you need to create the variables for horizontalMove and verticalMove (they are bools) and if you move horizontally you need to set horizontal move true for example

balmy radish
#

wait lemme try it ^^

whole yew
#

and also set a lerpSpeed, if it works, then good, but I didnt make it for that purpose, this should just be an idea how you could solve a problem like this

balmy radish
#

yes thx verymuch it is not working rightnow but i got the idea and iwill change it like that ^^

#

thx verymuch again ^^

whole yew
#

do you understand the logic though?

balmy radish
#

Yes iam just trying to understand why the player if flying with 15555000000 speed Xd

whole yew
#

LOL

balmy radish
#

smaller than 0.005`=? XD

whole yew
#

wait

balmy radish
#

XD

whole yew
#

you want 32 pixels right?

balmy radish
#

i said the Sprit is 32

whole yew
#

you want to snap how many units

balmy radish
#

1 only which is the play

#

i think it has to be val % 1

whole yew
balmy radish
#

wait can i write to u on private?

#

Xd

whole yew
#

sure

muted grove
#

Does IL2CPP produce faster code than Mono? Should you use IL2CPP everytime when producing a release build?

polar marten
muted grove
#

are there any downsides to using il2cpp beside longer compile times

polar marten
polar marten
muted grove
#

i looked up il2cpp and it looks like unity games compiled with it are very easy to mod with decompilation tools, should i care about that?

glossy barn
#

Can someone help me understand how machine ends up as null? I copy and pasted the file path of my prefab so I'm incredibly frustrated.

lucid valley
polar marten
lucid valley
#

^ yeah sorry i didnt actually look fully at your code, i agree with doctorpangloss. Referencing a prefab in the inspector is a lot better than using Resources.Load

#

you've already made it a [SerializedField] too

glossy barn
#

What should I do if I am going to be changing the prfab a lot though?

lucid valley
#

wdym changing

glossy barn
#

I change it based on player input then instantiate a new Game Object and delete the old one

#

its a building system

#

Should I just have like ten GameObject variables and assign them in the inspector?

lucid valley
#

how is the player choosing the input?

leaden ice
glossy barn
#

That shouldn't affect it but they use the number keys

glossy barn
lucid valley
#

number key to array index then?

glossy barn
#

Just out of curiosity, how would you do it the "hard way"?

#

Like if I wanted to grab a prefab with code instead of using the inspector?

lucid valley
#

i probably would never use Resources.Load, and just have some sort of storage system of prefabs in a singleton Scriptable object

#

but with what you were doing originally you could use Resources.LoadAll from a folder and then make the array but you'd need to have a script on those prefabs to determine the order so your number keys don't change if you add a new prefab

glossy barn
#

Cool

#

thanks for your help!

polar marten
#

so it's not super clear to me why you want to do things this way

glossy barn
neat lagoon
#

I would personally use addressables if I wanted to grab things without the inspector

polar marten
glossy barn
warm yarrow
#

Hey everyone,
Recently I uploaded my android game to Google Play Store. I have integrated Unity Analytics/DevOps. In the DevOps panel I see that 5 users out of 300 ecountered an error:

Managed Stack Trace:
 
UnityEngine.SceneManagement.SceneManager.UnloadSceneAsyncInternal (UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.UnloadSceneOptions options) (at <00000000000000000000000000000000>:0)
SceneLoader+<LoadCoroutine>d__10.MoveNext () (at <00000000000000000000000000000000>:0)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <00000000000000000000000000000000>:0)```

I'm unable to reproduce this manually on any of the devices that I own. Here's the code that I use for loading/unloading scenes:

```private IEnumerator LoadCoroutine(string sceneName)
{
    _loading = true;
    var scene = SceneManager.GetActiveScene();
   
    // load transition scene
    yield return SceneManager.LoadSceneAsync(LoaderSceneName, LoadSceneMode.Additive);
    SceneManager.SetActiveScene(SceneManager.GetSceneByName(LoaderSceneName));
    yield return null;
   
    // unload original scene
    yield return SceneManager.UnloadSceneAsync(scene);
    yield return null;
   
    // load new scene
    yield return SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);
    SceneManager.SetActiveScene(SceneManager.GetSceneByName(sceneName));
    yield return null;
   
    // unload transition scene
    yield return SceneManager.UnloadSceneAsync(LoaderSceneName);
 
    _loading = false;

Am I doing something wrong? Why would this occur only on 5 out of 300 devices? I'd appreciate any help.

polar marten
#

ideally you would not use scenes

warm yarrow
#

why not? aren't scenes one of the most basic structures in unity?

neat lagoon
#

you could, for whatever reason, have an improper (unintended) state generated via your code that could cause this function you sent to error

polar marten
#

i'm not sure if they provide value for you over prefabs. the issue you're experiencing is one of many anecdotes and problems

#

related to scenes, and the workarounds needed to do basic things like having an object that persists across scenes

#

anyway it's everyone's prerogative. i give this advice all the time, and i'm always right about it, in the specific context i give it

#

i don't know if your game needs scenes

#

you can probably store all the content in one scene

#

and use prefabs for your levels

#

you do not call Resources.UnloadUnusedAssets are you? if you're not calling it, you're not saving any resources, which is what you're about to say as to why you need scenes

#

even though that interacts correctly with destroying game objects for any reason, not just game objects that are destroyed by unloading scenes

neat lagoon
#

a little silly to recommend such an architectural change when the game is already on the google play store

warm yarrow
#

I don't ever call UnloadUnusedAssets

polar marten
polar marten
# warm yarrow Hey everyone, Recently I uploaded my android game to Google Play Store. I have i...

Am I doing something wrong?
if you can use just 1 scene, and remove all the complex code you have for deawling with transitioning between scenes, and instead use prefabs and simply
SetActive(true) on thigns that should be visible, SetActive(false) on things that should not be visible, which literally replaces 99% of SceneManager use cases
then in a sense you are doing something wrong. there's nothing wrong with your code here

neat lagoon
polar marten
#

Why would this occur only on 5 out of 300 devices?
given how hard it is to figure this error out, there is probably an application bug relating to multiple game objects with dontdestroyonload or similar techniques to persist between scenes, interacting unusually, in a situation that is hard to reproduce / QA

#

i don't know, it would probably take me about 2 hours to remove scenes

#

in a codebase i've never seen

#

2 hours is nothing

#

drag and dropping all the content of the scenes into prefabs, creating a new Game scene

#

removing all the weird code

#

then using SetActive

#

it's not bad

#

i don't know anything about the game

#

but hey, you've probably spent more than 2 hours dealing with this bug

#

or will

#

so it's your call

#

your game

neat lagoon
#

Yeah, it is his, so chill out on the random controversial suggestions

warm yarrow
polar marten
#

look at how much stuff you have to do

#

blocking input, toggling loading... for what exactly?

#

DontDestroyOnLoad?

#

don't you see

#

you don't need any of this if you just use prefabs to organize instead of scenes

#

this is obviously organizational

#

you can organize your stuff into prefabs

eager yacht
#

all of this effort put into a suggestion he doesn't need

polar marten
#

it is basically thes ame experience in editor

warm yarrow
#

how would switching to prefabs omit the need to blocking the input?

polar marten
#

you already do it all the time

#

you already use prefabs

warm yarrow
#

but Set active/Instantiate blocks main thread when it needs to load something

neat lagoon
#

Just store your entire game levels in prefabs and freeze your application while you enable / disable them ๐Ÿค“

polar marten
#

"async" doesn't mean no freezing

#

and besides, if you have everything instantiated - i always pre-pool, put a prefab reference directly into the scene, etc - there will be less freezing compared to loading a scene

#

@warm yarrow anyway you won't fix this problem, trust me

#

it's extremely obscure

neat lagoon
#

Hmm, well I would consider seeing a moving load screen with an animated load bar to not be "frozen", but I guess we all see things differently

polar marten
#

1.6% error rate... you are going to have to play your game for hours upon hours to reproduce this

warm yarrow
#

@polar marten I appreciate your advice but you are suggesting a solution that interferes with the way Unity is designed

polar marten
#

which is another way unity is designed

#

i'm not suggesting any interference

#

i'm suggesting a solution that interferes with how you like to organize and think, which is, "i have a lobby scene" "i have a game scene"

#

but unity doesn't care

#

and i'm suggesting you just have a lobby prefab

warm yarrow
#

how would I bake lightning in the prefab?

polar marten
warm yarrow
#

there might be, but you said you could convert any Scenes system into prefabs system

polar marten
#

that's correct

#

i would probably just drop the prefabs in and bake them into the scene

steep herald
#

Yeah, you can bake lighting into prefabs

polar marten
#

once

#

and then move on with life

#

because that would take like 5 minutes

#

then move them out

warm yarrow
steep herald
#

love your optimism for baking times

polar marten
steep herald
#

Hah yeah then that makes sense

polar marten
#

is sort of the right answer

#

none of us can do anything about how crappy unity's lighting is

warm yarrow
#

anyway I feel like this conversation is drifting away

neat lagoon
#

Has been for a long time.

polar marten
#

the error message is telling you something that makes literally no sense

#

which i hope has illuminated for you how utterly brittle and stupid SceneManager is

#

it is so bafflingly stupid and frustrating that you could wind up in a situation where a super straightforward piece of code causes crashes

#

you can probably reason about baking, but this

#

this is a disaster

#

we can all speculate about random shit

#

that can happen during the execution of this coroutine

#

but i'm sure you've already done that

#

so people who have never seen yoru game's codebase or even what scenes are being loaded aren't going to have extra insights

#

the underlying problem is that Scenes are bad

#

just consider it

#

1.6% that you observe. it's possible that many, many users will eventually see this bug and drop out

warm yarrow
#

okay, I'll keep that in mind, but I'm sure most of the unity developers use scenes

polar marten
#

which is why i find crashes like these so frustrating

neat lagoon
#

I have used scenes with no issues for nearly all my projects, albeit I generate and populate them at runtime. I do still use pre-populated scenes for things like levels and have never encountered issues.

warm yarrow
#

and they find a way to do that without issues

muted grove
polar marten
#

like 1.6% error rate isn't small - people who stop playing stop generating data, so it's possible to observe 1.6% reports for an error that, eventually, 100% of users experience

eager yacht
#

I've never had issues with Scenes

muted grove
#

like a windows C/C++ runtime kinda deal

polar marten
mental rover
polar marten
#

like DontDestroyOnLoad, "brain" scenes, etc. etc.

#

most unity developers ship 0 games

#

and you have, you have a game that's live with a finger pointing right at scenes!

#

i mean that's what the error message is saying. "this seemingly straightforward and obvious pattern, i'm just going to decide it doesn't work for you, because scenes"

#

one of the requirements i have for people who use an sdk i develop is that they have only one scene lol

#

because it's SUCH a common problem

#

and 100% of the games that use this sdk will be shipped, so there's no point in letting people "organize" or whatever

#

they can organize using prefabs

polar marten
#

that said, the workflow i'm describing is literally dragging and dropping prefabs into a scene, and then using SetActive wherever you would do scene loading. that's it, that's the whole idea

#

you get to eliminate a ton of other code by doing things this way, so it is definitely ROI positive

warm yarrow
#

I think that would work for a small game that doesn't need complex memory management

polar marten
#

the number of lines of code between this method i'm suggesting and scenes would not change, in order to do "memory management"

warm yarrow
#

but I wouldn;t be able to set it active again

#

because it was destroyed

polar marten
#

all things you've done a million times before

warm yarrow
#

and that would freeze the application unless I used Resources.LoadAsync or asset bundles

polar marten
#

that said, i think you should try to not juggle the memory like this unless you really have to. for mobile devices, you will get higher yield compressing your textures, mesh combining with an asset, atlasing, etc. than futzing about with all of this

polar marten
#

async doesn't mean not freezing

#

if you want to throw up a loading thing

#

you can do it. setactive on a loading UGUI panel

#

the progress bar will freeze, but it does that anyway, in both scenarios

hardy wren
#

hello is there a way to change FixedTimeStep from script?

warm yarrow
#

hmm you can get animated progress bar with using load async so there's no way it completly freezes the application

polar marten
#

the key difference between what i'm describing and what you're describing with SceneManager is bugs

#

you know i'm talking about stuff that doesn't cause bugs!

neat lagoon
eager yacht
#

Can you guys move this into a thread in case others have questions?

polar marten
# warm yarrow hmm you can get animated progress bar with using load async so there's no way it...

if you do not observe "freezing" with async loading, you won't observe "freezing" with setactive on a gameobject in your scene. however, as you know, you DO see freezing with SetActive on a game object in certain circumstances, and that same freezing IS occurring when loading a new scene with that same game object active for the first time. loadasync's superpower is dealing with assets that are on disk and turning them into something that the game engine can use, which i agree is valuable and can reduce freezing

#

but here's the thing: a user will literally never complain about stuttering during a loading bar on screen - the amount of total time they're waiting will be the same regardless of whether or not you use scenes or prefabs or anything - whereas they will stop playing if your game crashes

#

@warm yarrow so what i am basically saying is: scenes are useful but they are full of bugs.

#

they're full of bugs that make people quit

#

it's your prerogative, it's your game

warm yarrow
#

I appreciate your feedback

radiant notch
#

Hello fellas, im currently losing my sanity trying to make a "Spell inventory" or something similar to World of warcrafts spell system. I want to be able to drag and drop available spells onto a hotbar and use the spells from there. But i cannot find any good tutorials for this. Does anyone have a good tutorial for this? or is someone willing to be my teacher and get paid?

swift falcon
#

@radiant notch did u still need help?

radiant notch
#

ya

#

@swift falcon

swift falcon
#

Can i private msg u?

radiant notch
#

ofc

fiery oracle
#

i am trying to get the tile coordinates of a tile clicked, using the built in Unity tilemaps, however for some reason i am always getting the same position:

#
Vector3Int tilemapPos = tilemap.WorldToCell(Camera.main.ScreenToWorldPoint(Input.mousePosition));           Debug.Log(tilemapPos); // always returns (-1, 1, 0)
tired egret
#

how do I reset the model after an animation?

I call

player.animator.Play("DeathAnimation", -1, 0f);

then the body has the effect of laying on the floor, then after 5-6 seconds I want to "respawn" the player but he's stuck in the lying down position

potent sleet
#

debug the raycast

fiery oracle
tired egret
#

i might have figfured it out

potent sleet
wintry stone
#

does anyone know how to change a value over time while being able to modify It? I have a function that that when called, will lerp a value over to 3 over 1 second. The only problem is if I call this function again say .5 seconds before the other ends the values get messed up. I need to be able to call the function again so if you call it half a second after the first it adds to the other value so it than takes 1.5 seconds to lerp to 6 can anyone help?

leaden ice
#
float current = 0;
float target = 0;
float speed = 1;

void Update() {
  current = Mathf.MoveTowards(current, target, speed * Time.deltaTime);
}

void SetTarget(float newTarget) {
  target = newTarget;
}```
wintry stone
#

Ok will try this thanks a bunch! I appreciate it

distant glen
#

I've included some code of mine (that doesn't work) but it's just there as a reference.

Let's say I have three scripts. PanelsManager, PanelsParent, and ItemPanel.

PanelsParent serves as a parent to instantiated ItemPanel prefabs.

ItemPanel prefabs have the ItemPanel script, which takes information about Items in the player inventory and displays them in the ItemPanel.

PanelsManager takes care of adding and removing ItemPanels as children to the PanelsParent Transform.

I have no problem instantiating one panel for each Item in the players inventory.

However, what I want to do, is only display one panel per item type. For example, if I have three swords in my inventory, and two shields, two panels will be instantiated, one panel for a sword, and one panel for a shield.

My script isn't working for this. It will display the first item, but after adding a second, no panels will display at all.

silver lichen
#

Has anyone had a similar problem using the Unity Localization Package? Every time I save I get this error:

Failed to find entry-points:
System.Exception: Unexpected exception while collecting types in assembly `Unity.Localization.Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null` ---> Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'Unity.Localization.ThirdParty.Editor, Version=12.0.0.0, Culture=neutral, PublicKeyToken=null'
  at Mono.Cecil.BaseAssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference name, Mono.Cecil.ReaderParameters parameters) [0x00105] in <ebb9e4250ed24cbfa42055e3532ef311>:0 
  at zzzUnity.Burst.CodeGen.AssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference name) [0x00039] in <a2dd15248a25411e914af2a2c82fb63f>:0 
  at Burst.Compiler.IL.AssemblyLoader.Resolve (Mono.Cecil.AssemblyNameReference name) [0x00079] in <a2dd15248a25411e914af2a2c82fb63f>:0 
  at Mono.Cecil.MetadataResolver.Resolve (Mono.Cecil.TypeReference type) [0x00038] in <ebb9e4250ed24cbfa42055e3532ef311>:0 
  at Mono.Cecil.ModuleDefinition.Resolve (Mono.Cecil.TypeReference type) [0x00006] in <ebb9e4250ed24cbfa42055e3532ef311>:0 
  at Mono.Cecil.TypeReference.Resolve () [0x00006] in <ebb9e4250ed24cbfa42055e3532ef311>:0 
  at Burst.Compiler.IL.Server.EntryPointMethodFinder.CollectGenericTypeInstances (Mono.Cecil.TypeReference type, System.Collections.Generic.List`1[T] types
...

I searched in some forums, but I didn't find the solution. (Full stack-trace: https://gdl.space/sigopoqoza.coffeescript)

next crescent
#

A little confused, the documentation says LineRenderer.GetPositions should be given an out keyword parameter but it's returning an error, what's going on?

polar marten
#

it looks like your project is in some jeopardy. do you use source control?

polar marten
somber nacelle
next crescent
next crescent
somber nacelle
leaden ice
#

the docs might be out of date or just wrong

#

According to mine it's just a regular parameter, no out

#

out wouldn't really be needed for an array parameter anyway, since arrays are reference types. I think the docs are just in error

next crescent
#

Doesn't exist?

leaden ice
#

mouse over GetPositions

next crescent
#

oh whoops

#

Ah right

polar marten
#

you are looking at the docs for an older version of unity than you are using

leaden ice
#

Nah the docs are actually just wrong

polar marten
next crescent
#

How quirky

#

Thanks though, appreciate it

leaden ice
#

Docs for 2022.2 say out but Rider says no out.

somber nacelle
#

yep, just checked 2023 and there's no out param but the docs say there is

leaden ice
#

I reported the doc page as incorrect, not that this has ever yielded any results in recent memory ๐Ÿ˜†

polar marten
leaden ice
#

Funnily enough I'm reading 1984 right now and there's a lot of mention of "memory holes"

#

It seems like this is a memory hole ๐Ÿ˜†

tired egret
#

what am i doing wrong? i confirmed the two objects are in layers "Bullet" and "DeadPlayer", yet they are still colliding?

somber nacelle
#

are you looking at the correct physics settings? if you're in 2d make sure you're modifying the matrix in the Physics2D settings

#

also not a code question

tired egret
#

ok ty let me see

#

thank you! i think that's it (it wasn't set in 2D)

#

sorry i didn't know

silver lichen
hard sparrow
#

No motion is being produced. Anyone know why? The idea is curved movement.

potent sleet
#

debug values

hexed pecan
fiery oracle
#

np, was just wondering if i was missing something obvious

potent sleet
#

did you try to just set it to 0 since that seems to be your Z

hard sparrow
hexed pecan
hard sparrow
#

Hm so all the time values are coming out correctly... Is there something wrong with the AnimationCurve?

wide dock
#
using UnityEngine;

public class MapRules : MonoBehaviour {
    // Set up in inspector on each map if required
    [SerializeField] private bool _canTP;
    [SerializeField] private bool _canAttack;
    ...
    
    private static int _mapRules; // Up to 32 rules (1 << 31)
    public static bool canTP {
        get => (_mapRules & (1 << 0)) == 1;
        private set => _mapRules = value ? _mapRules | (1 << 0) : _mapRules & ~(1 << 0); 
    }
    public static bool canAttack {
        get => (_mapRules & (1 << 1)) == 1;
        private set => _mapRules = value ? _mapRules | (1 << 1) : _mapRules & ~(1 << 1); 
    }
    ...

    private void Awake() {
        UpdateRules();
    }
    private void UpdateRules() {
        canTP = _canTP;
        canAttack = _canAttack;
        ...
    }
}

Yo, I've been thinking of a way to set up different rules on each map of my game and came up with such an idea, but I don't really yet fully understand what properties are in C#
Is my understanding here, as to how should I use them, correct or should I do it in some other way instead?

glacial halo
#

I am having such a weird brain blockage at the moment, and embarrassingly it's something I always seem to have a problem with. lol.

Could someone point me in the right direction on this one please?

I have a ray shooting out from the camera that hits an object, and I'm trying to get the object to move to the player, but for the life of me I can't figure out how.

Here's the code, I know that it's massively messy, but atm I just want to get it to work. lol.

#

bare with me.......bloody character limit. lol.

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.

glacial halo
#

Ah didn't know about that command. lol.

lucid valley
glacial halo
hard sparrow
#

I just can't get animation curves to do anything for me. There are tutorials, but none of them have to do with moving an object along a curved path

#

Even asked chatgpt, it also doesn't know what's wrong, lel

lucid valley
#
[Flags]
public enum MapRules
{
    None = 0,
    CanTP = 1 << 0,
    CanAttack = 1 << 1
}

public static bool CanTP {
        get => (_mapRules & MapRules.CanTP) == 1;
        private set => _mapRules = value ? _mapRules | MapRules.CanTP : _mapRules & ~MapRules.CanTP; 
    }
wide dock
lucid valley
#

but yeah properties i think are ok for that

#

some people might say only have those be getters and use a function to set instead

public static bool CanTP => (_mapRules & MapRules.CanTP) == 1; 

public void SetTpState(bool state)
{
    _mapRules = state ? _mapRules | MapRules.CanTP : _mapRules & ~MapRules.CanTP;
} 
hexed pecan
#

The fact that you say "no motion" makes me wonder if it runs at all

hard sparrow
#

Basically what's happening is the object immediately teleports right to the end point, or very close to the end point. Then doesn't do anything else. And it's being caused by the coroutine because when I comment it out, it just sits at the start position

hexed pecan
hard sparrow
#

Only thing I can think of is the curve.Evaluate is being weird

hard sparrow
hexed pecan
#

In your current while loop, you are updating the gameObject's position before you have changed _startPosition

#

Isn't if(_endPosition != transform.position)
supposed to be if(_endPosition != targetTransform.position)?

hard sparrow
wide dock
lucid valley
wide dock
#

I see

#

good

#

thanks

cedar pivot
#

how can i make a freekick system for unity

hard sparrow
#

If you wanted to use an animationCurve to move an object in an arc, wouldn't you do this?
transform.position = new Vector3(_startPosition.x + xCurve.Evaluate(elapsedTime), _startPosition.y + yCurve.Evaluate(elapsedTime), 0);

potent sleet
#

3D or 2D

#

myriad of ways to do it

cedar pivot
hard sparrow
#

lol, don't use that. I'm trying to use it and I can't get it to work

cedar pivot
#

oh xd

#

hmm

potent sleet
#

you probably want physics + forces

cedar pivot
#

yeah

hard sparrow
#

Idk, football game using set curves could be pretty fun

potent sleet
cedar pivot
hard sparrow
#

Imagine a pause-and-play football game where you have to choose the right curve to kick the ball in, like a strategy game

potent sleet
#

what kinda view like this ?

#

my picasso skills

#

but um, like bar to charge shot ?

#

shoot infront of goal?

cedar pivot
hard sparrow
#

Good luck, curves are apparently the hardest thing in unity

cedar pivot
#

this camera position is same with my project

knotty sun
hard sparrow
cedar pivot
#

can chatgpt do this xd

#

im gonna try

potent sleet
knotty sun
potent sleet
#

break it down to smaller tasks you need to get done @cedar pivot

#

you have a very open ended question

#

too many abstact ideas floating , we need to know specifically what mechanic your first working on and need help with

hard sparrow
cedar pivot
tough storm
#

random question, how do we feel about the built-in unity character controller component

knotty sun
# hard sparrow

you do not need to understand the underlying math to be able to implement the algorithm

potent sleet
hard sparrow
hexed pecan
#

Bezier curve is just a few lerps

hard sparrow
#

fine, I'll do math witchcraft

hexed pecan
tough storm
knotty sun
hard sparrow
hexed pecan
#

And the time value of the keyframes too.

tough storm
#

here's an interesting question, if you had to have a collection of default components, almost like a template for a 3D game, what would you use? i'd probably use cinemachine, character controller, and then i guess fill in the gaps with stuff like healthbar/resourcebar scripts that ive made a million times

hexed pecan
wide dock
#
    [Flags] private enum MapFlags {
        None = 0,
        CanTP = 1 << 0,
        CanAttack = 1 << 1,
        CanOpenBook = 1 << 2,
        CanUsePotions = 1 << 3,
        ResetEffectsOnLoad = 1 << 4
    }
    [SerializeField] private MapFlags _mapFlags;
    private static int _mapRules; // Up to 32 rules (1 << 31)
    public static bool canTP => (_mapRules & (int)MapFlags.CanTP) == 1;
    public static bool canAttack => (_mapRules & (int)MapFlags.CanAttack) == 1; 
    public static bool canOpenBook => (_mapRules & (int)MapFlags.CanOpenBook) == 1;
    public static bool canUsePotions => (_mapRules & (int)MapFlags.CanUsePotions) == 1;
    public static bool resetEffectsOnLoad => (_mapRules & (int)MapFlags.ResetEffectsOnLoad) == 1;

    private void Awake() {
        _mapRules = (int)_mapFlags;
    }

I am kinda confused..
I set up CanTP, CanAttack and CanOpenBook in the inspector, when debuging _mapRules, it's correctly showing 7 (1+2+4, first three flags) but when debugging all the properties, only canTP shows true while the rest is false.
I must be blind, can someone show me what am I doing wrong here?

#

oh..

#

I spotted it, nwm.

#

shouldn't be ==1 everywhere

#

!=0

tough storm
#

was about to say that

lucid valley
#

though i'm not the best with flags

tough storm
#

also, ive never seen that [Flags] property before

wide dock
lucid valley
#

and i usually just cheap out and use _mapRules.HasFlag(MapFlags.CanTP); (if you make _mapRules into MapFlags type)

#

but it is worse performance than doing it manually

tough storm
#

wut, tahts a function?

#

how much worse tho

wide dock
tough storm
lucid valley
wide dock
#
  • in inspector
lucid valley
#

though i gave the bit shift example

tough storm
#

absolutely wild, cant believe ive been doing it manually this whole time

lucid valley
#

basically multi bool

whole yew
#

how can I make my volume setting save through scenes?

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SoundManager : MonoBehaviour
{
    public static SoundManager Instance;

    [SerializeField] private AudioSource musicSource, effectsSource;

    private void Awake()
    {
        if (Instance)
        {
            Destroy(gameObject);
            return;
        }
        Instance = this;
        DontDestroyOnLoad(gameObject);
    }

    public void PlaySound(AudioClip clip)
    {
        effectsSource.PlayOneShot(clip);
    }

    public void ChangeMasterVolume(float volume)
    {
        AudioListener.volume = volume;
    }
}
#

currently, I have a sound manager like this and its in the main menu scene, but when loading into another scene it seems to reset the audio back to 100%

lucid valley
whole yew
#

the function "ChangeMasterVolume"

#

gets called by another script anyways

#

that was just a test sorry i forgot to remove that from the code

tough storm
#

you could use the PlayerPrefs system

#
void SavePrefs(float masterVolume,...){
  PlayerPrefs.SetFloat("masterVolume",masterVolume);
  
  //best practice to prevent dataloss is to store floats as a string, this avoids floating point error
  PlayerPrefs.SetString("masterVolume",string.Parse(masterVolume));
  //believe this saves to disc, not sure if needed or not
  PlayerPrefs.Save();
}```
#

i would also recommend looking into the unity mixer if you haven't, that could help you create even more options for volume/mixing

distant glen
#

Help needed. For some reason, when I interact with my soil when it's SoilState.Harvestable nothing happens. SoilState.Overgrown functions as intended but I can't even get the Debug.Log to show for SoilState.Harvestable. I've tried removing the switch and replacing it with if statements, I've tried just having the code say if (currentSoilState == SoilState.Harvestable) { Debug.Log("Working") } but I get nothing. I can verify that the soil's state is set to harvestable because the inspector clearly shows it.

lucid valley
distant glen
#

Setting them from here.

potent sleet
distant glen
potent sleet
lucid valley
deft cairn
#

Hello how can I create a 3d tilemap?
I tried creating a lot of square planes using 2 for loops but it kills my CPU and RAM. Is there an optimized way to create it?
I want to make something like this

lucid valley
# distant glen No

how are you calling SickleSoil()? as that doesnt seem to be working if you are not getting any log

deft cairn
#

and thank you for replying

potent sleet
#

or you lag once it's generated

deft cairn
#

this is my map, it's composed of a lot of squares

#

every square is a tile

potent sleet
distant glen
# lucid valley wait, sorry is "Nothing to cut." being logged?

To clarify, "Nothing to cut" is logged when the soil is activated on any other state other than Overgrown and Harvestable. If the currentSoilState is SoilState.Overgrown the code functions as intended. The code for SoilState.Harvestable is exclusively not working.

potent sleet
#

it doesn't seem too big tho

deft cairn
deft cairn
lucid valley
potent sleet
distant glen
lucid valley
distant glen
distant glen
#

It's only Harvestable it doesn't show for.

lucid valley
#

well that means that some check is blocking SickleSoil running when it has the Harvestable state

#

i can't help you much more without seeing the full code

#

!code, you can paste it to one of those sites if you need further help

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.

distant glen
tough storm
#

hey, i've got a strange issue, im using omnisharp with VSCode and for some reason it doesnt know what cinemachine is. This compiles though

somber nacelle
#

regenerate project files and restart vs code

tough storm
#

just thought to try that, its working now

simple mountain
distant glen
#

Can anyone identify why my code is throwing an error on Line 113?

https://gdl.space/lidiqatabe.cs

This script was functioning as intended, but I moved the script to another GameObject, and since then, it has been throwing a NullReferenceException on Line 113 which seems to indicate that "selectedSeedListPanel" is equal to null.

What I don't understand is why moving it to another GameObject would cause the issue, as everything is still being properly instantiated, and everything else is functioning correctly.

Moving it back to its original GameObject resolves the issue, but I need to move it as it was not an appropriate place to have the script.

lucid valley
somber nacelle
#

is not as

lucid valley
distant glen
# distant glen Can anyone identify why my code is throwing an error on Line 113? https://gdl.s...

it can't be that it's not reaching the seedContained variable in selectedSeedListPanel, because the instantiated panel contains it, so it must be that selectedSeedListPanel is equal to null. However, when one of the panels is instantiated, the class subscribes to that panel's callback, so that when it's clicked, the selectedSeedListPanel is updated to that panel.

Moving the script shouldn't change that, and the fact that I'm getting the error means that the callback is functioning...

somber nacelle
#

are you certain that the updateSelectedSeedPanelCallback is being invoked with a non-null value passed as a parameter?

distant glen
somber nacelle
#

0 references
so where are you calling that method from?

distant glen
#

When clicking this button.

#

The script (SeedListDisplay) was originally attached to UI_SeedPrompt and I get no errors when it is attached to this GameObject. The problem is non-existent.

#

However, I re-attached it to UI Manager instead, as UI_SeedPrompt is not always active.

#

Since attaching it to UI Manager, this is when the NullReferenceException started appearing.

somber nacelle
#

i'd place some breakpoints and make sure that the methods are being executed in the order you are expecting them to be

distant glen
#

Well, clicking a Frame executes the callback method. I can't see any reason why the seedListPanel shouldn't be updated with the rest of the code. It's not being cleared anywhere else.

deft cairn
simple mountain
#

How are you creating this?

spark wedge
#

I'm interested in implementing sprite generator or something
Not sure what to call it but you can see that each can be connected by a that brown part(root)
I'm interested to know if there's an interesting/fast method to implement it without do it statically

Like a mesh generator or a spline maybe and if it's in the case of spline, would it be easy to implement(Within a short duration of time)?

next crescent
#

The shape the linerenderer I have is rendering is a little off kilter, but all the points are whole numbers. What's going on here?

next crescent
spark wedge
next crescent
#

Not in the slightest lel

pearl otter
#

I'm trying to make it so when the player kills an enemy, after 3 seconds the enemy will sink into the ground but the ground is interfering with the enemy even though the enemy's collider is disabled. And in the Scene when the in playing, I am able to move the Enemy's position through the ground manually with no problems. Any idea why? https://streamable.com/a950eu

Vector3 targetPos = new Vector3(transform.position.x, transform.position.y - 3, transform.position.z);
transform.position = Vector3.Lerp(new Vector3(transform.position.x, deathPos.y, transform.position.z), targetPos, 0.1f * Time.deltaTime);
if (transform.position == targetPos) Destroy(gameObject);```
distant glen
simple mountain
distant glen
pearl otter
simple mountain
#

I think you got something wrong about the lerp function

pearl otter
#

Which part of it? I followed the documentation

simple mountain
#

if(getsKilled)
{
int steps = 20;
Vector3 pos = transform.position;
Vector3 goal = new Vector3(pos.x,pos.y-3,pos.z);
Vector3 interval = (goal-pos)/steps;
getsKilled =false;

}
if(isdying)
{
    steps--;
    transform.position+=interval;
  if(steps==0)
  {
    isdying =false;
    GameObject.Destroy(gameObject);
  }
}
//Try this I know this can be simplified but having more readable code is worth it when you have an error that you can t find
pearl otter
#

Why aren't you using lerp? ๐Ÿค”

simple mountain
#

wait this is false as well

#

I am

pearl otter
#

If you look at the video, it really looks like the enemy is colliding with the ground

simple mountain
pearl otter
#

I just sent the relevant code

simple mountain
#

idk I'd be great if you tried mine and if it doesn t work you can still use urs

pearl otter
simple mountain
#

the thing I wrote is just like lerp I think

visual flare
#

anyone knows what that does?

pearl otter
#

@simple mountain It works, thanks!

visual flare
#

that thing is chewing 6ms

stuck forum
#

Just experimenting randomly with some things. Would this be a good thing to do? Only thing vs complains about is Cannot initialize type 'float' with a collection initializer because it does not implement 'System.Collections.IEnumerable' (Which sadly I need a dll for it) but then again, is this a valid way of doing it?
Edit: maybe it's not a dll? Potential fixes aint giving any useful fixes though

        float[] deltas =
        {
            new float { firer.x - target.x },
            new float { firer.y - target.y },
            new float { firer.z - target.z }
        };```
#

firer and target are just vector3 parameters of the method

#

wait

#

nvm still dont know

mossy snow
#

float[] deltas = { firer.x - target.x, firer.y - target.y, firer.z - target.z };
but I wouldn't do it like that, why allocate an array?
Vector3 deltas = firer - target;
You can still iterate through deltas if you need to do whatever it is you're doing with deltas

stuck forum
#

only thing i wanted to do is sort which delta had the highest value, so i thought OrderBy would do the trick

#

hence why i wanted to make an array

mossy snow
#

float maxDelta = Mathf.Max(firer.x - target.x, firer.y - target.y, firer.z - target.z);

#

you can slap in abs in there if you're looking only at magnitude

stuck forum
#

huh, didn't know Mathf.Max was a thing

#

TIL

mossy snow
#

technically the optimal solution is two maxes imo, since the 3 parameter version allocates an array which should be avoided in a hot code path which it sounds like this will be

stuck forum
#

ouch... that's not good

#

hmm

lime niche
#

Hello!, im really new to unity, is there a way to code in lua or is it only just c#

lime niche
#

Ah okay

cold bolt
#

How do I make a script that increments a value by one when a gameobject is set to active?

north moss
#

Hello is there a way to add a scriptableObject into a non-Monobehavior? (Without adding it by constructor)

potent sleet
dusky lake
# spark wedge I'm interested in implementing sprite generator or something Not sure what to c...

Look at this video: https://www.youtube.com/watch?v=v7yyZZjF1z4 it might not fully be what you want but should be a good starting point

Learn how to create procedurally generated caverns/dungeons for your games using cellular automata and marching squares.

Source code:
https://github.com/SebLague/Procedural-Cave-Generation

Follow me on twitter @SebastianLague
Support my videos on Patreon: http://bit.ly/sebPatreon

โ–ถ Play video
tight ice
#

hi, i'm trying to do
float waveHeight = WaveManagerGerstner.instance.GetWaveHeight(transform.position);

but it's mad that i'm feeding it the transform.position. it says: There is no argument given that corresponds to the required parameter '_y' of 'WaveManagerGerstner.GetWaveHeight(float, float, float)'

the getwaveheight function in question is:

` public Vector3 GetWaveHeight(float _x, float _y, float _z)
{
Vector3 gridPoint = new Vector3(0, 0, 0); //vertexData.vertex.xyz;
Vector3 tangent = new Vector3(1, 0, 0);
Vector3 binormal = new Vector3(0, 0, 1);
Vector3 p = new Vector3(_x, _y, _z);
Vector3 currentPosition = GetWaveAddition(p, gridPoint, ref tangent, ref binormal);
Vector3 normal = Vector3.Normalize(Vector3.Cross(binormal, tangent));

    Vector3 displacement = GetWaterDisplacement(_x, _y, _z);

    for (int i = 0; i < 3; i++)
    {
        Vector3 diff = new Vector3(_x - currentPosition.x, 0, _z - currentPosition.z);
        currentPosition = GetWaveAddition(diff, p, ref tangent, ref binormal);
    }

    return currentPosition;
}`

i'm quite confused; why is it not happy with what i am feeding getwaveheight function?

dusky lake
#
var pos = transform.position;
float waveHeight = WaveManagerGerstner.instance.GetWaveHeight(pos.x, pos.y, pos.z);
dusky lake
tight ice
#

Oh duh! Thank you.

hard sparrow
#

@hexed pecan @knotty sun I implemented bezier curves and it works perfectly and is way more flexible. Thanks for the help.

#

(turns out doing your own bezier curves is way simpler than trying to finagle unity AnimationCurve)

lime niche
#

How good is unity's navigation and pathfinding?

quaint rock
#

depends on your usecase

#

if you have navmesh based navigation for 3d its fine

#

or as long as you can bake the navmesh and do not need to make large changes to it at runtime

lime niche
#

ahh okay

quaint rock
#

i have used it for some projects, and i have just implemented my own pathfinding system on others. depends on the needs at the time

lime niche
quaint rock
#

i needed grid based and i needed to modify it at runtime

cold bolt
full scaffold
lime niche
wispy wolf
plucky karma
stuck forum
#

Idk why i did that to begin with

potent sleet
#

show code

fathom lynx
#

hey, i have this variable called speed in a base class and in the child im trying to do animator.SetFloat("speed", Mathf.Abs(direction)); but it cant find the float speed

#

i couldnt find anything on the docs

quaint rock
#

its setup in the animator its self in parameters

fathom lynx
quaint rock
#

yeah the various animator.SetX methods are for setting paramaters on your animator controller

fathom lynx
#

ahh, so i should rename it to like animation_speed right?

quaint rock
#

the string you give it depends on what you have setup in your animator controllers parameters

#

the docs give a example of usage

summer pecan
#

I am having an issue with Pathfinding. The default rotation for my character models is (-90,0,0) however this happens when running the following script:

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

public class NPCWalk : MonoBehaviour
{
    public float updateFrequency = 2.0f; // Time in seconds between updates
    public float speed = 2.0f; // The NPC's speed

    private UnityEngine.AI.NavMeshAgent agent;
    private float timer;

    void Start()
    {
        agent = GetComponent<UnityEngine.AI.NavMeshAgent>();

        transform.rotation = Quaternion.Euler(-90, 0, 0);
    }

    void Update()
    {

        // Update the destination every "updateFrequency" seconds
        timer += Time.deltaTime;
        if (timer >= updateFrequency)
        {
            timer = 0;
            SetRandomDestination();
        }
    }

    void SetRandomDestination()
    {
        Quaternion currentRotation = transform.rotation;
        float y = currentRotation.eulerAngles.y;
        float z = currentRotation.eulerAngles.z;

        transform.rotation = Quaternion.Euler(-90, y, z);

        Vector3 randomDirection = UnityEngine.Random.insideUnitSphere * 20.0f;
        UnityEngine.AI.NavMeshHit hit;
        UnityEngine.AI.NavMesh.SamplePosition(transform.position + randomDirection, out hit, 20.0f, UnityEngine.AI.NavMesh.AllAreas);
        agent.destination = hit.position;
        agent.speed = speed;
    }
}
cinder kindle
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AttackManagerScript : MonoBehaviour
{
    BlazeAI blaze;
    public HealthManagerScript healthManager;

    public void AttackUnit(int damagePoints)
    {
        
        blaze.Hit(gameObject, true);
        healthManager.healthPoints -= damagePoints;
        Debug.Log(healthManager.healthPoints);
    }

}

I've tried fixing this so many times but it keeps throwing the same error.. If anyone could help that would be greatly appreciated.

Error

NullReferenceException: Object reference not set to an instance of an object
AttackManagerScript.AttackUnit (System.Int32 damagePoints) (at Assets/AttackManagerScript.cs:13)
rain minnow
#

Look for any reference variables on that line and make sure they are assigned a value . . .

rain minnow
deep willow
#

is an empty slot in a list null? If so, is this how I would check?

        {
            if (gameManager.spellQueueList[i] != null)
            {
                Debug.Log("test");
                filledQueueSlots++;
            }
        }```
frank pumice
#

ok

#

whichever silly man told me to make a capsule collider array you have screwed me over for 2 weeks

#

for some reason this fucks with networking

#

are there ways other than manually defining a long list of [SerializeField] CapsuleColliders now

#

whatever ill do it

dusk apex
dusk apex
deep willow
#

hmm okay so its not working because when i do this:

gameManager.spellQueueList.Add(gameObject);

the object is still not being added for some reason

#

it stays null

frank pumice
#

rn

dusk apex
#

Is there an error? @deep willow

frank pumice
#

it isnt the for loop

#

seems that it just isnt happy with multiple colliders

#

or collider array

#

one of the two

dusk apex
muted grove
#

Classes that are inheritting another class inherit everything from that class, right? If so, how does Transform inherit Component if Component has a Transform as a property?

dusk apex
dusk apex
#

Transform just so happens to also be a component. So it'll have a reference to itself.

#

Through the inherited Component class

dusk apex
#

An object will always have a transform component

#

Implies "Unity Game Object"

muted grove
#

im trying to understand how scripts access references so im going down the inheritance chain

dusk apex
#

The property merely returns a reference of the actual component on the object.

muted grove
distant glen
#

I've attached my code and a video demonstrating the issue.

The "add item" button places two seeds in the players inventory of a different type.

The code instantiates the panels you see beneath the "plant seed" UI in the GIF image.

The intention is that no matter how many seeds you have in your inventory, only one panel will instantiate per seed, so the screen is not flooded with panels.

However, as the GIF demonstrates, selecting the right-most seed causes a bug where only one panel is instantiated despite multiple seeds being in the player inventory.

Selecting the left-most seed causes the panels to display correctly again. I do not understand.

Full code is here: https://wtools.io/paste-code/bJzl

west sparrow
#

They finally managed it with rigidbody, but they do have their eyes on transform..

muted grove
#

or do i really only need the docs

west lotus
#

!learn

tawny elkBOT
#

๐Ÿง‘โ€๐Ÿซ Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

muted grove
#

most of those are beginner tutorials on how to make template games though, right?

west sparrow
west lotus
#

There are advanced concepts as well. You wont learn the actual internals since well unity is closed source. But plenty of the packages such as the SRPs are open on github

dusk apex
# muted grove from https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/...

I'm not sure what you're looking into or asking, specifically. Properties are simply methods under the hood. In this instance, it returns a reference to the Transform component on the object. I do not know the underlying means of which it acquires the reference. Could probably just assume it caches it once after the component is added to the object or acquires it after first call to the transform property (they aren't likely calling get component for Transform every time the property is used - if so, they need to stop doing so as the Transform of an object cannot change). Knowing what you're concerned about would better help us answer your question. Likely there's some sort of misunderstanding.

muted grove
#

would learning CLR or .NET help with programming in unity or am I just about fine with random searches to leanr.microsoft.com or "learn c# in 4 hours," "this is what delegates are!" kind of videos

#

if i were to look up how c# handles garbage collection would that be helpful

dusk apex
#

Build your game then profile afterwards.

muted grove
#

alright

#

thanks

west sparrow
cinder kindle
#
blaze.enemyToAttack.gameObject.tag = "Dead";

Is this how I would change a gameobjects tag? Because it's not working?

west sparrow
#

It has to be a tag already specified in the Editor, and caps matters for it

cinder kindle
west sparrow
unreal temple
#

like... put a log after it

#

or check with debugger

#

There are probably better ways to store if an enemy is dead btw.

cinder kindle
cinder kindle
opal pine
#

Hey guys. Having issues with lists atm and google isnt helping me with this one. It must not be a common issue.
Im getting all colliders with Physics2D.OverlapCircleAll and thats all working correctly but its not putting them into a list in order. Trying to find the first one in the list by foreach (Collider2D col in colliders) {} but watching in the inspector normally the 3rd or 4th collider will get thrown in element 2 in stead of becoming the new element 0. So when I remove an element (out of range) its no longer detecting the next furthest collider.

Is this intended? Doesnt seem to be a common issue that I can find.

main shuttle
opal pine
#

Sorry yes its an array. I was working with lists before. Here is the update function.

colliders = Physics2D.OverlapCircleAll(transform.position, range, mask);
        foreach (Collider2D col in colliders) {
            Debug.Log(col.name + " Has been found");
            if (selectTarget == targetSelect.First) {
                currentTarget = colliders[colliders.Length -1].gameObject;
            }
        }
        if (colliders.Length == 0) {
            currentTarget = null;
        }
    }
main shuttle
#

cs or csharp @opal pine

#

I don't understand the problem in regards to your story.

#

if (selectTarget == targetSelect.First) { this whole part is unspecified.
Then you set your target to the last one in the colliders array.

#

Your foreach seems fine.

opal pine
#

Very sorry for the sloppy screenshot.
As you can see on the inspector I've highlighted the 2nd element but in the Hierarchy its highlighting the last spawned gameobject

main shuttle
#

Why does the order of the hierarchy matter?

opal pine
#

Cause then it will select the next first gameobject.

dusk apex
opal pine
#

just trying to find the first one. But as the array gets smaller I want it to find the next "first" one. Not a random one in the list because its been added in the wrong element

dusk apex
#

What's "first one"?

#

I'm guessing the one that's in the lead?

main shuttle
#

But OverlapCircle would remove it the next frame anyhow.

opal pine
#

First spawned object. Yes in front

open thorn
#

I got a problem where one of my raycasts returns a false positive. It returns true when it collides with layers not defined in platformLayerMask variable, which is set to default layer in the unity editor.
But the weird thing is that my other raycast doesn't return a false positive...
Anyone knows what the problem could be?

private bool IsBlocked()
{
  RaycastHit2D raycastHit = Physics2D.Raycast(collider2D.bounds.center,               Vector2.right * movementDirection, platformLayerMask);
  return raycastHit.collider != null;
}

private bool IsGrounded()
{
  RaycastHit2D raycastHit = Physics2D.BoxCast(collider2D.bounds.center,               collider2D.bounds.size - new Vector3(0.1f, 0f, 0f), 0f, Vector2.down, 0.2f,       platformLayerMask);
  return raycastHit.collider != null;
}
dusk apex
#

Put some value on each object, then you'd be able to evaluate that object to see who's the highest priority

main shuttle
#

if (selectTarget == targetSelect.First) { this is either true for everything in the array or for none, it also uses nothing of what you are iterating over. So the foreach also doesn't make sense.

dusk apex
#

Else you'll need to have some way to weigh which object is first.

opal pine
#
public enum targetSelect {First, Last, MostHealth, LeastHealth, MostArmour, LeastArmour, MostShield, LeastShield}
    public targetSelect selectTarget;

That if (selectTarget == targetSelect.First) has nothing to do with the array being added. I just didnt think when you add something to an array it would be added in a random spot

dusty gulch
#

Hello guys
The main branch is old and it has alot of glitches so i want to delete it and make (The-work) branch to be the main branch
i dont whant to merge it becuase the main branch is very old and alot of glitches

main shuttle
opal pine
#

Well that doesnt help me haha. Its so weird that it just wouldnt add any new elements in the array at the end or the start.
Guess Ill have to do a check that grabs all objects then checks each one with distance rather then relying on it being added in order that is finds the colliders

main shuttle
opal pine
#

well that makes sense. And I thought this was going to be easy

main shuttle
main shuttle
open thorn
elfin vessel
#

What's a quick way to generate a mesh along a spline? A simple flat thing like a road will do.

#

My current code is

Mesh GenerateMesh()
        {
            Mesh outMesh = new();
            List<Vector3> verts = new();
            int pointsRange = ((int)math.floor(container.Spline.GetLength() * 10));
            for (int i = 0; i < pointsRange; i++)
            {
                container.Spline.Evaluate(i / pointsRange, out var pos, out _, out var up);
                verts.Add(pos + (up * grabLength)); //Add far point
                verts.Add(pos); //Add point on spline
            }
            int[] tris = Enumerable.Range(0, verts.Count - (verts.Count % 3)).Select(x => x).ToArray(); //The mod is to cut off the last triangle if there arent enough points
            outMesh.vertices = verts.ToArray();
            outMesh.triangles = tris;
            return outMesh;
        }
#

I am purposefully generating it only to one side

simple mountain
#

if that works that s pretty quick

elfin vessel
#

I'm making a mesh for a Gizmos Drawmesh here, but I can't find it anywhere in my scene, so I can only conclude im not doing somethign right

#

I also tried wiremesh in case it was being affected by backface culling

simple mountain
#

I've never used gizmos.drawwiremesh I would try

  • Debuging the outMesh.vertices.Length
    -Creating a mesh and looking at it in scene view with wireframe on
    -Writing out every point of the mesh and check if something is fishy
elfin vessel
#

Iโ€™m take a better look tomorrow

#

Thanks

barren void
#

How can I access the animation state from my animator through script, so that I can modify its speed?

mossy snow
#

enable parameter checkbox, set parameter via script

deft timber
#

animator.speed

mossy snow
#

that will affect all states

deft timber
#

animation["Idle"].speed for example

mossy snow
#

hmmm I think the animation clips are shared, so that would probably modify the clip's speed for all animators that use that state. I haven't tried that though

deft timber
#

Yea if you are using the same animation clip attached to different object i believe it'll modify the speed in both

coral kettle
#

does anyone know how I would do this? I have a value "20". I have another value that I will call "balance". what I want to do it lower 20 by 1 for every power of 10 "balance" that I have

#

I know it's logarithmic, but I don't know the syntax or how this would look in unity

#

in C# that is

lucid valley
#

i think that should work

near crown
#

Guys can you help me with an error that i'm getting?

lucid valley
#

sure, post the error and code

#

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

near crown
#

I am getting "NullReferenceException: Object reference not set to an instance of an object Player_Movement.Update () (at Assets/Scripts/Player_Movement.cs:28)"
with the line that references like
if (Input.GetKeyDown(KeyCode.LeftControl) && CoinScript.CoinCounter > 5)
{
RUN = 2f;
CoinScript.CoinCounter -= 5;
Invoke("Walk",RunTime);
}

#

I referenced the CoinScript

#

I have referenced it in the editor

lucid valley
#

line 28 the if?

near crown
#

and I still get this error

#

ya

lucid valley
#

you sure you are not changing CoinScript anywhere in code?

near crown
#

In what sense?

lucid valley
#

CoinScript =

#

or is it just being set in the inspector

near crown
#

I putted at the start CoinScript = GetComponent<Coin>();
just for autonomation

lucid valley
#

so does the gameobject that has the Player_Movement also have the Coin script?

near crown
#

Also what I'm trying to do is accessing a variable in the script

lucid valley
#

....then that is why it is erroring

#

GetComponent<Coin>() is returning null as that script isnt on that gameobject

near crown
#

UH I understood!

#

I should have done FindObject not component!

#

Ty now it works!

warm tendon
#

hi, i'm trying to procedural generate a map but i'm having problems with adding colliders, when i add a mesh collider it just goes like this

agile plaza
#

how difficult is the input system to learn ?

agile plaza
#

I am new to this and I am making a game for the global games jam

dusky lake
warm tendon
#

i did something, no idea what, but it's fixed now, thanks for responding though ๐Ÿ‘

#

also i think that i had put the mesh in the mesh collider property but again, i have no idea what i did

vagrant agate
deft cairn
#

Hello, is there a way of change color of the child image (Icon) when I hover the parent Buton?
Right now it changes the green circle color when I hover, but I also want to change the leaf icon color

agile plaza
#

How can I make a simple player character movement with old input system ?

deep fable
#

Performance of collider without rigidbody vs collider with static rigidbody?

somber nacelle
vestal oriole
#

Hi guys! can someone help me to convert an image? unfortunately I don't know how to program ๐Ÿ˜ญ thanks

#

I need to convert a .texture2D file to .exr

maiden fractal
next crypt
#

Hello, I want to create a static function that can be called by any class, it is supposed to compare the tag of something of any possible type to another tag and then basically assign something to another thing, no matter the type. As an example, I have the function

       if (tmproText.CompareTag(TagsManager.AchievementNameTag))
           {
               tmproText.text = achievement.Title;
           }```
i'd want to create a static function that looks like:
```cs
   void CompareAndAssign(firstThing, string TagToCompareFirstThingTo, thingLeftOfEqual, thingRightOfEqual)
   {
       if(firstThing.CompareTag(TagToCompareFirstThingTo))
       {
           thingleftOfEqual = thingRightOfEqual;
       }
   }```
So in my example, I'd basically only have to call CompareAndAssign(tmproText, TagsManager.AchievementNameTag, tmproText.text, achievement.Title)
However, I have no idea how this is possible, help would be very much appreciated, thanks in advance ๐Ÿ™‚
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.

next crypt
rain minnow
next crypt
rain minnow
#

everything derives from object but you'd have no idea what the actual type is. you can't confidently assign one value to another with receiving errors if they're aren't the same type . . .

#

you need to constrain the type to smth all of your input will have in common . . .

#

you're main goal is to compare tags. tag is a GameObject property, so why not use that type?

next crypt
rain minnow
#

that doesn't make sense; TextMeshPro is a component . . .

#

you can see that from your inspector . . .

next crypt
# rain minnow you can see that from your inspector . . .

So what can I do in order that my function works?

    void CompareAndAssign(object firstThing, string TagToCompareFirstThingTo, ref object thingLeftOfEqual, object thingRightOfEqual)
    {
        try
        {
            if (firstThing.CompareTag(TagToCompareFirstThingTo))
            {
                thingLeftOfEqual = thingRightOfEqual;
            }
        }
        catch
        {
            Debug.LogWarning(thingLeftOfEqual + " can not be assigned to " + thingRightOfEqual);
        }
    }

Based on what you said I tried to adjust my function, I decided to use object as GameObject is not compatible, like you stated, however how can I use CompareTag with the class object, is there and thing like firstThing.TryGetComponent<GameObject>(), that might be possible?

distant bloom
#

dawg wtf I dont even remember joining this server

#

โ˜ ๏ธ

next crypt
rain minnow
#

i said using object doesn't make sense because you don't know what the actual type is that you are passing in . . .

warm night
#

Hey, how can i change without script the transform of a child gameobject without changing his parent's transform..? It doesn't work for me ! :/

next crypt
warm night
#

fr ?

rain minnow
#

@next crypt what if the first param is a GameObject and the second param is a c# class? they're not compatible . . .

potent sleet
warm night
#

i have the case in another scenes, and it works pretty well in the inspector, but not on another scene, it's so weird

rain minnow
next crypt
potent sleet
warm night
#

yeah ikr :/

#

i'm gonna try to find out

#

thanks anyway

rain minnow
warm night
#

Yeah but in another scene, i'm not using animations, or code and i can move the child independently in the inspector, but not on my current scene, that's weird xD

rain minnow
rain minnow
swift falcon
#

Where is player model at?

next crypt
next crypt
warm night
rain minnow
warm night
#

I mean, the child object is "local" to parent, and i don't want that

rain minnow
#

that's just how parenting works . . .

next crypt
warm night
rain minnow
#

moving a parent will affect the child . . .

warm night
#

the first screen is the position of the player, and the second one, it's the position of the player after moving up the "graphics" child to the good Y pos

#

i swear it's weird bro

#

ok for some reason i just redid the manipulation as i did just for the screens, and it works

#

wtf

#

i'm not drunk xD

rain minnow
warm night
#

Yeah it was bugging

hollow bay
#

Hello, I don't know if this is the correct channel to post my code for review but I feel like I'm doing some stuff wrong (performance wise) with this code, I'd appreciate if anyone can pinpoint any bad practices in my code!

public class EnemyController : MonoBehaviour
    {
        [SerializeField] float attackRange = 5f;

        private void Update()
        {
            GameObject[] players = GameObject.FindGameObjectsWithTag("Player");

            Transform currentPlayer = GetClosestPlayer(players);

            if (GetDistance(currentPlayer) < attackRange)
            {
                print("Can attack");
            }
        }

        Transform GetClosestPlayer(GameObject[] players)
        {
            Transform nearestPlayer = null;
            float minDist = Mathf.Infinity;
            foreach (GameObject player in players)
            {
                float distance = Vector3.Distance(player.transform.position, transform.position);
                if (distance < minDist)
                {
                    nearestPlayer = player.transform;
                    minDist = distance;
                }
            }
            return nearestPlayer;
        }

        private float GetDistance(Transform player)
        {
            return Vector3.Distance(player.position, transform.position);
        }
    }
pine bronze
#

hello guys so i just finished watching a video about headbobbing and in the video the headbobbing is normal but mine is like this:
this the code that does the headbobbing:

private void HandleHeadbob()
    {
        if (!characterController.isGrounded) return;

        if (Mathf.Abs(moveDirection.x) > 0.1f || Mathf.Abs(moveDirection.z) > 0.1f)
        {
            timer += Time.deltaTime * BobSpeed;
            playerCamera.transform.localPosition = new Vector3(
                playerCamera.transform.localPosition.x,
                defaultYPos + Mathf.Sin(timer) * BobSpeed,
                playerCamera.transform.localPosition.z
            );
        }
    }
leaden ice
#

Remember BobSpeed is already taken account of with this: timer += Time.deltaTime * BobSpeed;

pine bronze
leaden ice
#

again

#

like I said

#

you're using bobSpeed there

#

he's using bobAmount there

#

different variable

pine bronze
#

oh

dawn dock
#

Hey so I've made a health system, mostly, but I'm struggling to add immunity for a certain amount of time after being hit. https://gdl.space/gicolawemi.cs Can anyone help?

pine bronze
leaden ice
#

and what code did you end up with

#

debug it

pine bronze
#

this is the code now:

if (!characterController.isGrounded) return;

        if (Mathf.Abs(moveDirection.x) > 0.1f || Mathf.Abs(moveDirection.z) > 0.1f)
        {
            timer += Time.deltaTime * BobAmount;
            playerCamera.transform.localPosition = new Vector3(
                playerCamera.transform.localPosition.x,
                defaultYPos + Mathf.Sin(timer) * BobAmount,
                playerCamera.transform.localPosition.z
            );
        }

and these are the bobbing amounts

leaden ice
#

this is really just you not being careful and not copying the code properly / paying attention to what you're doing

pine bronze
#

yeah sorry it works now

spring bobcat
#

Hello, I'm having a problem with getting my Player to the next scene. I put everything how it's supposed to be but still nothing is working, I don't know if I missed something or if something is wrong with the code.
(I put the Is Trigger on the object the player has to go through, and I put the scenes is build settings)

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

public class SceneRight : MonoBehaviour
{

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            int sceneBuildIndex = SceneManager.GetActiveScene().buildIndex;
            SceneManager.LoadScene(sceneBuildIndex + 1);
        }
    }
}
leaden ice
#

This is where you start debugging

#
Debug.Log($"Collided with {other.name} with tag {other.tag}");```
#

you can't just stare at code and guess. Debugging is the only way forward

rapid brook
dawn dock
leaden ice
dawn dock
#

I tested the immunity frames to be 100 on start, and the immunity frames went straight down to -0.02 in the console

vagrant agate
#

start a coroutine that waits X seconds and have a global boolean or use enums to track whether you should be immune

rapid brook
#

I assume you want to start a Coroutine after the character was hit that would trigger a variable "isImmune" and make it true , then after a certain amount of time, make it false again then in your collision system you check If isImmune is false

dawn dock
#

Yeah

#

Thanks Ill try that

leaden ice
#

you need to figure out which one you want.

#

and frames is probably not it

dawn dock
#

Yeah Im looking for seconds

leaden ice
#

get it straight in your head what you're dealing with

#

and make your code reflect that and clearly state it

#

to reduce confusion

dawn dock
#

Yeah my bad

rapid brook
#

Also, in your Coroutine don't use Wait for seconds, If you pause the game by making the Time.timescale = 0, your Coroutine will still run and set the bool back to false after the set amount of time

vagrant agate
#

you can def use waittforseconds. be smart be aware of your coroutines

#

store it or use StopAllCouroutines on the behavior

rapid brook
#

Using waitForSeconds is not a good idea if the game has a pause system, which most likely has, it's better to use WaitForFixedUpdate and have a value that increments until it reaches the amount of time the player should be immuned for

#

That, is considering the pause system just set the TimeScale to 0

summer pecan
# cinder kindle why is it -90?

Thatโ€™s how the model is, if the X is 0 theyโ€™ll be on their faces but if itโ€™s -90 theyโ€™re standing up

rapid brook
#

Something like this :

#

don't forget to add a yield break if the player is already immune, better safe than sorry

slender helm
#

Is there a proper way to transfer ownership of network game object from client to host and in opposite ? For some reason with this code I am getting, Client wrote to NetworkVariable ... without permission, Why I am getting this error, (I am trying to transfer ownership via Server rpc) ?

swift falcon
#

Hello i got this error in Google Play Console After trying to upload an aab file:

APK or Android App Bundle which has an activity, activity alias, service, or broadcast receiver with intent filter, but without the 'android: exported' property set. This file can't be installed on Android 12 or higher. See developer.android.com/about/versions/12/behavior-changes-12#exported

rain minnow
rapid brook
rain minnow
# rapid brook Oh, then replacing deltaTime by fixedDeltaTime should do it? I wasn't aware of t...

yeah, but there are many different ways to do it. they can yield return null; and use deltaTime. if timeScale is set 0, it will not add anything to the timer (variable), resulting in a stalled state for the coroutine (paused). you can also set the keepWaiting property to suspend the coroutine. using WaitForFixedUpdate means you're relying on FixedUpdate, but that should only be used for physics-based code (unless you're doing smth deterministic) . . .

rapid brook
#

Yeah my first approach was to use yield return null coupled with incrementing the number with time.deltaTime, but then when I saw I could just wait for the fixed update it seemed to be more appropriate, guess it works, but didn't know it kept running the coroutine, I though it really just was waiting for the next fixed update

rain minnow
#

if they do want the coroutine to run while paused, they'd use the Realtime version of the yield instruction . . .

rain minnow
rapid brook
#

Okay, so it means the deltaTime is not 0 when TimeScale is 0?

#

I don't get it, it has to stay at 0 since the value doesn't increment anymore when timeScale is 0

#

And since it's a delta, it has to be some sort of interpolation between one moment to the other? So deltaTime is not going to change by much?

#

Or am missing something?

rapid axle
#

Hey yall, I have a ton of animations and I dont want to set them all up in an animator, is there any way I can change blend tree animations through script on runtime?

rain minnow
# rapid brook Okay, so it means the deltaTime is not 0 when TimeScale is 0?

No, didn't say that. deltaTime will return 0 when timeScale is 0. If you add deltaTime to the timer and wait until the next FixedUpdate โ€” the deltaTime between fixed updates are constant at 0.02 which is different from the deltaTime you added to the timer (since it's at a variable rate) โ€” the value is not consistent when the caller returns to the coroutine . . .

dim whale
idle meteor
#

Hello everyone! I'm having a problem with Unity and still haven't found the solution. When I first start my game, there is a very short freeze while rendering any UI element. Sometimes this can be in milliseconds, sometimes it can be in seconds. What could be the reason for this?
https://youtu.be/-wbs0EYGkgA

glad shoal
rocky void
idle meteor
wintry stone
#

I just switch over to the new unity input system and Im having trouble converting my code would anyone know how to get this if statement to work?
if (context.performed)
{
jumpBufferCounter = jumpBufferTime;
}
else
{

        jumpBufferCounter -= Time.deltaTime;
    }
rocky void
# idle meteor So how can I preload all the items? Sorry, I'm very new to Unity.

A game manager and game loop is a bit harder to explain if you're new to unity but do have a look at the SOLID principles and learn about different programming patterns. It's a lot but will help your coding in general to be more efficient and extendable. For now have a look at this, it looks like Unity can preload selected assets and make them available in memory from the start of the game: https://forum.unity.com/threads/how-does-preloaded-assets-in-player-settings-work.318259/

vestal crest
#
        return list[^1];
#else
        return list[list.Count - 1];
#endif```
#

is this syntax okay?

dull merlin
#

hey guys i have a quick question if someone can help me out

#

if you can dm i will explain it

dull merlin
#

mb yo

kind wolf
#

do canvases work when instantiated?

somber nacelle
#

yes

kind wolf
#

specifically if it has a button

#

because i instantiated a canvas with a button and it doesnt work

somber nacelle
#

is there an event system in the scene?

halcyon thorn
#

I am having trouble finding the cause of a pathfinding issue with my NavMeshAgent.

Goal: find the shortest NavMeshPath to the Vector3 target
Problem: when the target (my player character) is in motion, the pathfinding returns a NavMeshPath. If the target is not in motion, it returns null.

I use the following method to find the shortest path to the player position:

private NavMeshPath GetShortestPath(Vector3 target)
{
  var path = new NavMeshPath();
  if (NavMesh.CalculatePath(transform.position, target, _agent.areaMask, path))
  {
     return path;
  }

  return null;
}

Has anyone encountered this problem or has any ideas what I can do to find the issue?

halcyon thorn
# kind wolf yea

Use Debug mode with the Event System selected and see where what the active object is.

#

Common issue is that you did not have a GraphicsRaycaster component on the Canvas

kind wolf
#

oh wait

#

i dont have an event system

#

im assuming thats the issue lol

dull merlin
#

so i need to animate a button on my main menu to smoothly scale up when hovered over and smoothly scale down when the mouse exists, i tried using animator to record a scale up and scale down- but im not able to figure out how to make the animation only run once and stay on the ending keyframe while the mouse is hovering over the collider, as well as scale down and stay on the regular scaled down keyframe after the mouse exits the collider

Animator animator;
    public bool mouseOver = false;

    void Start() {
        animator = GetComponent<Animator>();
    }
   void Update()
   {
       if(mouseOver==true)
       {
           animator.SetTrigger("MouseEnter");
           animator.ResetTrigger("MouseExit");
       }
       if(mouseOver==false)
       {
           animator.ResetTrigger("MouseEnter");
           animator.SetTrigger("MouseExit");
       }
   }
    public void OnPointerEnter(PointerEventData eventData) {
       
        mouseOver=true;
    }

    public void OnPointerExit(PointerEventData eventData) {

       mouseOver=false;

    }
}
#

not sure how to separate the code block sorry

halcyon thorn
somber nacelle
#

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

kind wolf
#

btw

#

does anyone else have issues with the input system or am i just dumb

halcyon thorn
somber nacelle
#

"have issues" is incredibly vague.

kind wolf
#

im just asking in general cuz like

#

ive had to do a lot of bs to get it working

#

for example

halcyon thorn
#

I am not a huge fan of it personally, I think it can be easier but it's okay now that I have done it many times

kind wolf
#

i have an instantiated player and the player gets disabled through gameplay so i cant have a player input on it

kind wolf
#

lol is it

halcyon thorn
#

you can put player inputs on a different object

kind wolf
#

yea i did that

#

i put another object in the player prefab that sets its parent to nul

#

but it just feels so weird

#

to do that

halcyon thorn
#

you could have it as a separate prefab

kind wolf
#

i just wanted to know if i was bad or if everyone has to deal with new input system bs

halcyon thorn
#

oh is this the new input system? I haven't used it extensively

kind wolf
#

yea

somber nacelle
#

still sounds like a design issue tbh

#

i use the input system exclusively and have never run into issues like that. you just need to learn how it works so that you can use it effectively

kind wolf
#

how is it a design issue tho?

halcyon thorn
#

in my current project, I have a Player GO that exists throughout the game that stores all things related to a single player (my game is multiplayer). Then, PlayerCharacter is a separate object that receives only the inputs it needs

kind wolf
#

like what else am i supposed to do?

#

should i not disable the char or smth?

halcyon thorn
#

what is the issue exactly and what are you trying to accomplish?

somber nacelle
#

i mean you haven't really even described the actual issue. you've just said you cannot put the player input component on the player object because you disable the player. but why is that an issue

kind wolf
#

i mean there isnt an issue because i did the weird workaround

#

maybe its just a personal thing idk it feels weird to do something like that

#

is there a way to append functions to player input events?

somber nacelle
#

well considering you haven't even said what the issue was then nobody here can possibly know what you actually need to do

halcyon thorn
#

yeah I'm not sure what you are trying to do and what issue you are working around

kind wolf
#

i might be rambling a bit sorry lol