#archived-code-general

1 messages · Page 224 of 1

leaden ice
#

Debug statements are stripped I believe

hard viper
#

he’s seeing problems in build vs development build, so that was my first thought

leaden ice
#

Actually surprised it's not a compile error in the release version

#

although maybe it gets done at the bytecode level

hard viper
#

i forget what the issue was tbh

leaden ice
#

so those are techincally separate "lines"

simple egret
#

The out variable gets initialized before the line at compiler level

hard viper
#

point being, you do not want to actually modify/initialize variables within any Debug. calls

wheat cargo
#

Are only Debug.Assert lines stripped? Do Debug.Logs get stripped as well?

hard viper
#

in my case, i think my variable was declared before. and I got a NRE because the Assert was assigning it

hard viper
#

this should make your code run a lot better in final built. because you SHOULD be spamming Debug.Assert

wheat cargo
#

Wait I'm confused now, how is anything logged to the Player.log in release build then?

hard viper
#

I probably average 0.5 Debug.Assert per method I write

#

for that you need to write to Console

heady iris
#

I actually wasn't sure if it completely stripped everything inside the method call

hard viper
#

it does

heady iris
#

or just skipped calling the method

#

I guess it's the former!

#

good to know

hard viper
#

it’s like the line is deleted

#

compiler doesn’t want to think about it too hard

simple egret
#

You'll get something along the lines of

Collider2D col;

if (col.forceSendLayers == 0) {
hard viper
#

I have an idea to make a polygon Composite collider2D with radius. I think I might be able to make a class that derives from CustomCollider2D, and add the shapes of a Polygon mode Composite collider, swap to outline mode. Generate, and then add the shape.

simple egret
#

After compilation, which is why it throws, that variable is not initialized

heady iris
hard viper
#

either way, it’s bad

#

don’t declare/modify/initialize in debug calls

simple egret
heady iris
#

ah, makes sense

#

i figured it was something like that

#

(this is very nice pattern for early-exiting)

wheat cargo
#

Debug.Log and Debug.LogError is definitely logging to the Player.log in a release build. I just tested it.

heady iris
#

you could just log a stack trace manually

#

that's convenient

#

I've used the StackTrace class in the past

wheat cargo
#

Thanks may have to try that

#

Yeah so Debug.Assert gets stripped but not Debug.Log and Debug.LogError, so it isn't the entirety of Debug. that gets stripped.

simple egret
#

Yep your logs will still get written to some file at runtime. This can be a slow operation (I/O is always slow compared to pure code executing on the CPU), so it's better to strip them out before building a release

heady iris
#

your users will also get mad if you write 23 GB of logs

simple egret
#

Opens logs:
"here 1"
"here 42069"
"fuck me why this won't work"
"this should be unreachable"

#

Almost forgot the usual "aaaaaa" and "fgfgfdfdfsrg"

heady iris
#

"hi"

#

other classics include "WHAT" and "WHY"

simple egret
#

I'm going to start putting jokes in these log files

Initializing dependency injection engine, registered 3 containers
Just kidding we have a tightly coupled code base here

heady iris
#

just kidding, we actually shipped a game

waxen kayak
#

Hello guys, I'm having the following problem: I am trying to add a class to a 2d array, I think the adding void is fine, it's just that the class is always null for some reason

    [System.Serializable]
    public class gridObj : NetworkBehaviour
    {
        //To change material

        public FishNet.Object.NetworkObject soldierMeshRenderer;
        //To move the soldier

        public Transform soldierTrans;
        //The speed the soldier is walking with
  
        //Has to do with the grid, so we can avoid storing all soldiers in an array
        //Instead we are going to use a linked list where all soldiers in the cell 
        //Are linked to each other
        public gridObj previousSoldier;
        public gridObj nextSoldier;

        //The enemy doesnt need any outside information
        public virtual void Move()
        { }

        //The friendly has to move which soldier is the closest
        public virtual void Move(gridObj stuff,Vector3 oldpos, Vector3 newpos)
        { }
    }
    public override void OnStartNetwork()
    {
        if (NetworkManager.transform.GetChild(1).TryGetComponent(out GridPartitioning component))
        {
            gridObj self = new gridObj();// { soldierTrans = transform, soldierMeshRenderer = NetworkObject };
            self.soldierTrans = transform;
            self.soldierMeshRenderer = NetworkObject;
            oject = self;
            if(self == null)
            {
                Debug.Log("self is null");

            }
            component.grid.Add(self);

        }
        base.OnStartNetwork();
    }

It is done in a multiplayer game, but Idon't think that has any relevancey, sincein the OnStartNetwork is says that it's null
any ideas?

simple egret
#

Probably can't use new on a NetworkBehaviour, like you can't do it on a MonoBehaviour

#

You may need to instantiate an object and add the GridObj component to it

waxen kayak
#

ah, that might be it

#

I'll check that quickly

leaden ice
#

definitely can't use new on NetworkBehaviour

#

it derives from MonoBehaviour

waxen kayak
#

yeah

simple egret
#

Also names of types (classes, structs, enums, etc.) start with an uppercase letter: GridObj, please follow the naming conventions

waxen kayak
#

does that really matter?

simple egret
#

For anyone that will read your code, yes

leaden ice
#

It makes it much harder to read when you don't follow the conventions

#

It also just looks very amateurish

simple egret
#

The naming convention is well made, enough for someone to see what kind an identifier is without looking at its declaration

heady iris
#

you'll be spending a lot of time reading your own code

hard viper
#

I'm trying to figure out the best way to make a Collider2D that is a CustomCollider2D, based on a CompositeCollider2D. The idea is CompositeCollider2D is set to Polygon mode => put shapes into customcollider => set to Outline mode => generate => put shapes into customcollider.

#

The issue is that CustomCollider2D is a sealed class, and none of the Cast etc methods of Collider2D are virtual

clever trellis
rigid island
clever trellis
rigid island
simple egret
#

There is also no question here

tawny elkBOT
clever trellis
simple egret
#

Try doing it all in one message, you can hit Shift+Enter to add a new line without sending the message

clever trellis
#

https://paste.ofcode.org/5W5tQW73vJeFhcBuZ5nE4R

i'm using googlecardboardVR tools and I want to make player move voluntarily. For that I tagged 2 objects with walk and sprint resp. I want that when i point the rectile towards them , i move otherwise don't. In this script, its casting a ray in the game environment, if it colides with the tagged objects, it moves.
As there are no triggers in cardboard vr, so i thought this would work. but not working!

#

anyone knows?

crude creek
#

Hi! I want to make so when this is called, the array called cars have all gameobjects with those tags, any suggestions? Thanks!

#

I know the + doesn't work for the arrays, I just didn't know how to do it

rigid island
crude creek
#

my what?

rigid island
#

integrated development environment (IDE)

crude creek
#

the IEnumerator?

#

oh

#

I understand now

#

I have it configured, I just took the screenshot before it started properly

rigid island
#

gotcha

crude creek
rigid island
#

put them in an array

#

loop thru the array

#
foreach (car in cars){
if(car.CompareTag("One") ){
}
#

not sure why multiple tags are needed here

crude creek
#

I have different gameobject that spawn when I hit play, and I want to access them through an array, I just didn't know how to do it I did it this way

simple egret
#

Is that.. trying to add arrays togehger with +? That's a first

#

In the new C# version (out a few days ago) you would be able to do that with a spread operator, but this is Unity

rigid island
#

what you should do is ditch tags and use types

#

so one object can have multiple attributes in form of Interface

crude creek
rigid island
#

you want to put multiple objects with diff tags in a list or

crude creek
# rigid island huh?

In another codes, I spawn various gameobjects in the scene, some have the tag Damagable, some have the tag cars, and others have the tag Ground. I want every gameobject in scene with some of this tags in the array

rigid island
crude creek
#

they do very different things

simple egret
#

Doesn't mean you can't put a script on it that's only for searching objects

#

This is composition

crude creek
#

Those are gameobjects that if they are too far away from the player, despawn them for game optimizing

crude creek
#

ohhh Iunderstand

#

I liked that code you made

simple egret
#

Okay, you're basically just redoing LOD right here

#

That already exists

#

Or, just decreasing the camera's far plane

crude creek
#

I just didn't know what was it and how to make it, so I just made it myself

crude creek
simple egret
#

Limit how far the camera can render

crude creek
crude creek
#

It still runs at low fps

latent latch
#

have you profiled it

simple egret
#

Is the object amount really the cause of bad performance, have you profiled it?

rigid island
#

you might need to also do occlusion culling

rigid island
#

if you want real fps boost

#

bake your occlusion

rigid island
crude creek
latent latch
#

if you look away (have no camera rendering the objects) is the fps still low

simple egret
simple egret
#

You cannot know whether X is the cause of performance drops without running the profiler basically

#

"It's the cause of low fps" - "source?" - "trust me bro"

latent latch
#

id double check the profile and make sure you've not doing something like raycasting 1k times an update ;)

crude creek
#

I tried deactivating myself the gameobjects, and when I do that, the fps go normal

rigid island
#

it could be scripts too tho

simple egret
#

They might have scripts on them that impact performance

rigid island
#

thats why you profile

simple egret
#

Like, doing FindGameObjectsWithTag() 60 times a second is very much not recommended

rigid island
#

fr

simple egret
#

Now imagine that on 500 objects lol

crude creek
rigid island
#

lookup a few vids on it

crude creek
rigid island
#

its very easy and poweerful tool

rigid island
crude creek
late wigeon
#

Does anybody know how to make a ball movement system for VR so whenever you kick it it actually acts like a ball?

late wigeon
#

thx

crude creek
#

np

crude creek
rigid island
#

also keeping things that dont move checked with static on gameobject improves how meshes get rendered

crude creek
#

I don't understand this, what is causing low fps?

rigid island
#

looks like your physics is high, also you need to put in hirerchy mode to understand it better

#

rendering is also pretty high

#

you should def go through a basic video how to read Profiler accurately

hard viper
#

is there a way to get around CustomCollider2D being a sealed class?

rigid island
crude creek
hard viper
#

my idea is to make a “Collider2D” class with its own shape and its own methods to modify the shapes, then use the shapes in a CustomCollider2D to make it work with physics

crude creek
hard viper
#

would it be possible to just copy all the source code from CustomCollider2D into an identical wrapper class that isn’t sealed?

#

idk how injected code works in that regard

#

uhh... UnityEngine.Bindings.NativeHeader is inaccessible due to protection level.

polar marten
# crude creek

your mind is in the right place for sure, with snippets like these. don't be discouraged!

hard viper
#

is there any way to get access to UnityEngine.Bindings? It seems to be necessary to bind methods to the proprietary C++ code

#

this is all because I'm trying to unseal the CustomCollider2D class

crude creek
#

@rigid island How bad is this?

rigid island
#

you're dipping below 15fps

#

you have tons of batches goin on

simple egret
#

There's also two large allocation spikes

crude creek
#

Physics is the thing it's consuming the most

simple egret
#

Switch to hierachy mode instead of Timeline to get a list of what uses the most resources

hard viper
#

would anyone know how to get around a sealed modifier in a built-in class?

crude creek
#

I think thats a lot of trigger stays

simple egret
#

Seems like you have some stuff that monitor trigger stays yes

crude creek
#

I think I know whats making that

simple egret
#

Do you have a lot of script instances with OnTriggerStay() implemented?

crude creek
#

Is there a way to see where are the triggerstays that are consuming the most?

simple egret
#

You'll have to enable Deep Profiling (button at the top of the profiler window) to see where in the code the issue is

crude creek
#

I enabled it

#

what now?

crude creek
simple egret
#

Profile again, and you'll be able to open the profiler's hierarchy items deeper this time

rigid island
#

holy shit 0.6MB of GC

#

what could you be doing OnTriggerStay

crude creek
rigid island
crude creek
#

it don't

wicked berry
#

so hi could someone help me out i tried to putting gliding into my game by making my velocity change my gravity but now i cant even get off the ground by jumping

simple egret
# crude creek

You need to run a new profiling session, ie. you need to play the game again

crude creek
#

still ends on those two lines

simple egret
#

Well no

#

These are your scripts

crude creek
#

ohhh

#

thats it

#

that really fits on what I thought

#

the problem is that I call those methods, or that I do a lot of thingds in those?

simple egret
#

Allocations (CG Alloc) are separated in the Hierarchy, but they are coming from the scripts at the same level

crude creek
#

ohhhhh

#

I know understand whats making it really go down

crude creek
#

the props.Ontriggerstay

#

Its what its the most consuming I think

#

correct me if I'm wrong

simple egret
#

You'll have to post the code, so we can see what's the source of all these allocations

crude creek
#

I found the problem

#

I'm using ontriggerstay when I could easily use ontriggerenter

neon plank
#

How can I know if an object is inside this infinitely wide (but not infinitely long) plane?
I would like to know the point in the plane where a vertical line fall thought it

simple egret
crude creek
#

I gotta go real quick

#

I'll be back rn

lean sail
rigid island
# crude creek

ahh thats almost like doing GetComponent in FixedUpdate

#

expensive

simple egret
#

And the Instantiate

rigid island
#

yeah constantly Destroying too

simple egret
#

And a small bit for the lack of CompareTag

rigid island
#

someone needs to learn pooling 😏

#

yeah this whole method screams optimizations needed

#

no wonder profiler is crying

simple egret
#

Yeah especially if this is on a lot of objects. The text objects can indeed be pooled yup

hard viper
#

pooling is an optimization you plan for early, but you do later.

#

it makes sense that now is the time to upgrade

simple egret
#

Putting that in OnTriggerEnter should shave off a great part of the slowdowns

wicked berry
#

if i put my jump in fixed update it doesnt jump immediatly

#

but if i put in update it does but people said its bad for optimizing

hard viper
#

the optimal way to do it is to use InputSystem to call methods specifically when the jump button is pressed

neon plank
# lean sail What do you mean by that last sentence? What vertical line are you hoping to ach...

I have a rectangle of infinite width (ignore the vertical yellow lines) and finite length which is defined by two points plus a normal.
If have a green point above the rectangle, I want to get its corresponding (purple) point in the rectangle.
And if the green point doesn't have a corresponding rectangle point, I don't want anything (this is not an infinite plane, but an infinite rectangle).

rigid island
#

if you are using Impulse force, Update is acceptable for a frame pressed

hard viper
#

if you use Input, that has to go into Update

#

InputSystem doesn't need to go into update nor fixedupdate

#

but in no case can you be putting it in fixedUpdate

wicked berry
#

oh lmao xd

#

thanks

simple egret
wicked berry
#

i though anything physics related had to go into fixed update

neon plank
#

Ok

crude creek
#

I'm back

#

I read all your comments, and I'm gonna apply them. Thanks a lot!

lean sail
# neon plank I have a rectangle of infinite width (ignore the vertical yellow lines) and fini...

What is this for in terms of your game? This seems like a very niche problem that doesnt need to exist in the first place. If you cant define a max size and use a collider to solve some of the work, you'll need to keep track of every object that can potentially be above this. Then im pretty sure it should be as simple as checking if the current position lines up with the rectangles normal + some offset. That offset is just the finite dimensions of the rectangle

neon plank
hard viper
#

Ok, I think I'm narrowing down on my options, and I need a bit of help: I want to make a wrapper class for CustomCollider2D, but idk how to do this since it is sealed. Most of my code uses Collider2D to call Cast, Distance, logic in dictionaries etc. And idk how to add this while keeping compatibility. The class I want to make should be identical to a CustomCollider2D, but it has some extra methods/fields. Any ideas?

midnight sun
#

Does any1 know what could be causing a consistent an immediate crash when generating lightmaps? This randomly started happening today, many different versions and newly created projects are affected.

lean sail
hard viper
#

I'm thinking about making a Class containing a CustomCollider2D, make a static dictionary to connect class to customcollider2D, and whenever I want to call on anything with a Customcollider2D, I need to go check this dictionary. Sound like a plan?

midnight sun
#

Like everything else works fine but I just cannot bake anymore

rigid island
midnight sun
#

Omg

#

Lmao

#

I just saw general and was like this is the one

hard viper
#

is there a way to get a message when an object is destroyed? or when a destructor is called?

umbral temple
hard viper
#

it's a built-in component

#

I want to subscribe a method to its destruction

rigid island
#

just invoke an event inside OnDestroy ?

hard viper
#

let's say my target is a Collider2D

#

I want to know if/when this collider2D is destroyed

#

and I want to call Foo() when it destroyed. How do I do that

rigid island
#

might be easier to look in editor scripts, if you need it runtime maybe there is a better way and might be XY problem

hard viper
#

!code

tawny elkBOT
hard viper
#

This should give an idea of what I'm trying to do

#

I am trying to make a generic wrapper class to deal with Unity's fetish for sealed classes

#

The way it works is: The wrapper can tell you the thing it wraps. When you initialize the wrapper, it needs to basically add itself to the static wrapper dictionary that ties the wrapper class to the type of component it wraps.

#

Then the wrapper class can hold whatever things you need

#

And if you have an object of the wrapped type, this dictionary lets you access the extra information

#

The problem is: in order to make a static dictionary, I need to know when the component is destroyed to remove it from the dictionary

#

any idea on how to do this lightly? I don't want to make something that just checks the dictionary for destroyed entries every frame, just to block memory leaks

#

it would also work if I could subscribe a method to an object being disabled

mossy snow
#

what's the purpose of this wrapper? Your design seems to be screaming that whatever it's supposed to do, it would best be done as a component as well that's adjacent to this wrapped thing on a GO, not an association in a static dictionary

hard viper
#

I can't modify Unity's built-in components outside of extension methods

#

extension fields aren't a thing

#

I would love to derrive from CustomCollider2D, making a class that just matches the outside behaviour (so you can call Cast, Overlap, Distance....)

#

to make a CustomCollider shape that is more specific, and thus has certain parameters/fields for that shape

#

and this is a general issue: I wish I could just... add fields to built-in components. But I can't

#

I wish I could inherit from built-in components, but I can't

#

I wish I could copy the code and make a new class from scratch, but because of how Unity injects C++ code, I can't

#

I wish I could just change the source code. Change one or two words. but I can't

mossy snow
#

well you're working against the system here. Make a CustomCollider2D class with a serialized field to a target Collider2D and implement all the same methods. I don't see how your wrapper is going to be a better solution over that, especially since it really doesn't have any functionality

hard viper
#

CustomCollider2D is sealed

mossy snow
#

MyCustomCollider2D that accepts a target CustomCollider2D then

hard viper
#

and most methods are injected, with attributes with a protection level that blocks you from copying them

#

ok, Cast/Distance/Overlapping etc isn't virtual

#

if 99% of my methods solely depend on a Collider2D, I can't just .Cast it

mossy snow
#

your wrapper has the same limitation, while also being more complicated and confusing to use though

hard viper
#

what is your suggestion

#

MyCustomCollider2D can't inherit from CustomCollider2D, and inheritting from Collider2D just gives the wrong behaviour.

#

and I can't give Collider2D an interface

mossy snow
#

I just described it. I still don't know what your ultimate objective is though. Maybe your specialized Cast/Overlay behaviour should be in a static class instead and you avoid wrapping anything

hard viper
#

I don't have specialized Cast/Overlap/Distance behaviour

hard viper
#

what does MyCustomCollider2D inherit from, if anything

mossy snow
#

it beats the stuffing out of a static dictionary, so yeah. But what do you want to do with CustomCollider2D? This looks super generic already

#

MonoBehaviour

hard viper
#

This would basically give me the ability to know when the object is destroyed.

mossy snow
#

yes

hard viper
#

how is this different from the wrapper method?

#

my whole game depends on Collider2D, and Collider2D methods

mossy snow
#

did you find a way to solve the object destruction problem? Because the next point on that train is "well I'll add a component to the wrapped component's GO..." and then all your previous code might as well deleted, and you'll end up at my suggestion

hard viper
#

I think I will give my wrapper an initialize method that takes in an Action, that gets triggered on destruction

#

and a different monobehaviour that it lives on can tie it

#

the wrapper would make it so I only need to call the wrapper for a couple of methods that need really specific behaviour

#

I think this is what we're going with

#

Generic class. If you inherit from this, then you can maintain it automatically

#

the idea is to compose this wrapper into another monobehaviour

#

or just... let it be in the ether, not composed into anything

hard viper
#

Finally got it. success

#

janky success

broken light
#

is there a built in function to query if Bounds is visible for a specific camera

#

since they do those checks with meshes

#

wondered if they exposed the function for us to query freely

#

i really would like to avoid doing the math myself given they have the function already there some where for their OnBecomeVisible etc

broken light
#

it looks like it might just be

#

thank you @lean sail

#

shame they didnt just have a helper function on the camera itself

#

like _camera.IsVisible(myBounds)

elder chasm
hasty wave
#

how can I prevent the "bed" from detecting the mouse over once there's a UI above it?

broken light
#

some where in their inspector

broken light
hasty wave
broken light
#

yeh i know OnMouseOver is doing a ray check on your behalf

#

if you block the rays it shouldn't trigger

#

on your canvas gameobject add canvas group component

#

and tick block raycasts

elder chasm
broken light
#

oh you might have to do body.AddForce() and give it equal and opposite force on x axis

#

to cancel it out

#

body.totalForce = new(0,body.totalForce.y);

#

might also work

hasty wave
broken light
#

well you should really use IPointerClickHandler interface rather than OnMouseOver

#

i believe that will respect the ui

hasty wave
#

I see.. alright thanks :D

elder chasm
#

i might just be being dumb

broken light
#

its lowercase t not T

#

the doc has example code at the bottom

elder chasm
#

oh my bad

#

sorry my internet did a funny there

#

honestly i dont have any clue why its not working

#

all i know is that if i put a Debug.Log before the set velocity it runs the log script

spring creek
elder chasm
#

!= mean is not right

spring creek
elder chasm
#

ye what i mean lol

spring creek
#

So, the side of the platform for example

#

Assuming a platform is tagged Ground?

elder chasm
#

yes

spring creek
#

Ok, well that is why the x velocity is reset when you hit the side of a platform. You do it explicitly.

elder chasm
#

i want it to be where when you stop touching the side you dont keep your velocity

#

from before you hit it

#

like in mario how if you run into a block and in the same jump you stop touching the block from gaining height you dont keep momentum @spring creek

spring creek
elder chasm
#

no thats not what im asking

#

you know how in mario you need to build momentum to go fast

#

but if you run into a block or something you lose all your momentum

#

thats what im goin for

spring creek
hasty wave
#

how do I make it so that any interaction like dragging with the mouse, scrolling to zoom and interacting in the background is disabled when a UI appears?

spring creek
hasty wave
spring creek
# hasty wave wdym by that?..

There is the new input system and the older input manager.
Are you writing things like Input.GetAxis, or using callbacks?
If you aren't sure, you are 99% using the old input

hasty wave
#

I do use the Input.GetAxis for my zoom

elder chasm
#

this sounds like a really dumb question, but how do i add non-ui text

spring creek
# hasty wave I do use the Input.GetAxis for my zoom

Ok, well you'll want to just have some condition wrapping the input. Like when menuOpen is false read that input, when it is open, you don't

You could also have it in a script that you enable or disable (disabling a script only disables unity methods like update btw)

hasty wave
#

wait, how do you disable a script?

spring creek
#

scriptReference.enabled = false;

hasty wave
hasty wave
spring creek
soft shard
spring creek
elder chasm
#

oh

spring creek
#

2d in Unity is still 3d

elder chasm
#

ye i forgor that

#

oh wow its that easy

spring creek
#

TMP is cool haha. Worldspace text is great.

elder chasm
#

hello me again

hasty wave
# spring creek this.enabled = false; or

the cameraDrag and cameraZoom did stopped working when disabled. but the bedFunction still does the "OnMouseOver" dispite it's script is already disabled. why is it like that?

elder chasm
#

how would i make a loop that moves something up and then moves it down and then repeats

spring creek
hasty wave
hasty wave
#

@spring creek sorry for the ping but thank you so much for introducing me this .enabled really helped a lot!

soft shard
# elder chasm how would i make a loop that moves something up and then moves it down and then ...

Sounds like you might be looking for a PingPong: https://docs.unity3d.com/ScriptReference/Mathf.PingPong.html
Since this return a float you can manipulate one axis at a time with it, heres an example that seems similar to what you want to achieve, searching "unity c# mathf.pingpong vector": https://forum.unity.com/threads/ping-pong-gameobject-up-and-down-from-current-postion.226442/#post-1509140

elder chasm
#

can someone break this down im a bit confused

#

shouldnt it need a min y

mossy snow
#

why wouldn't you just read the documentation that you were linked?

elder chasm
#

i got confused

mossy snow
#

PingPong returns a value that will increment and decrement between the value 0 and length. confused you?

elder chasm
#

im trying to apply it

#

to move something

#

im a bit slow

#

i just want to move something up and then down and then repeat and im tryin to figure it out rn

#

i think im gettin it now though

wispy wolf
#

@elder chasm You want to do this without physics? Just forcibly set the location every FixedUpdate()?

elder chasm
#

yeah i think ive got it almost figured out gimme 1 sec

wispy wolf
#

Think of it as a library to blend between two values over time, but incredibly flexible and customizable

elder chasm
#

oh thanks

wispy wolf
#

It can feel a bit overwhelming bc it can do a lot, but its good to have a basic understanding of it. dm me if you ever need help with it

spare island
#
            DOTween.To(() => _canvasGroup.alpha, x => _canvasGroup.alpha = 1f, 0f, UIFadeInOnActiveGlobalConfiguration.Duration);

i may be stupid but what am I doing wrong here to make this canvasGroup's alpha go from 1 to 0?

#

dont mind the incredibly long name for that class

mossy snow
spare island
#
            DOTween.To(() => _canvasGroup.alpha, x => _canvasGroup.alpha = x, 1f,
            UIFadeInOnActiveGlobalConfiguration.Duration);
``` im trying to figure out why this works and the other thing doesnt (i tried with "x, 0f" too)
mossy snow
#

that has a correct setter

spare island
#
            DOTween.To(getter: () => _canvasGroup.alpha, setter: x => _canvasGroup.alpha = x, endValue: 0f, duration: UIFadeInOnActiveGlobalConfiguration.Duration);

with labels

mossy snow
#

that one is now correct

spare island
#

what CH_IconLoading

mossy snow
#

your first snippet ignores the value of x and sets alpha to 1 every time

polar marten
polar marten
#

i see you figured this out

spare island
polar marten
#

that code is correct. your canvas group (your hierarchy) is probably not set up correctly

#

or, rarely, you may have configured dotween to not autoplay

mossy snow
#

or you set timeScale to 0, that surprises people every now and then too

spare island
#

no whats weird is that it sets the alpha of the canvasgroup to 0 immediately

polar marten
#

well

#

then the duration is zero. or, you are setting it to zero immediately elsewhere

spare island
#

oops

#

well at least i wasnt wrong about being stupid

polar marten
#

it's okay

spare island
#

that will look much cleaner

finite swift
hexed pecan
finite swift
#

Just an empty object placed on the edge of the player

hexed pecan
#

Anyway you could start by visualizing the forces, collisions etc. with Debug.DrawLine and such

gray mural
#

Hello, why isn't value assigned to the StartCoroutine(coroutine)?
It also throws the IDE0059 on the value =

/// <summary>
/// Stops the value coroutine if it isn't null and assigns it to the newly started one
/// </summary>
public void AssignCoroutine(IEnumerator coroutine, Coroutine value)
{
    TryStopCoroutine(value);
    value = StartCoroutine(coroutine);
}
#

the Coroutine is the class and it should save the reference, shouldn't it?

#

do I just make value a ref ?

#

oh, just remember you cannot assign a class to the smth, you can just change its fields

#

that's a stupid mistake 🙄

hexed pecan
#

You can just make your method return a Coroutine

#

Or ref

gray mural
finite swift
hexed pecan
#

I would use a bool instead of relying on float comparison and transform.localScale.x

#

Or at least check the sign of it instead of exact value

#

Not sure how to fix your walljump issue though

fiery path
#

Am i correct in saying having a public bool method will be originally assumed as false?

EG:

    {
        return (Time.time - lastEnteredTime) >= CooldownTime;
    }
simple egret
#

No

#

It'll evaluate what's after the return and return that value

#

Methods do not have default values, you'll only know the value when you call (execute) it

fiery path
# simple egret No

I see
So in this case it will check if the elapsed time is greater than or equal to the cooldown time and then the method would return true

So am I understanding that boolean methods technically dont have a base true or false state
They just turn true once a returned condition is met?

simple egret
#

No method has a "base state", only variables do

fiery path
#

Got it, thanks

fervent furnace
#

it just returns the result of expression

fiery path
#

Yeah nevermind, I was completely overthinking 💀

#

i fully understand

dapper palm
#

I followed this video https://youtu.be/eL_zHQEju8s?si=uLLHWhr-6kZgfZaV on water physics and at the end of the video he says how to add movement but doesn't show it can someone help me do that.

In this tutorial you'll learn how to set up boat movement and dynamic water physics in Unity.

Check out my devlogs: https://www.youtube.com/playlist?list=PLXkn83W0QkfmQI9lUzi--TxJaOFYIN7Q4

⎯⎯⎯⎯⎯⎯

Catlike Coding's article about shader-based vertex manipulation and Gerstner waves: https://catlikecoding.com/unity/tutorials/flow/waves/

Discord s...

▶ Play video
#
public class Floater : MonoBehaviour
{
    public Rigidbody rigidBody;
    public float depthBeforeSubmerged = 1f;
    public float displacementAmount = 3f;
    public int floaterCount = 1;
    public float waterDrag = 0.99f;
    public float waterAngularDrag = 0.5f;

    private void FixedUpdate()
    {
        rigidBody.AddForceAtPosition(Physics.gravity/ floaterCount, transform.position, ForceMode.Acceleration);
        float waveHeight = WaveManager.instance.GetWaveHeight(transform.position.x);
        if(transform.position.y < waveHeight)
        {
            float displacementMultiplier = Mathf.Clamp01((waveHeight - transform.position.y) / depthBeforeSubmerged)* displacementAmount;
            rigidBody.AddForceAtPosition(new Vector3(0f,Mathf.Abs(Physics.gravity.y)* displacementMultiplier, 0f),transform.position, ForceMode.Acceleration);
            rigidBody.AddForce(displacementMultiplier * -rigidBody.velocity * waterDrag * Time.fixedDeltaTime, ForceMode.VelocityChange);
            rigidBody.AddTorque(displacementMultiplier * -rigidBody.angularVelocity * waterAngularDrag * Time.fixedDeltaTime, ForceMode.VelocityChange);
        }
        if (Input.GetKeyDown(KeyCode.W))
        {
            
        }


    }
}```
prime sinew
#

so just look into AddForce and AddTorque for rotation?

gray mural
#

Hello, what's the best way to set the mouse position in Unity?

#

I've found some stuff that uses System.Windows.Forms, but it's not the best thing to use in Unity, or am I misunderstanding something?

dusk apex
#

Maybe consider making a game mouse cursor and hiding the OS cursor.

fervent furnace
#

mouse position is controlled by OS (and read from the hardware)
there should be some system calls to change the mouse position in the OS, maybe google it by yourself

gray mural
dusk apex
#

Which would differ per platform etc

ashen yoke
dusk apex
#

Else consider manipulating the non OS mouse and acquiring deltas from the OS mouse instead.

gray mural
ashen yoke
#

you can i think with CursorMode.ForceSoftware

gray mural
#

so I had to implement my custom logic

gray mural
#

I surely cannot achieve this stuff using the built-in cursor

ashen yoke
#

no you can only set image, you are correct

#

but you can set larger image than 32 which hw cursor allows with software mode

#

which ui is drawing the cursor?

#

uGui?

gray mural
gray mural
ashen yoke
#

they are fine in debug build/editor

gray mural
ashen yoke
#

reason is simple a single call anywhere in the project will spin up the GUI system in build which with zero load will still consume about 2ms per frame

#

no, build is build

#

the .exe

gray mural
ashen yoke
#

while in editor you can use GUI if you #if UNITY_EDITOR #endif

gray mural
#

I don't use it in editor though, so no troubles 🙄

ashen yoke
#

yes you are planning to use it for the game itself, so it will go into the build

#

and your performance will suffer

gray mural
#

oh, so the Build Mode is when the game is played outside of the Unity?

ashen yoke
#

build is the process of creating the final executable, asset bundles so that the game is playable outside the editor, yes

#

term build refers to the .exe and all the files of the published game

rich widget
#

Hello. Running into a weird issue/bug(?) when manually playing animations onto a standard Animator component.

The thing I am trying to do is

  • create an object
  • specify the animation to play on it by name

The behavior I am seeing is that for 1 frame after creation, the object is drawn with a sprite from the default (from entry) animation state instead.

Relevant code snippet, I removed some irrelevant lines and simplified the code. I think it's more likely to be me misunderstanding some nuance of the unity animation system than an actual programming error;

var new_obj = GameObject.Instantiatekind, position, rotation);
var animation_comp = new_obj.GetComponent<Animator>();
animation_comp.Play(animation_name);

I feel like this didn't used to happen, but I cannot say that for sure.

ashen yoke
rich widget
#

*animation controller

gray mural
#

Drawing a custom cursor in OnGUI method

ashen yoke
#

it seems the normalized time has potential to fix your issue if you provide 1

rich widget
#

that seems strange. Reading it it seems that normalizedTime would be used to pick the starting point in an animation consisting of blend+target animation. I'll try it but my guess would've been I'd jump to the end of my animation. Happy to be wrong though

#

hah. the behavior I am getting is;

  • Still 1 frame of default state
  • Rest of animation skipped
ashen yoke
#

does it have "play on awake" ?

rich widget
#

sorry, I am not familiar with that setting. where would that be located? is it in the animation controller, the animation, or the renderer?

ashen yoke
#

the animator component

#

frame delay may be the animator no in isInitialized state yet

#

so your Play command is buffered

rich widget
# ashen yoke the animator component

the actual animator, at least from inspector, does not expose such a variable. but it has a 'normal' update mode and a 'always animate' culling mode

rich widget
gray mural
rich widget
#

I'll try to force the initialization with rebind

ashen yoke
#

im shooting blindly i dont remember if i had this issue or not and if i did anything to remedy it

#

so im scratching off the bottom of the memory barell for potential fixes

rich widget
#

yeah it is understandable. I sure sometimes wish I could sidestep the animator system entirely 😬 sadly not an option I think

rich widget
rich widget
ashen yoke
#

i probably mixed it up with something else

#

lots of unity component have setting like that

rich widget
#

no worries

ashen yoke
#

that Keep animator state fixes nasty issue when disable/enable of the animator would break its internal state

#

it has potential to fix your issue, but its low, but still worth a shot

rich widget
#

I think it might've if I wasn't creating a new object every time?
There are actually a lot of fun interactions I am noticing now that I am truly stepping through this unity step-by-step

ashen yoke
#

if it fails, my last suggestion is to manually go through transitions in the state machine itself and disable "has exit time" on them

#

another thing you can try doing

#

is when you spawn the object, disable/enable it

rich widget
#

feels a little silly that that'd be the thing, considering I am not actually using any of the regular transitions

#

disable it for 1 update frame would certainly work around this

ashen yoke
#

no i mean just disable/enable

#

synchronously

rich widget
#

huh

#

sadly, nope

ashen yoke
#

if something pops in mind ill share, atm nothing

rich widget
#

I am noticing another problem semi-related to this now, too;
The physics outline consistently lags behind the animation by 1 frame (first frame has some sort of prefab default prism structure)

wise arch
#

I cannot seem to copy InputAction.CallbackContext and it's making my input based replay system fck up when it tries to read a vector2 from the context.

How can I copy it anyway and fully?

rich widget
ashen yoke
#

in any case, that is normal, physics dont step in sync with Update

#

are you calling Play in fixed update?

rich widget
#

I dont think so but let me double check

rich widget
ashen yoke
#

all colliders live in a separate physics world which is synchronized with unity scene

#

the physics world is updated at fixed rate, Update is not

rich widget
ashen yoke
rich widget
#

YEP that handles it

#

(with 0 as argument)

#

many many thanks

ashen yoke
#

great!

hard viper
#

I'm confused as to why the commented line gives an ArgumentOutOfRange exception

#

Debug.Log shows that shapes.GetShapeVertices breaks when i=1, and shapeCount = 2

ashen yoke
#

can it be that shape 2 has 0 verts?

hard viper
#

when I look in debug mode, that seems to not be the case

#

PhysicsShapeGroup2D is kind of weird. I think it stores all the vertices in one big list

#

then each shape corresponds to a range of indices

hard viper
#

ah ha. I can use the assembly browser, but I couldn't see the line numbers

ashen yoke
#

post the stacktrace

hard viper
#

ok this doesn't make sense. Stacktrace says to look at line 2654, which is a different method

ashen yoke
#

versions differ

hard viper
#

ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.Collections.Generic.List1[T].get_Item (System.Int32 index) (at <130809ae6f984869a6663c878f16e3f3>:0) UnityEngine.PhysicsShapeGroup2D.GetShapeVertices (System.Int32 shapeIndex, System.Collections.Generic.List1[T] vertices) (at /Users/bokken/build/output/unity/unity/Modules/Physics2D/ScriptBindings/Physics2D.bindings.cs:2654)
LoupExtensionMethods.LoupPhysicsExtensions.ToStringVertices (UnityEngine.PhysicsShapeGroup2D shapes) (at Assets/Scripts/GenericPhysics/BasicKinematicMovement.cs:452)
CompositeColliderRound2D.MakeRoundedCompositeWithoutWrapper (UnityEngine.CustomCollider2D custCollider, UnityEngine.CompositeCollider2D compCol, UnityEngine.PhysicsShapeGroup2D& shapes) (at Assets/Scripts/GenericPhysics/CompositeColliderRound2D.cs:99)

#

I had to cut off the stack trace because it is too long

ashen yoke
#

shapeVertices[shapeVertexIndex++] the only indexer in that method

hard viper
#

uh... that is different from where the assembly browser brings me

#

but it looks the same

ashen yoke
#

can you use the debugger and check if groupVertices matches amount of verts in both shapes

hard viper
#

anyway, I don't understand why I would get an argument index out of range exception

ashen yoke
#

because of a bug, most likely

hard viper
#

can I put a breakpoint in the assembly browser?

ashen yoke
#

no just in your IDE

hard viper
#

anyway, the point of all this is to debug more easily, because I see when I add 2 physicsshape groups, the result is different

#

my shapes has 2 shapes, one with 4 and 5 vertices. Groupvertices is 9 long. which is right

ashen yoke
#

which unity version?

hard viper
#

2022.3.2f1

#

I suspect the issue is in GetShape

ashen yoke
#

check each shape vertexStartIndex

merry sierra
#

do any one know how to get desktop's audio

hard viper
#

OH shit I found it

hexed pecan
hard viper
#

my second shape has vertexStartIndex = 5. First shape is 4 vertices long. So the start index should be 4

merry sierra
#

lets say i am playing some music on spotify so it should detect the music so that i can get the spectrum values and stuff

hard viper
#

ty cache. I'll report the bug

cloud marsh
#

does anyone have an idea on how to recreate tf2's movement?

hard viper
#

ty .cache. I love fixing bugs in unity /s

#

wtf. was this class tested?

ashen yoke
#

probably fails under specific conditions

hard viper
#

i don't think so

ashen yoke
#

when shape is inserted it may report incorrect vert count

#

or something like that for some specific shape

hard viper
#
    int num = physicsShapeGroup.vertexCount;
    groupShapes.AddRange (physicsShapeGroup.groupShapes);
    groupVertices.AddRange (physicsShapeGroup.groupVertices);
    if (count > 0) {
        for (int i = count; i < m_GroupState.m_Shapes.Count; i++) {
            PhysicsShape2D value = m_GroupState.m_Shapes [i];
            value.vertexStartIndex += num;
            m_GroupState.m_Shapes [i] = value;
        }
    }```
This function doesn't make sense. This is .Add
#

groupVertices uses .AddRange to add the new shape to the end of the vertex list

#

and then it goes through all the old shapes, and shifts their start forward

#

that's not correct

#

that's flipped

#

it's so wrong, that this function was probably not tested

hard viper
#

I fixed it by not using.Add

hard viper
#

bro. this component was not tested. wtf unity

young bluff
#

This part of the code takes about 712ms to excute. chunkList is a arraylist of chunkinfo. Any idea how to make it performe better

hard viper
#

I've had something like that before

#

do you have ruletiles?

#

and how many tiles are you setting at once?

#

what is var.Positions.Length ?

#

also, don't use Time. that's wrong

#

you want to use stopwatch

#
DoWhatever();
stopwatch.Stop(); Debug.Log("Time it took to load level (in ticks): " + stopwatch.Elapsed.Ticks);```
#

stopwatch is designed to actually properly measure this stuff

fervent furnace
#

ArrayList?

#

it should be List i see, ArrayList and List is completely different

lyric atlas
#

This might be a rather dumb question but is it worth having a helper method to narrow certain calls which use GetComponent?

say:

if (target.GetComponent<Health>())
  target.GetComponent<Health>().Damage(data);

and using a static helper to implement this so I can just call something like

HelperClass.DoDamage(target, data);

as if this may be called lots, condensing it like this is nicer and any class can access it. I'd like it to condense my code but wasn't sure if there was a better way than this. I'm presuming I could also use GameObject.SendMessage as an event-ish route but I'm not sure on its performance
I can think of a few ways to do it fine, i'd just like to know which ways would be better practice and why, ta!

fervent furnace
#

what is the type of target

lyric atlas
#

GameObject

fervent furnace
#

if the objects is nondeterministic, eg argument in OnTrigger/Collision callback then i prefer tryGetComponent (it is just two lines of code) otherwise just reference to the script

ionic isle
fervent furnace
#

what?

ionic isle
lyric atlas
fervent furnace
#

look likes spam

lyric atlas
lyric atlas
fervent furnace
#

i would do this if you prefer to use helper method

public static bool Method(){
  return true if component (ie the script) exists
}
``` then call it as
```cs
if(Helper.Method()){do works}
else other works
#

since you may have further logic to be performed depends on whether there is the component

lyric atlas
#

ah fair point, I'll probably make it a bool and return true if the default path is used and false if not, this is gonna be very general and used by a lotta stuff as a baseline so it doesn't need to handle special behaviour cases in the helper

fervent furnace
latent latch
#

I question some of these methods. Why would you ever use this instead of just grabbing the references?

dapper palm
#

!code

tawny elkBOT
young bluff
dapper palm
hard viper
young bluff
#

sorry was out of internet for a bit let me see what i can implement

clever trellis
#

this is not working!
i want to move the object in the direction camera is looking when i click the screen
i'm calling this onpointclick from another script (attached to some other object)

stark plaza
#

What's the best way to make a Narrator System? I was thinking about a SO with audioclip and some other info that you can attach to a Game object script that handles based on different implementations (collisions, interaction, player stuff) etcs handles the events raising to the main Narrator System

rigid island
tawny elkBOT
clever trellis
#

i thought its a small code snippet 😅

rigid island
#

no, regardless they should at very least go in codeblocks

#

screenshots are the worse for code

#

also not accessibility/screen reader friendly

clever trellis
rigid island
#

what is supposed to be calling OnPointerClick()

clever trellis
#

i show u, just a sec

hard viper
#

I'm trying to figure out the smartest way to handle depenetration. Some options:

  1. One pass through all moving objects, iteratively trying to depenetrate one at a time.
  2. Many passes through all moving objects, with a single depenetration attempt
  3. Other?
    Any suggestions?
rigid island
#

if its a one frame event the translate won't do anything

#

Debug.Log inside the if statement should tell you how many times its being called

clever trellis
#

this player has the movement script which includes onpointer click
and the CardboardReticlePointer has the rectile script which calls the player one

rigid island
#

I understand

clever trellis
rigid island
rigid island
#

Gets a value indicating whether the Cardboard trigger button is pressed this frame.

#

its one frame

clever trellis
#

what to do now

rigid island
clever trellis
#

let me try

rigid island
#

like way low esp with Time.deltaTime

clever trellis
rigid island
# rigid island like way low esp with Time.deltaTime

@clever trellis you did Vector3 movement = 10f * Time.deltaTime * Camera.main.transform.forward; (0, 0, 1)
say Time.deltaTime was 0.0063257 that frame you would only moved about (0.00, 0.00, 0.06) in a frame

clever trellis
#

if a put the code directly inside is triggered func, it functions fine ie. moves the object the script is attached to (the rectile dot)

#

but i want to make the whole player move

rigid island
#

yes because trigger is being called every frame

#

so make a reference to the player

clever trellis
#

ig OnPointClick is not being called

rigid island
clever trellis
rigid island
#

children transforms do not move parents

clever trellis
rigid island
clever trellis
rigid island
#

transform property is the object script is on

clever trellis
#

😭

rigid island
clever trellis
clever trellis
rigid island
#

your script is named different than your class

clever trellis
rigid island
winter jungle
#

Can anyone help with this problem... recently i made my game multidevice so it can be played from pc mobile and ps. However to do this i had to switch to the new input system while all my scripts were coded woth the old one. I found on unity how the controler is but does anyone know how is this line translated: Input.GetAxis("Horizontal"); or at least how to make smooth movement using it?

wicked berry
#

why is my triangle not detecting collisions with my players

clever trellis
#

<i>AndroidPlayer "samsung_SM-M515F"</i> OPENGL NATIVE PLUG-IN ERROR: GL_INVALID_VALUE: Numeric argument out of range

rigid island
#

Player if statement has nothing in it

oblique spoke
civic igloo
#

Getting a missing reference exception for a destroyed delegate even though i am removing the listener on destruction?

oblique spoke
civic igloo
#

no, on player death, i have an event for whenever the player dies, it's supposed to disable all ai in the scene

#

wait could the fact that it's inheriting from a base class mean something?

oblique spoke
#

Logging subs, unsubs and whenever that method is called could provide some hints

civic igloo
#

sorry how do i do that?

latent latch
#

Connect the debugger and throw down a breakpoint and usually you can get a stacktrace of subscribers

oblique spoke
#

Using the debugger might help, but knowing when you are subbing and unsubbing from events as the game goes might be more helpful. You can log with Debug.Log

heady iris
#

I had trouble with this

civic igloo
#

but doesnt ondestroy still get called?

heady iris
#

Yeah. My problem was that I used a unity property in the process of trying to unsubscribe

#

and so it threw an error

alpine turret
clever trellis
alpine turret
#

take a compliment...

#

@spring creek 🤡

static matrix
#

is it possible to convert points in worldspace to points on a texture?

#

like if I get a clicked point can I get where that would be on a texture
or vice-versa

waxen kayak
#

Good day to everyone, I have a giant memory leak
I'm now trying to check if an object has moved to another grid, so I can update it, here is the code:

Vector3 oldPosition;
     Vector3 lastPosition;
    public void refresh()
    {
        oldPosition = lastPosition;
           lastPosition = transform.position;
        addtoPart.move(oldPosition, lastPosition);
    }
    public void Awake()
    {
        waterManager = GameObject.FindGameObjectWithTag("WaterManager").GetComponent<GridManager>();
        addtoPart = GetComponent<AddToPartitioning>();
        InvokeRepeating("refresh", 1,1);
        lastPosition = transform.position;
        oldPosition = transform.position;
    }

this is on the class my object is inheriting from
public void move(Vector3 oldpos, Vector3 newpos)

  {
       gridObj[] list;
       Vector2 pos = partitioning.grid.gridIndexAtPosition(transform.position);
       partitioning.grid.returnObjectInCell(new Vector2Int((int)pos.x,(int)pos.y), out list);
       
       foreach (var item in list)
       {
           if(item.soldierTrans = transform)
           {
               partitioning.grid.Move(item, oldpos, newpos);
               break;
           }
       }
       
   }

actual function it calls
I do not think that any of these functions would have anything to do with it, since I'm using them elsewhere too, problem free
What happens is that I start the server, loads up and I gain like 2 gb of memory in less than a second and Unity crashes.
Weird thing is that the profiler shows as if everything was fine

#

that is normal profiler activity, but I couldn't get more data because it crashes

alpine turret
#

if and break

static matrix
#

if its crashing, it definitely isn't normal

waxen kayak
#

censorship in effect or what

#

anyway I removed the move function from the foreach and now it doesn't

soft shard
waxen kayak
#

so I guess I gotta look at that

soft shard
alpine turret
#

@spring creek I literally complimented the dudes work, you people are something else

#

dont ever dm me again

waxen kayak
#

weird because i'm not seeing any loops in it or anything that would cause memory leak

#

I'm not getting errors so I really have no clue

static matrix
#

ig I can use a rendertexture

spring creek
soft shard
# static matrix ig I can use a rendertexture

A render texture could work, I believe there is a mathematical way to convert coordinates from one system to another, though I don't remember the formula, maybe you could look into "coordinates conversion"

waxen kayak
#

okay I have reduced the problem to the ADD function

#
         public void Add(gridObj soldier)
        {
            if (!init)
            {
                return;
            }
            if (soldier == null)
            {
                Debug.Log("tryingto add null");
            }
            //Determine which grid cell the soldier is in
            Vector2 cellPos = gridIndexAtPosition(soldier.soldierTrans.position);
            int cellX = (int)cellPos.x;
            int cellZ = (int)cellPos.y;

            //Add the soldier to the front of the list for the cell it's in
            if(cellX > size || cellZ > size)
            {
                Debug.LogWarning("Object is out of the bounds of the grid partioning system, at position (" + soldier.soldierTrans.position.x + ", " + soldier.soldierTrans.position.y + ")", soldier.soldierTrans);
                return;
            }
            soldier.previousSoldier = null;
         
            gridObj gridj = cells[cellX, cellZ];
            //soldier.nextSoldier = ;
             
            //Associate this cell with this soldier
            
            cells[cellX, cellZ] = soldier;
            //Debug.Log("Added to " + cellX + ", " + cellZ);
            if (gridj != null)
            {
                soldier.nextSoldier = gridj;

                //Set this soldier to be the previous soldier of the next soldier of this soldier (linked lists ftw)
                soldier.nextSoldier.previousSoldier = soldier;
            }else
            {
            }
        }
```this is it
#

the only Void that this is calling now is gridIndexAtPostion

#

but that is literally just math```cs
public Vector2 gridIndexAtPosition(Vector3 position)
{

        int cellX = (int)(position.x / cellSize);
        int cellY = (int)(position.y / cellSize);
        if (cellX < 0)
        {
            cellX = size/2 + (-cellX);
        }
        if (cellY < 0)
        {
            cellY = size/2 + (-cellY);
        }
       // Debug.Log(position + " is at the pos, cellpos x = " + cellX + ", y = " + cellY);
        return new Vector2(cellX, cellY);
    }
static matrix
#

why does 2022 LTS editor cap my framerate? can I make it not do that

main shuttle
static matrix
#

is there a reason the camera is not seeing the world-space canvas? this is not the main camera, dont know if that matters

static matrix
#

oh wait now it isnt capping?

#

odd

#

ok but second issue is more important

#

idk why it cant see it

main shuttle
static matrix
#

yeah in either case it doesnt show

main shuttle
#

Culling mask on everything?

static matrix
#

yup

#

maybe its a priority thing?

#

oh I dont even have that setting lol because built in rp

main shuttle
#

Oh, then I don't know, I know nothing on the build in RP

hard viper
#

I have a method called in Start(). How do yield return to try to execute later within the same frame?

vagrant blade
#

You can turn the Start method into a coroutine or call another coroutine from it. However, if you're delaying a single frame, you likely have a bad order of executing your code/references.

#

You shouldn't need to delay a frame in order to solve something like an NRE

wicked river
#

So I need to create a minimap and I have the full minimap working however I need to manually place 2D cube sprites on the boarders of ALL my walls, doors and objects I want to show up on the minimap.. Is there a better way to have the minimap camera just look at all edges of a wall with X tag and render that with a color of my choice ?

tawny elm
#

for some reason this getkeydown only fires once and never again. i tried using just getkey, but then after pressing the key once, it acts like the key is still down forever. cant find out why.

soft shard
tawny elm
#

i have a similar thing for a different key thats also in Update() and this one works perfectly fine

polar marten
#

the inputs are working

#

the thing you are instantiating is interacting with the raycast in a surprising way

tawny elm
#

rite its just i thought the whole function would only be running at all if the GetKeyDown is appearing true, so if the key wasnt sticking down then it wouldnt do anything

polar marten
#

i'm not sure why you are multiplying transformdirection by 10

soft shard
# tawny elm i have a similar thing for a different key thats also in Update() and this one w...

GetKeyDown will only fire for the frame that the key was detected as being "down", and not continue, GetKey will fire for every frame the key is detected "down" and remains held "down", so if you have a high framerate, GetKey could be called multiple times within the time it takes you to lift your finger off the key, unless you are really fast, you can test this by just logging something like if(Input.GetKey(KeyCode.Space)) {Debug.Log("space hit");}

polar marten
#

it means you're not sure what's giong on

polar marten
polar marten
#

if you write debug.log inside the input.getkeydown rightshift version - notwithstanding an extremely unlikely configuration in your OS - you will see it correctly occur; if you try to replace rightshift with something else, you will still see your bug

#

focus on the raycast and the fact that you are instantiating something, which itself has a collider

#

and that you are using a very short distance

tawny elm
#

yeah i know man i get it but then whats wrong with the raycast

polar marten
#

for some reason

#

it's very blub. there's nothing wrong with the raycast per se, it's the object you are instantiating is messed up somehow

tawny elm
#

its just a cube with no scripts

polar marten
#

what is going on gameplay wise?

#

why are you choosing a distance of 10f?

tawny elm
#

i dont know why im chosing that distance man it just works fine normally

#

im making a really bad minecraft clone

#

heres how the placing goes weird when its GetKeyDown. it only places one and then never does it ever again

polar marten
#

can you looka t your console instead

#

are there errors?

tawny elm
#

and here's how it goes with GetKey. spawns them forever after pressing the key despite it not being down

tawny elm
polar marten
#

what did you put as the prefab slot that youare instantiating?

tawny elm
#

its just a cube with no script

polar marten
#

okay, but is it from your assets directory, or something in the scene?

tawny elm
#

lil man down there

polar marten
#

also, there must be more going on

#

because it's being instantiating at a raycast hit

tawny elm
#

i was honestly confused on why it was spawning on a grid tbh

#

i didnt make it do that but it did it anyway

polar marten
#

i see that you are using the hit.transform

#

that makes more sense to me

tawny elm
#

oh right yeah that does make sense

#

just didnt question it myself

polar marten
#

i don't have enough context to help i'm sorry.

#

there are a lot of things that could be wrong

#

it takes only one checkbox

#

or one error somewhere you haven't shown us

tawny elm
#

idk theres no errors coming up at all

#

the entire update function

#

apart from the object refs above it this is all the code in the project

fiery path
#

What is the easiest way to check how long is remaining in a Coroutine?

tawny elm
#

@polar marten yeah no its DEFINITELY the Input.GetKeyDown(KeyCode.RightShift()) because using the E key works perfectly fine

soft shard
hard viper
#
            => string.Join(", ", list.Select(x => x.ToString()).ToArray());

public static string ToStringUseful<T>(this List<T> list, Func<T, string> entryToString)
            => string.Join(", ", list.Select(x => entryToString(x)).ToArray());```
Is there a way to set a default value for a Func?
fiery path
hard viper
#

this would be a lot simpler if I could just set a default value for that Func

soft shard
# fiery path Simply I have three seperate booleans that need to be flipped to true at seperat...

You could either start a new coroutine for each bool, passing the time that should be waited, or what I often do is use Time.time instead of deltaTime, and check for (or in this case, yield) the difference, for example:

float timePassed;

void SomeFunc()
{
someBool = false;
StartCoroutine(SomeCo(ref someBool));
}

IEnumerator SomeCo(ref bool condition, float wait = 3f)
{
timePassed = Time.time + wait;
yield return new WaitUntil(() => Time.Time > timePassed);
condition = true;
}

There are many ways you could do more-or-less the same idea, that may be one that could let you reuse "SomeCo" for all 3 bools, unless specific logic differentiates them where you may need slightly different logic

warm kraken
#

hi guys. i have a button system where i use time.deltatime to scale buttons depending on wether or not mouse collides with them. when i pause the game using Time.deltatime = 0 command, my button code becomes useless (doesn't scale the buttons at all). short question would be: when i set time.deltatime to 0 to pause the game, what alternative system can i use to replicate multiplying by time.deltatime?

somber nacelle
#

Time.unscaledDeltaTime

warm kraken
#

this is the best discord server ever. second time in a row a random guy just solves my problem with one simple sentence. thanks

bleak tree
#

Hello, I'm developing a zombie survival game in the style of Call of Duty zombies with my classmates and there is something I'm curious about
In my gun script I'm using 2 variables for certain values, such as damage, headshot multipliers or different ammo values (current ammo, max ammo etc) since I want to be able to change these values on the fly for various different reasons, is there a way to handle this more efficiently or is this good? I can show code if needed

hard viper
#

is there a simple way to truncate a float?

#

i worry that the last digits will lead to imprecision in physics system, so my idea is to truncate position components to like 10^-6 every frame

bleak tree
#

Mathf.FloorToInt?

simple egret
#

Okay that's not truncating then

#

Truncating is getting rid of the decimal part

bleak tree
#

oh thats rounding

#

i see

hard viper
#

i currently have Mathf.RoundToInt(num * 10^6) * 10^-6

simple egret
#

Yeah, I assume that's the simplest way of doing it

hard viper
#

but i worry idk if this will really work properly on values on the order of 100 vs 10^-6

#

floats get 23 significant bits, which is worth 10^6.9 in the significand

simple egret
#

Imprecisions are everywhere anyway
10e-6 is small enough to not be noticeable

#

It's built-in, due to how floats are represented

hard viper
#

i just want to make sure I don’t actually fuck with my number outside of truncation by doing this, if my number is too big

simple egret
#

And the best way of doing it, is to not do it at all

#

10e-6 meters is one micrometer, pretty much invisible

hard viper
#

man, I took a class on this, and i don’t remember the fine details. I thought I would get 10^-16 difference in machine epsilon

#

but floats aren’t spaced like that 🤷‍♂️

lean sail
hard viper
bleak tree
#

No there is no performance issues I just wanted to know if it's good practice or not

lean sail
#

As long as it fits your need and doesnt cause massive headaches, it's as good practice as you'll need

hard viper
#

I would keep some immutable values to work with, and calculate based on thos

bleak tree
#
    public bool isReloading, headShot, powerUp;
    public float rateOfFire, damage = 25f, rof, fireDelay, headshotMultiplier, range;
    private float internalDamage, internalHeadshotMultiplier;
    public ParticleSystem muzzleFX;```
This is what I have
hard viper
#

like totalDmg = fixedGunDmg * multipliers;

bleak tree
#

I'm using the "internal" private floats to do the calculations of damage and such

lean sail
#

It is common to use scriptable object to store some initial value, then load the data from the SO. But this still means you store the same things on the gun

bleak tree
#

The public ones I use to set the value in the editor and to have a value stored to go back to after a powerup ends

hard viper
#

try not to mutate values that you plug in during inspector

simple egret
bleak tree
#

There's an empty gameObject in the scene that just has the script of the enemy hp

lean sail
#

That sounds more like something that's bad practice instead of anything with this gun script

bleak tree
#

how else am I supossed to get the hp value from the enemy at any time

#

It's not a fixed amount

hard viper
#

the enemy gameobject should have a monobehaviour with its current status

lean sail
#

The enemy should have some method somewhere, where it takes damage. Inside that, it should have access to the health

bleak tree
#

I already tried accesing directly the hp in the enemy but that has it's issues

#

For once if there are no enemies in the scene the script for the instakill powerup just doesn't work

lean sail
#

You shouldnt be accessing the enemy hp as a bullet (using bullet as example). You should just be calling some method saying "I wanna deal this much damage" and then the enemy processes that

bleak tree
#

Ah, wait actually
I think I could just have the hp value be in the GameManager

hard viper
#

this boy is going to need more help, bawsi

lean sail
#

Unfortunately I must go soon but I suggest trying to get away from any solution where your objects that deal damage, know how much hp the enemy has. Unless this is like a mechanic of your game where X targets the healthiest Y

#

A bullet would do something like
If I collide with something that can take damage
GiveDamage(x)

That something that receives damage, processes it and can adjust their own health float. This now helps centralize armor calculations or block chance for example

bleak tree
lean sail
#

If that's what it's doing then nothing should need to know the enemy hp. You can make another method to deal % health damage and then just send in 100% as a value

#

Or just an instakill method if 100% is the only percent used

hard viper
#

so, you have a relationship between one instance of A and one instance of B, right? Like player-enemy or bullet-enemy.

Both A and B need to know about themselves. This would normally be a reference to an immutable scriptable object that has specific values that apply to any of that type (eg bullet is tied to a M16 gun asset, or Rifle gun asset, all of type Gun : ScriptableObject)

#

Both A and B ALSO need knowledge of their current state in a separate script (probably in a monobehaviour). This is something like currentHP (in monobehaviour) vs maxHP (in scriptableObject. monobehaviour reads maxHP in scriptableObject to initialize…)

#

follow so far?

#

Now A and B need a way to interact with each other. Which would be like a method in B that can read info in A and in B, and can then change B’s state based on it.

#

eg B has a script with DoDamage which takes in info from both A and B. Like
DoDamage(Gun myGun) {
currentHP -= myGun.baseDamage;
}

#

understand?

#

gtg now or my wife will kill me

bleak tree
#

I am not using Scriptable Objects and I am calling the function to reduce the enemyHP directly on the function that handles firing (Using raycasts)

sonic holly
#

fellas, quick question. is it possible to have an animation in a 9 tile sprite? so having the edges be as normal and have the middle tile be animated?

bleak tree
#

Alright so I just changed it to call the death function if instakill is enabled

hard viper
sonic holly
#

there might be a better way to do that but im too dumb to think of one atm

latent latch
#

if you wanna do a shader you can just scroll the uvs

hard viper
sonic holly
#

thats what i did

sonic holly
#

but thanks anyway!

grave arch
#

Got a question about jobs, is it okay to access structs outside of a job or should you place them inside of the job itself?

fervent furnace
#

Don’t understand, can you give an example

elder chasm
#

I just started working on a 2d top down shooter and ive given my player a rigidbody2d (on kinematic) and a box collider, and the walls have a box collider, but i can still move through them, here is my code in case its needed

using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
    public float speed;
    private Rigidbody2D body;

    private void Awake()
    {
        body = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, Input.GetAxis("Vertical") * speed);
    }
}```
prime sinew
#

And are any of the colliders marked as trigger?

elder chasm
elder chasm
#

so i need to make the wall rigidbody2d on dynamic?

prime sinew
#

Are both the walls and player kinematic?

elder chasm
#

the walls only have box collider

prime sinew
#

I think it's your player that needs to be dynamic

elder chasm
#

yeah but i dont want it to fall

prime sinew
#

Then set the constraints in the rigidbody

#

Should be one for rotation

elder chasm
#

my player just falls slowly like that

#

my player is a circle if that matters at all

#

oh putting gravity scale on 0 seems to make it work

#

thank you

#

i do have another question though

#

how would i make an object rotate around the player by aiming at the mouse?

sly drum
#

Any expert on ML Agents?

spring creek
sly drum
#

Thanks!!

latent latch
#

What's a good way to store a bunch of interfaces that are implemented on a bunch of different classes throughout different namespaces. An example is my EntityRoutine class that accepts objects that implement the IEntityRoutine interface. This interfaces is used a bunch through different namespaces such as EntityAbility, EntityEffect, EntityConditions, ect, so it's quite popular. I've a bunch hanging out in global space I want to clean up is why I ask.

steady moat
latent latch
#

Ah, yeah maybe something like just a general Entity namespace

#

then have these sub-namespaces inside of it

#

Would ask something similar to some enums but I think that applies to it as well

steady moat
#

I'm not expecting to see other type of ability

weak venture
#

Are children guaranteed to be alive during awake or can I not count on that?

west lotus
#

Alive?

weak venture
#

like created. I get that if I'm referencing a different object during awake it might not exist yet. But does that also apply to children? Can a script in a parent assume its children will already be created when parent awake is called?

west lotus
#

Do they exist in the scene or are you instantiating them ?

weak venture
#

they exist in the scene

#

or if instantiated, they would be a part of the prefab and implicitly instantiated from the parent being instantiated

unreal temple
#

You control your namespace so you can always resolve collision through renaming, which is going to be a lot clearer than allowing the same name to exist in two namespaces in the same project.

sonic trench
#

hey! I'm making a game with input fields, I'm a starter so I don't really know much, so like I have it if its a string that it needs to be then it shows the gameobject, I aalready have everything but the script isn't really working, the text is equal as the string but it still somehow sees it like not equal (its a string "number")

Here is the script:

using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour
{
public InputField inputField;
public string desiredString = "1";
public GameObject correctObject;
public GameObject incorrectObject;

private void Start()
{
    if (correctObject != null)
    {
        correctObject.SetActive(false);
    }

    if (incorrectObject != null)
    {
        incorrectObject.SetActive(false);
    }
}

void Update()
{
    if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter))
    {
        CheckAndShowObjects();
    }
}

void CheckAndShowObjects()
{
    if (inputField != null && !string.IsNullOrEmpty(inputField.text))
    {
        if (inputField.text.Equals(desiredString))
        {
            StartCoroutine(ActivateAndDeactivateWithDelay(correctObject));
            Debug.Log("Correct!");
        }
        else if (!inputField.text.Equals(desiredString))
        {
            StartCoroutine(ActivateAndDeactivateWithDelay(incorrectObject));
            Debug.Log("Incorrect!");
        }

    }
}

IEnumerator ActivateAndDeactivateWithDelay(GameObject targetObject)
{
    if (targetObject != null)
    {
        targetObject.SetActive(true);
        yield return new WaitForSeconds(2.5f);
        targetObject.SetActive(false);
    }
}

}

please help me with this asap, I tried so many things!

fervent furnace
#

dont cross post

sonic trench
#

bro like I'm trying to make a game and i'm a beginner, so like yea... i'm trying to get help asap

fervent furnace
#

try log the string in inputfield first

sonic trench
#

uhhh.. how to do that :/

#

and like how do you mean that i don't really understand

#

I'm new

fervent furnace
#

Log($"entered: {inputFielt.text}")

sonic trench
fervent furnace
#

before comparsion

sonic trench
#

in the "check and show object()"?

fervent furnace
#

yes

sonic trench
#

so like before the "if"?

fervent furnace
#

yes

sonic trench
#

alr thanks

#

it still doesn't work, like it says its like correct and incorrect

fervent furnace
#

log is just showing you what is the text doesnt affect any logic after it

sonic trench
#

and it prints the right number that I entered

fervent furnace
#

i doubts that maybe some hidden chars eg zero-width space, in this case i will loop the string

#

i just realize that it is not TMP inputField

sonic trench
#

do i need to put it as tmp?

fervent furnace
#

just keep this one should be fine...havent used this before

sonic trench
#

alr

fervent furnace
sonic trench
#

so, what should I do?

fervent furnace
#

based on the posts i suggest you use textmeshpro inputfield first

sonic trench
#

yea i tried rn

#

but it doesn't let me put the tmp input fields in the script

#

like if you know what i mean

#

in the inspector tab

#

do i need to change something in the script, so then I could?

fervent furnace
#

yes you need to change it to TMPro.TMP_InputField

#

or using TMPro; then get rid of the "TMPro."

sonic trench
#

so i need to change that here?

public InputField inputField;

fervent furnace
#

yes