#archived-code-general

1 messages · Page 16 of 1

neat lagoon
#

But choosing which direction to travel and when is complicated

#

unless you were able to simplify it in some way by placing a constraint on the system (like for example, nodes will only be directly adjacent to each other in cardinal directions)

swift falcon
#

what couldve caused this distortion in cosine

regal grove
warm shadow
#

So i have this code that is suppose give in index number out but it always gives 0. Here is the code:

private Color GetSkinColor()
    {
        int colorIndex;

        int numberOfUnlockedTools = toolManagers.Where(tool => tool.Value.isBought == true).Count();

        colorIndex = Mathf.FloorToInt((numberOfColors / numberOfTools) * numberOfUnlockedTools);
        print("colorIndex: " + colorIndex + " = (" + numberOfColors + " / " + numberOfTools + ") * " + numberOfUnlockedTools);

        return colorSpectrum[colorIndex];
    }

And here is the print:
does anybody know what it is I'm missing

warm shadow
#

ohhh, i see, thanks

twilit hamlet
#

How do I assign a value to a variable only if its undeclared?

leaden solstice
twilit hamlet
#

It's declared just hasn't been assigned anything

leaden ice
#

You'd have to use a nullable

neat lagoon
#

value types are not null when unassigned, they are their default value

twilit hamlet
leaden solstice
neat lagoon
#

for example, by default, floats are 0

leaden ice
#

Why is it weird

#

They're basically primitives they can't be null

#

You could use a nullable if you want

twilit hamlet
swift falcon
#

Anyone know what couldve caused it?
transform.position += transform.right * Mathf.Cos((Time.time - startTime) * projectileFrequency) * projectileAltitude;
is what i have
should be fine but for some reason there is some weird offset

leaden ice
#

float? myNullableFloat;

leaden ice
leaden solstice
#

Nullable or use flag like bool isMyFloatSet

swift falcon
#

oh

#

hmmm

twilit hamlet
leaden solstice
#

null

swift falcon
#

oh right. start time is simply time.time in Awake function

twilit hamlet
swift falcon
#

so the bullet always starts moving from the same start

#

lemme make a gif

twilit hamlet
twilit hamlet
leaden ice
#

trying to additively do this won't be consistent

leaden solstice
#

Yeah you should make it relative to initial position

twilit hamlet
leaden solstice
#

Not accumulation

leaden ice
swift falcon
#

oh, that makes a lot of sense actually

#

thank you so much, ima take my time and try to understand it

twilit hamlet
leaden solstice
#

NullReferenceException

simple egret
leaden ice
#

Straight from the docs

simple egret
#

?? returns the thing on the right, if what's on the left is null.

leaden solstice
#

Ah it's InvalidOpertionException 😄

twilit hamlet
#

Jesus, I thought this was a quick and easy question, why do floats gotta be so weird with nulls

twilit hamlet
leaden ice
#

you're overcomplicating it tbh

dusk rain
#

I have a problem, I'm getting a null reference on this line https://i.imgur.com/JQO4ZsX.png, and its the Gamecontrols part of the code, that gives a null reference, but its not doing that for a different script with he same line of code.

twilit hamlet
#

are you kidding me

leaden solstice
#

Remove .Value there

simple egret
#

Well don't access .Value in this case

dusk rain
#

the start of the If statement

twilit hamlet
simple egret
#

Nothing, you get an error: InvalidOperationException

leaden ice
#

you'd have to show where you assigned it

dusk rain
twilit hamlet
leaden ice
#

that's just declaring it

dusk rain
#

The code that isnt working in this script, is working in other scripts though, so i'm not sure why this script cant find my inputsystem

leaden ice
#

you are in the others

dusk rain
#

oh ok

leaden ice
#

Assignment needs the = operator.

dusk rain
leaden ice
#

Why don't you just show where you're assigning it

#

so we can rule that out as the problem. So far I can only assume you just never assigned it.

dusk rain
leaden ice
swift falcon
#

oh right, i remember the issue i ran into about when using relative to initial position, like X and Y is fixed in the world, but is there some method i dont know about that could kinda make it relative to a certain vector

#

something along these lines

#

dont know how to formulate the question to google it haha

dusk rain
leaden ice
#

that field

#

it's a static field?

#

How and when is it assigned?

#

How do you know that assignment is happening before this code runs?

#

proobably just a script execution order issue

dusk rain
leaden ice
#

Go to the InputManager script

leaden solstice
leaden ice
#

show how and where inputActions is assigned

swift falcon
#

oh alright thank you

dusk rain
leaden ice
#

as I said

#

it's just a script execution order issue

#
   private void Awake()
    {
        if (inputActions == null)
            inputActions = new GameControls();
    }```
#

This is running after your other code

#

so it's still null when the other code runs

dusk rain
#

oh ok

leaden ice
dusk rain
swift falcon
#

o almost got it

#

just projectile stands in place now lol, but at least the sine is right

swift falcon
#

oh right, because i used rigidbody force as forward movement

#

when changing transform.position directly it doesnt quite work now

trim spoke
#

hey guys , i can use some help breaking my head over this for hours. my raycast drops my game from 60 to 30fps or worse. what could be the cause if anyone stumbled upon something similar?

warm shadow
#

I have a problem, so I have some things you can unlock, and some of them makes a popup show. The current way I'm doing it is every unlock have a variable that is isBought which become true when you buy it, the the popup system runs every frame and looks if the specific unlock is unlocked, and if it is it shows the popup.
The issue is now it of course keep showing even after I close it, as it is still bought. How do I fix this?
I cant change isBought because I use it in other places…

trim spoke
proper oyster
trim spoke
#

if(item is bought) => popup.setactive

than make the button linked to a function in the same screen that has a function like
popup.setactive(false)

you dont even need the variable for that

trim spoke
#

mind you im running the profiler on a pc for a game meant for android. on the phone this raycast is so bad it makes it go BURRR

proper oyster
# trim spoke about 3.4ms

for 60 fps each frame is 16.7 ms
and for 30 its 33.3
so your 3.4 ms is probably not the cause to drop from 60 to 30

trim spoke
past pier
#

Hey Guys,

I'm desperate for anwsers and apparently equally incompetent.
What on earth is causing GC allocation in this code:

public static bool IsConstructionPiece(this Piece piece) => IsType(piece, snapNodes => snapNodes.Count != 0, Type.CONSTRUCTION);

Calling:

        private static bool IsType(this Piece piece, Func<List<Vector3>, bool> isType, Enum type)
        {
            if (isType.Invoke(primarySNs))
            {
                //Debug.Log($"Piece '{piece.m_name}' { piece.transform.position} IS a {type} piece");
                return true;
            }
            else
            {
                //Debug.Log($"Piece '{piece.m_name}' { piece.transform.position} IS NOT a {type} piece");
                return false;
            }
        }

(yes - you are correct - the commented out sections cause the Enum type parameter not do do anything)
while primarySNs refers to a simple collection variable, and Type.CONSTRUCTION is an enum value

I have a lot of these "IsSomethingPiece" calls -> calling IsType under the hood. And all of them allocate quite a bit of trash.
But more importantly than improving the performance I would like to simply understand... why does this allocate?

Is this some wierd-ass clojure magic due to me dragging in a constant enum value? Is this due to extension methods... somehow? Is it the work of the devil?

proper oyster
#

so very complex ui you have?

trim spoke
twilit hamlet
#

I don't understand, the first one works fine but the second one tells me that using new on a MonoBehaviour class is not allowed. What's the Difference here? I just want to store data but im not allowed to make a new object to hold it?

trim spoke
proper oyster
proper oyster
trim spoke
simple egret
proper oyster
trim spoke
twilit hamlet
simple egret
#

Then Unity isn't picking it up

#

Either way you should never use new on anything that derives from MonoBehaviour

twilit hamlet
simple egret
#

If it's not meant to be attached to a Game Object directly, don't inherit from MB

simple egret
#

Yeah that's a result of using new on MBs

#

Or trying to attach a script that isn't a MB, onto a Game Object

twilit hamlet
simple egret
#

Yeah because now it cannot be on a game object anymore

#

If it just stores data, make a plain class

twilit hamlet
#

Oh cuz its not mono

simple egret
#

It wouldn't execute yeah

#

You would do stuff with it, from other scripts that are MBs

twilit hamlet
#

Erg so I have to decide between a data structure and a Unity Runtime structure

#

I want an encompassing objects to store all its children in a list to save

#

omgosh, this linking between class objects and monobehavior objects is making my head hurt

swift falcon
#

@leaden solstice @leaden ice just wanted to thank you! managed to figure out how it works and make it work as well

leaden solstice
#

Cat power

swift falcon
#

🐱

split furnace
#

Hi. I'm trying to make a zip line the player and the AI can go in and out of. problem I run into is that the AI can go in but they can't get out. I tried measuring vector3.distance for the line to let go once the AI reaches point but no go.

#

any suggestions?

timber snow
#

hi guyzzz!!! how do i read how deep i am i to a collider O_O

coral hornet
#

how should i logically handle a character system

#

i want 4 different chooseable characters or classes, each with heavily varied gameplay

#

and im not sure how i should handle everything from the playermodels to the code that controls them

#

should i try to set up a base character controller that can use a public variable to determine what class it is controlling? should i store each playermodel indevidually or use a base playermodel and try to tweak it to fit the appearance i want for each class? should i have an items system to determine which item each character will start with or should i hard code it into the character controller considering that you wont be aquiring any more items?

loud portal
#

why doesnt the Mathf.Clamp do anything

somber nacelle
# loud portal why doesnt the Mathf.Clamp do anything

clamping the value doesn't mean anything if you aren't using that value to assign a specific rotation. all you are doing with that value is putting it in a Vector3 then using that vector's magnitude to rotate the object.
you should search "clamp camera" in this discord to find examples of how to correctly clamp the rotation

#

and don't crosspost

loud portal
somber nacelle
#

yes well you need to go back further and click examples

indigo drift
#

I'm currently using JSON.net but when i use jsonconvert.serializeObject I get a self-referencing loop error. Strangley this only happens when the class contains a vector2 variable... how do I fix it?

twilit hamlet
#

Hey quick question, is JsonUtility.ToJson() recursive? meaning if i have a gameobject with a list of gameobjects with lists, will this turn all of that into one json or do I need to manually pass up json data?

zinc parrot
#

why are index buffers not available in builds for meshes that dont have read/write enabled?

polar marten
zinc parrot
#

yes

polar marten
#

i think it has something to do with the graphics apis

#

and read/write really means whether or not a unity object is given to you representing the graphics resource

#

because in order to make that work, it has to do some kind of synchronization step that is potentially slow

zinc parrot
#

so wait why are they available in editor but not in builds?

river lynx
#

i have a script called score on 2 game objects how can i do that a variable has the same values?

twilit hamlet
dusk rain
river lynx
#

i have a score display that shows my score. when i die i have another score display but it says 0

twilit hamlet
twilit hamlet
river lynx
#

yes that probably i just didnt want to make a new script for only one purpuse

polar marten
#

it may appear to be the same mesh in editor

#

not 100% sure

river lynx
#

how

polar marten
#

when i run into issues like these it's never "because the editor is using the single threaded graphics device and player builds are multi-threaded / native jobs"

#

it's very very rarely "because the editor is dx11 and the device is opengles 3"

twilit hamlet
# river lynx how
public class PlayerHealth : MonoBehaviour
{
    public static float health=100;
}

polar marten
#

index buffers sound too normal for that to be the issue

zinc parrot
#

hmmmm

polar marten
#

you can make sure your device and editor graphics apis are exactly th esame

twilit hamlet
# river lynx how

a static variable is one that is shared among the class. So its like a globaly shared value, exectly for what you are trying to do

polar marten
#

including unchecking multithreading

#

which will worsen performance possibly significantly

zinc parrot
#

again, if I make the mesh read/writeable in editor and build, the index buffer is available
if I dont make it read/writeable its not available
im running dx12

valid minnow
#

why am i getting an error here?

#

above the else

polar marten
#

you'll bea blet o see

#

the windows editor supports opengles3

valid minnow
#

oh i fixed it, it was the semi colon on the if statement

zinc parrot
#

device?
3080 mobile?

polar marten
#

hmm

river lynx
#

now it messed up this csharp scoremanager.GetComponent<score>().score_count++

polar marten
#

no meant GraphicsDevice as in the graphics api

#

which yes it sounds like it's the same

zinc parrot
#

ahhh

polar marten
#

i think its' some other bug and this is a red herring

zinc parrot
twilit hamlet
river lynx
#

Static member 'member' cannot be accessed with an instance reference; qualify it with a type name instead

twilit hamlet
zinc parrot
twilit hamlet
river lynx
#

also do you mean static score class? thats the class name with the variable. score_manager is just a "container"so im told

polar marten
#

if not switch to dx11

twilit hamlet
twilit hamlet
river lynx
#

oh no i have a ton of errors

#

its ok ill try the non static method first

zinc parrot
#

but the error is on the CPU side

#

saying that the index buffer is null

polar marten
#

try dx11

#

dx12 is pretty buggy until 2022.2

zinc parrot
#

I... cant run my project on dx11

mossy oriole
#

Quick question, is it better to use a timer variable and subtract from it time.deltaTime to wait for a certain amount of time or is it more performant/simple to use corroutines?

polar marten
zinc parrot
#

I have not, the thing I am making is for others to use

leaden ice
#

If this timer is not going all the time, a coroutine might be better to avoid having an Update.
But coroutines have their own costs - like garbage collection etc.
If the timer is going all the time Update is both simpler and cheaper

mossy oriole
#

Like for a jump pressed buffer it would be best to use update rigth?

leaden ice
#

probably

mossy oriole
# leaden ice probably

And couroutines for something like a loading screen that works similarly to the time-line package and that needs to be called just once?

river lynx
#

if this is my movement code
GetComponent<Rigidbody2D>().AddForce(transform.up * jumpForce);
why do i get a boost if i colide with 2 things it jumps higher (edited)

#

when colliding with platform

versed marsh
#

you die

swift falcon
river lynx
swift falcon
#

You can try

#

I dont really know how to check if its colliding with 2 objs

river lynx
#

Okay

#

And also how can I duplicate a game object through code? (A different game object not the one with the script) I’m trying to make a self generating level

#

My idea was to duplicate a platform every few meters and have a random X level in a range idk if it would work

frosty moon
river lynx
#

Thanks now can you please explain what each word is? I’m a beginner sorry

quartz folio
#

But you can use the docs to look up what Instantiate does, or what Quaternion.identity is

river lynx
#

Okay my bad

upper adder
#

I have a strange issue with the vertical rotation of my 2D character. I am using Unity's new Network for GameObject system. For example, when I flip my character on the X axis in my client, look how it acts on the host's screen. It flips like a sheet of paper, a bit like Paper Mario. It only does this when the Interpolate option is checked. I am having a bit of trouble understanding what to do to fix the problem. I have made a little video for better understanding: https://www.youtube.com/watch?v=xZeNciB7zfo

neat lagoon
#

Opposed to syncing the scale automatically

upper adder
#

@neat lagoon, so it's better to turn off synching of ScaleX ?

neat lagoon
#

Yes

upper adder
#

Okay I understand, thanks for the fast reply, I'll try that! 🙂

gusty willow
#

Anyone know what would be the preferred way to make a combat log/chat would be?
I'm wanting to use TextMeshPro so I can include symbols, and would ideally like it in a standard scrollable log
But as more text gets added it causes framerate spikes (my actual framerate is ~800, but adding text can take it down to ~8 for a few milliseconds). This is definitely noticable as it freezes the whole game (I can't thread off TMP)

I have seen some mention of this being down to TMP resizing and that it should be fixed (back in 2018), but other than that I can't see what a likely cause may be. Does anyone know of a good TMP chat/log tutorial? It feels like it would be a pretty common thing for a game

cosmic rain
gusty willow
#

I'm using one component. I have turned on profiling, but honestly I am not familiar enough with it to know how to track anything specific

#

like, it happens for roughly half a second every 10 seconds

#

(Half a second is generous, more like 100ms)

#

I was going to try multiple components, but the replies on stackoverly make me hesitant to try otherwise, though I can't imagine a text variable gaining more and more lines would do well long term?

#

(speaking on the current one-component setup)

cosmic rain
cosmic rain
gusty willow
#

Apologies, as I said, I'm not familiar with this at all really. DO you mean the frame debugger, or the CPU usage frame-by-frame in the profiler itself?

cosmic rain
gusty willow
#

Yeah, I was trying, I feel like I do get stuck on the simplest points tho. Like, how to go back frames
It says I captured 20k frames, but I can only see the latest ~300

cosmic rain
#

Yeah, you can only see the data for the last several hundred frames. Captured frames is simply to get an idea on how long the profiler was on.

#

You can increase the max kept frames in the editor preferences.

gusty willow
#

I went with just spurting a lot more logs to make it easier to capture

cosmic rain
#

Garbage collection.

gusty willow
#

And one with actual column names... 😛

cosmic rain
#

You allocate 2.7 mb every frame😱

#

That's crazy kinda

gusty willow
#

Yeah, it kinda is. I have no idea where it comes from though

twilit hamlet
#

Hey just want to check, is the GetComponent<T>() a read only? or can I use a JsonOverride to set all values at once.

gusty willow
#

the scene has.. like, 3 spheres in it and the chat

cosmic rain
cosmic rain
twilit hamlet
cosmic rain
twilit hamlet
#

wait, i just realized how stupid that is since its a function

#

my b

cosmic rain
#

Or any language that I know...

gusty willow
twilit hamlet
gusty willow
#

I mean, the obvious answer is... it's a good chunk of text and most of it gets masked off, but.. it's one component getting assigned all the logs

cosmic rain
# gusty willow

Aah. I bet it's the hypertext tags. Tmp is parsing the whole string and processing them, creating a lot of garbage in the process.

#

In this case splitting it into several components is probably the best option.

gusty willow
cosmic rain
#

One for each line. And you can use a pool of text objects.

gusty willow
#

So have a list of text and push them into a limited set of components?

cosmic rain
#

Correction: when I said "split into several components" I actually mean "split into several objects". I think that was obvious, but just in case.

gusty willow
#

like a list of 20k lines, but only 20 actual components being assigned the text?

#

based on scroll*

gusty willow
#

I'll give it a go, thanks a lot for that

#

Any advice for a more.. customised scroll bar?

cosmic rain
#

Customized in what way?

gusty willow
#

In that if I have a fixed 20 components, it won't have an actual relative scroll, right?

#

I'll just be cycling 20 objects

cosmic rain
#

Aah

gusty willow
#

Or am I getting this wrong?

cosmic rain
#

Indeed. That would be a problem.

#

You'll need to customize the scroll bar for that, you're right.
I'd start with researching how the normal scrollbars works and figuring out if you can actually adjust it to your needs via code or you'll need to code it from scratch.

gusty willow
#

Cheers for that. Also, is there a way to run the profiler on a build game? I'll look it up if it's not a simple answer

#

but I figure I may as well check what it does with an actual build for GC

twilit hamlet
#

oh hey @cosmic rain , by the way remember when we couldn't get Unity to work? well I submitted a ticket and after 2 weeks of them not replying I opened unity to keep troubleshooting and it just worked. not a single error. not a single project that wouldn't run. I thought they put out a patch or something but then they got back to me and offered a new binary to try but I told them that it magically fixed itself.

cosmic rain
gusty willow
#

Thank you again, Really appreciate your time on this. It might seem simple to you, but I was banging my head over it 😛

cosmic rain
twilit hamlet
orchid bane
#

If I try to stop my coroutine does the parameter matter? Does it have to be the same as it was when I started it?

cosmic rain
orchid bane
#

Thanks

cosmic rain
#

Just to clarify: you don't stop it the same way you start it. You need a reference to your coroutine instance to stop it.

orchid bane
#

You helped me to remember, yeah

#

So if I stop my coroutine, at what point will it stop? At random point in the coroutine or at the yield?

cosmic rain
#

In the latter case it would still probably get to the yield.

pale stream
#

I have a quick question. When we try to run the game in the unity engine it runs fine, but when we build and run it, the triggers don't work. We have been trying to figure it out for hours now... Any Ideas?

dusk apex
pale stream
untold stream
#

I have text that is supposed to be shown on a screen. the only issue is I was hoping I could apply a fisheye filter to the test to simulate the rounded screen. how could I do this??

digital meadow
leaden ice
digital meadow
#

the settings I use

leaden ice
digital meadow
#

I currently use my own script but I also tried Cinemachine and had the same Problem

digital meadow
#

yeah wait

leaden ice
#

(I do recommend Cinemachine 😉 )

digital meadow
undone plaza
#

Hi guys
Wanted to ask
Is it correct to use UnityEvent to handle input?

orchid bane
#

As you wish

undone plaza
#

Thanks mate

leaden ice
undone plaza
#

I mean if I should do it

cosmic rain
leaden ice
#

Can UnityEvent somehow be involved in input handling? Sure.

#

depends on how you're using it

#

what you're doing

#

etc

undone plaza
#

Keyboard and mouse (not mouse movement) input

#

Is it responsive enough?

leaden ice
#

wdym by responsive?

#

again what are you trying to do - how is UnityEvent involved?

undone plaza
#

If i detect some input I call some action

leaden ice
#

Ok what would be a problem with that?

undone plaza
#

Idk, is there any problem with that?

#

That's my question

leaden ice
#

Like what?

elfin vessel
#

hey, what does this error mean?

undone plaza
leaden ice
#

wdym by "fast"? It's fine

undone plaza
#

It is a fps test, so it shouldn't feel laggy or something like that

#

It should feel instantaneous

leaden ice
#

You think invoking one UnityEvent is going to have impact on your framerate??

#

if you're really concerned, do it and check the profiler

#

you probably won't even be able to find it

undone plaza
#

Wellp, that's enough for me

leaden ice
#

If invoking a single UnityEvent in a frame was a problem they wouldn't even be in the engine

undone plaza
#

And have a good night

cyan kernel
#
void Update()
    {
        if(throwable != null && Input.GetMouseButtonDown(0))
        {
            throwable.DisableObjectGravity();
        }

        if(throwable != null && throwable.beingCarried)
        {
            UIManager.Instance.AddInfo("THROW (RIGHT MOUSE CLICK)");
            if (throwable.touchWall)
            {
                throwable.EnableObjectGravity();
                UIManager.Instance.CleanInfo();
            }

            if (Input.GetMouseButton(1))
            {
                throwable.EnableObjectGravity();
                throwable.rb.AddForce(playerCam.forward * (throwForce * Time.deltaTime), ForceMode.Impulse);
                UIManager.Instance.CleanInfo();
            }
        }
        else
        {
            Ray ray = new Ray(playerCam.position, playerCam.forward);
            RaycastHit hit;
            Debug.DrawLine(ray.origin, ray.origin + ray.direction * pickRange, Color.green);

            if (Physics.Raycast(ray, out hit, pickRange) && hit.collider.CompareTag("Throwable"))
            {
                throwable = hit.collider.GetComponent<Throwable>();
                UIManager.Instance.AddInfo(hit.collider.gameObject.name + "(LEFT MOUSE CLICK)");
            }
            else if (throwable != null)
            {
                float distance = Vector3.Distance(throwable.transform.position, transform.position);
                if (distance > pickRange)
                {
                    UIManager.Instance.CleanInfo();
                    throwable = null;
                }
            }
        }
    }
#

hey guys, since TriggerEnter and Exit are more expensive than using raycasts, I changed my code to help with that. But the problem is that the ray doesn't move from place while in play mode, although in debug it moves correctly like I want to (maybe Update updates differently from DrawGizmos?). Can someone help me fix this problem, which I think is due to the parent of the camera - because when I move it the raycast also moves but I don't understand why and how can I fix it. Thanks!

#

yellow represents the debug.drawray and the green the current state in update

#

also hierarchy

leaden ice
#

since TriggerEnter and Exit are more expensive than using raycasts
That's usually not the concern when deciding which of those two to use but ok...
Ray ray = new Ray(playerCam.position, playerCam.forward);
Your ray is explicitly being drawn from the camera's position in the direction the camera is facing so of course it depends on the camera position.

cyan kernel
leaden ice
#

how is that different from play mode

cyan kernel
#

That's why I made this post. As you can see in the code I posted, I created a ray that should update based on the playerCamera. I tried debugging using Debug.DrawRay on the Update function (the green ray on the video) and also in OnDrawGizmos (the yellow ray) and you can see that they display different results although I'm using the same code

leaden ice
#

show the whole script

cyan kernel
#

word limit

leaden ice
#

use a paste site

cyan kernel
#

it only has this more

    {
        Debug.DrawRay(playerCam.position, playerCam.forward * pickRange, Color.yellow);
    }```
#

its just this

leaden ice
#

I mean pretty sure those are equivalent but why didn't you just literally write the equivalent code

#

ALso you don't need to use OnDrawGizmos for Debug.DrawRay - it's only for Gizmos.DrawXXX stuff

cyan kernel
leaden ice
# cyan kernel

it's unclear to me why in your video it doesn't look like the camera is moving around

#

it looks like a light is moving around

#

I'm guessing you have just mixed up an object reference somewhere

cyan kernel
#

it's a flashlight, the camera moves on play mode

leaden ice
#

and seeing the rest of the code may help

#

Also knowing which object in the hierachy is assigned to playerCam

cyan kernel
#

the main camera

#

That's all the code for that script

#

I wish I could explain it better to you but I don't know what else to say lol

leaden ice
#

Also making sure you've assigned the camera correctly

#

and knowing for sure there isn't another copy of this script in the scene

#

etc

cyan kernel
#

What code do you want? Do you want a specific script? The script is all there

cyan kernel
leaden ice
#

You missed something, that's why you're here

cyan kernel
#

It's all right

leaden ice
#

Do you want help or not

cyan kernel
#

But it has nothing to do with the hierarchy or not assigning correctly, I'm sure of it

leaden ice
#

People have been sure of things before and been wrong

#

Do you have any other copies of this script in scene?

#

How have you confirmed not?

cyan kernel
#

Of course I want help, that's why I came here, I'm not trying to be rude

leaden ice
#

I'm also not trying to be rude, just asking for more information so I can help

cyan kernel
leaden ice
#

just manually?

cyan kernel
#

yeah

leaden ice
#

Have you done a t:MyScript search in the hierarchy?

#

Have you done this search at runtime?

cyan kernel
#

Yes

#

no runtime, how do I do it?

#

okay I checked it, only on the player

leaden ice
#

And you're sure there's only one copy on the player?

cyan kernel
#

I'm pretty sure it has something to do with the parent of the camera

cyan kernel
#

i'm going to send a video and try to explain

leaden ice
# cyan kernel yes

I mean one possibility is your camera in Update is being reset to the identity rotation and then some other script such as CM points it at the target

#

any scripts which deal with camera rotation might be helpful to see

cyan kernel
#

Ok, so as you can see when i change the rotation and position of the CamHolder that is the parent of the Main Camera playerCam it also moves the raycast

leaden ice
cyan kernel
#

I have a pretty simple MouseLook script that is on the MainCamera:

{
    [SerializeField] private float sensX;
    [SerializeField] private float sensY;

    [SerializeField] private Transform playerDir;

    private float xRotation = 0f;
    private float yRotation = 0f;

    private void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    private void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * Time.deltaTime * sensX;
        float mouseY = Input.GetAxis("Mouse Y") * Time.deltaTime * sensY;

        yRotation += mouseX;
        xRotation -= mouseY;

        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.rotation = Quaternion.Euler(xRotation, yRotation, 0f);
        playerDir.rotation = Quaternion.Euler(0f, yRotation, 0f);
    }

}```
leaden ice
#

you shouldn't multiply mouse input by deltaTime btw

cyan kernel
leaden ice
#

it's going to make things stuttery

cyan kernel
leaden ice
#

what is playerDir

leaden ice
cyan kernel
#

it's a child of the player

leaden ice
#

Orientation?

cyan kernel
#

yeah

leaden ice
#

CamHolder has no components on it (other than Transform)?

cyan kernel
#

that's what i was going to say now lol

#

it has a move camera script that makes the camera follow around the player, it basically just changes the position of the camholder to be the same as the camposition (child of player)

#
    
    void Update()
    {
        transform.position = cameraPosition.position;
    }```
#

I did this so the Player and Camera stayed separated

leaden ice
cyan kernel
#

I place it in the camholder or the camposition?

leaden ice
#

it replaces your small script here

cyan kernel
#

how does it work

#

what do i change?

leaden ice
#

you give it a target

#

and it will follow that target

cyan kernel
#

and put the weight to right

leaden ice
#

it also handles offsets, weighted following of multiple targets etc...

#

anyway...

#

as for your actually original question, I'm still not sure 🤣

#

you're sure that green gizmo isn't drawn by a different script?

swift falcon
#

how to stop texture bleeding from an atlas in a minecraft game?

cyan kernel
west sparrow
swift falcon
cinder kindle
#
        if (Input.GetMouseButtonDown(0))
        {
            while (Input.GetMouseButtonDown(0))
            {
            GunInfo gunInfo = new GunInfo();
            float fireRate = gunInfo.fireRate;

            StartCoroutine(waiter(fireRate));
            items[itemIndex].Use();
            }
        }

Does anyone know how I can get the info of the current gun?

leaden ice
clever spade
#

also creating new GunInfo every single time

leaden ice
#

Wdym by "info"

cinder kindle
clever spade
#

if you want information from something then it needs to be referenced

cinder kindle
# leaden ice Wdym by "info"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(menuName = "FPS/New Gun")]
public class GunInfo : ItemInfo
{
    public float damage;

    public float fireRate;
}


leaden ice
#

How are you associating these with different guns

#

And why are you writing a while loop

#

And why are you creating a new one

cinder kindle
cinder kindle
leaden ice
#

I would expect a collection of GunInfo somewhere

#

Or at the very least a single reference to the current gun

cinder kindle
#

wait

#

I can move it out of the player controller

#

into another script

#

that has the reference

#

the main script

#

that fires the gun

#
    void Shoot()
    {
        Ray ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f));
        ray.origin = cam.transform.position;
        if(Physics.Raycast(ray, out RaycastHit hit))
        {
            hit.collider.gameObject.GetComponent<IDamagable>()?.TakeDamage(((GunInfo)itemInfo).damage);
            PV.RPC("RPC_Shoot", RpcTarget.All, hit.point, hit.normal);
        }
    }

Would this work?

#

If I put it somewhere in there *

upper adder
#

I am having trouble figuring out how to implement the network variable so that it is applied to all clients and the host. I want my 2D character to flip horizontally on all clients, as well as on the host. Currently, the host can move and the clients can see the host move, and the host can see the clients move. However, I am experiencing difficulty syncing the flipX for the sprite renderer across all clients and the host.

I'm pretty sure I have to do something in OnValueChanged but damn I can't find out...

If someone can help me, full code is here: https://forum.unity.com/threads/i-am-having-difficulty-understanding-networkvariable.1386966/

thin kernel
#

Hello. Anyone know some good tools to visualize ur code structure? I just want to see the hole simplified picture of my projects, with decisions I made and class dependences.

cosmic rain
trim spoke
#

Hi guys , please help. have a raycast performance issue. but i dont even use it. how can you find the source object the uses it? profiler doesnt mention any script/object

west lotus
#

Enable deep profiling

trim spoke
#

enabled , one sec sending shot

west lotus
#

Thats the ui raycaster...interesting why its taking 3 ms

#

It would seem that the raycaster is being called for every object in the canvas when you move the mouse for example. So I guess you have 179 ui objects. My solution. Split your ui into multiple canvases each with its own graphics raycaster and remove the one from the root canvas

#

That way it wont iterate over disabled objects

mossy snow
#

how many GraphicRaycasters are in your scene?

trim spoke
#

Problem found. I had many text prefabs instantiate with raycast component attached to them

scarlet bane
#

Im making a game, and the main damage is throwing explosive projectiles at enemies

#

But as the game progresses, as i shoot multiple projectiles and hit multiple enemies

#

It get laggy

woeful leaf
#

Do the projectiles despawn?

scarlet bane
#

What in my code / project should i look at to reduce lag?

scarlet bane
woeful leaf
#

In what way

scarlet bane
#

Destroy

woeful leaf
#

Hm

scarlet bane
#

I have reference images

#

ive given to them

woeful leaf
#

Maybe consider implementing pooling

scarlet bane
#

should i remove those

#

What that revolve around?

woeful leaf
#

I don't know the context of that reference

woeful leaf
scarlet bane
#

What would that involve*?

main shuttle
#

Profile the problem first. Currently your just guessing what the problem is.

woeful leaf
#

Making it so that you don't Destroy objects, but set them inactive to reuse them first

scarlet bane
#

My enemies are 2d animation based, but i use an image to check sizing

woeful leaf
thin aurora
#

This is most likely not too related to pooling but it's a good idea to start with this

woeful leaf
#

Yup

thin aurora
woeful leaf
#

If you could share code that'd help

scarlet bane
#

Yeah im ok to share code

#

Its just that idk where to start

#

I could break down how i go about things

woeful leaf
#

I don't know how large it is, but I'd just share the relevant code

#

Probably in paste sites by the sound of it

scarlet bane
#

Yeah ill do it after but ill tell u the gist of it first

woeful leaf
#

Sure

scarlet bane
#

So first I suck up a bunch of enemies, they are stored into a list.

#

I intend this to be a wave ebased game

#

Then shoot them out

#

But as a seperate projectile object

hexed pecan
#

Are you using some physics query like Physics.OverlapSphere?

scarlet bane
#

E.g. i suck up 6 enemies (set them inactive) then instantiate 6 projectile gameobjects

#

After the projectile game objects collide, they destroy itself, then instantiate the sucked enemy

woeful leaf
scarlet bane
#

Then instantiate an a explosion for each projectile collision that does damaage to each enemy hit

woeful leaf
#

Roughly, how many objects are you creating at once?

scarlet bane
#

So e.g. the 6 projectiles collide with a wall then 6 enemies are spawned in the collision place and then 6 explosions are

#

instantiated then destory + damage calculation

main shuttle
#

It's purple though UnityChanClever

scarlet bane
#

yuh

#

but the thing i think lags it

woeful leaf
#

But it doesn’t lag at the start?

scarlet bane
#

is that each explosion can hit each of the one enemy

#

so there will be 36 collisions

#

with explosion and enemies

hexed pecan
#

Start with sharing the code?

scarlet bane
#

Sure

#

Uh is there a format i have to share it in

#

Im new to this

main shuttle
woeful leaf
#

^

woeful leaf
scarlet bane
#

Alright one moment

main shuttle
#

Still, if you would profile it, you would know if the instantiation is the problem, the explosions effects, or the physics checks are the problem. Maybe a combination.

scarlet bane
#

Im not quite sure

#

I think its the fact that this collision i sent

#

can happen alot of times

hexed pecan
#

name.Contains doesnt look very good

scarlet bane
#

Yuh, its my first time using unity lmao

hexed pecan
#

(Regardless of any of this speculation, profile it)

scarlet bane
#

I know my design and style is bad

#

Not sure what that even means 😭

#

I should be in beginner chat

thin aurora
#

Code for damagePopup?

lyric moon
#

if i reference something in a scene (in a script that is not in that scene) and then unload and reload that scene, will that reference still work?

thin aurora
scarlet bane
#

I already know there will be alot of problems

thin aurora
#

Hmm, maybe just use the profiler

hexed pecan
thin aurora
#

Nothing weird in these scripts

#

Pooling will definitely help if you have this instantiate often

scarlet bane
#

Do u think it would lag

thin aurora
#

But it should not lag

scarlet bane
#

if that code that to run in one instant like 40 ish times?

main shuttle
#

Also, instantiating world UI objects without a pool seems inefficient to me, afaik they are quite expensive.

scarlet bane
#

So maybe pooling?

woeful leaf
#

100% pooling

#

Like the best it can do is improve your performance

#

The worst it can do is still just have a better system kek

scarlet bane
#

Yeah fair

woeful leaf
#

So it’s a win win

scarlet bane
#

How taxing is having to instantiate an extra image

woeful leaf
#

You’d have to profile that

#

Just go apply pooling and see what that does

scarlet bane
#

Alright, i should do some more testing to delve into what lags

#

ill try taking out the damage canvas

#

also

#

and the hp canvas

#

to see if that changes anything

woeful leaf
#

Profiler

scarlet bane
#

O

#

Sorry I thought u guys were talking about note taking or something

#

Didnt profile was for checking performance

#

Apologies

woeful leaf
#

Also do the compare thing Osmal said

main shuttle
#

Ah, that explains it 😅

#

Was wondering why you just wouldn't open the profiler

scarlet bane
#

Also i was making a mobile app

#

And the thing is about the lag, is that u dont usually lag until late into the game

#

And u cant get late into the game without playing on the mobile

#

LOL

#

I havent been doing much testing till recently

#

So i should just make some testing scripts

woeful leaf
#

You should look into how you use the profiler

scarlet bane
#

Yeah definitely

woeful leaf
#

Maybe something is somehow hogging a bunch of memory

#

Since it is something long-term

scarlet bane
#

I have one more main problem

#

So i had my designer design a start menu screen

#

And i was gonna add buttons overtop the menu screen he drew

woeful leaf
#

Is it a coding problem

scarlet bane
#

Yeah

woeful leaf
#

Okay, fair, continue

cosmic rain
#

Mobile are susceptible to overheating. When they do, they throttle down performance.

scarlet bane
#

But Im not sure

cosmic rain
#

High and often resources usage can make mobile devices heat up faster.

scarlet bane
#

How to make the buttons stay consistent with the location of the menu screen background

#

Instead of relative to resolution

#

of the mobile screen

#

Im not sure if u guys get what i mean

scarlet bane
scarlet bane
woeful leaf
#

Try harder lol

real anvil
#

Does Unity have a way to calculate GPU VRAM usage at runtime?

#

Im running out of VRAM and need to cap it before the app just kills itself

scarlet bane
#

But i doesnt make the button stay same position relative to the background image

real anvil
#

Can't profile it

woeful leaf
#

What

real anvil
#

Runtime on iOS I should say sorry

#

And it's user generated

#

So I can't predict how much will be used

scarlet bane
#

NVM I see gotta anchor to the image

woeful leaf
slender nacelle
#

hi guys, im trying to user the profiler to identify an issue in my code, but im not sure how to use it to drill further down into the issue, atm it just says this one script is consuming all the resources, but the update functional does a few things, is it possible for this profiler tool in unity to help me narrow it down further?

cosmic rain
#

But from the look of it, the issue seems to be with memory allocations, so it shouldn't be hard to identify the culprit.🤔

slender nacelle
#

yeah like creating something over and over again, i reckon.. but i dont think i am..

outer radish
#

Hello, i am trying to get the height and width of a texture2D but unity always limits the texture to 2048x1024 although I changed the MaxSize in the settings of the Texture to 4096. Does anyone know why?

outer radish
woeful leaf
#

I don't think this is code releated

#

I've got a question about inheritence, I don't quite understand how to work with constructors in combination with inheritence. I'm trying to run the inherited constructor, if even properly possible
This is currently my code

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

public class MainMenuButton : MonoBehaviour
{
    public Button button;
    public UnityAction onClick;

    public MainMenuButton(UnityAction onClick) 
    {
        button = GetComponent<Button>();
        this.onClick = onClick;
        button.onClick.AddListener(onClick);
    }

    private void OnDisable()
    {
        button.onClick.RemoveListener(onClick);
    }
}
using UnityEngine;
using UnityEngine.Events;

public class Quit : MainMenuButton
{
    public Quit(UnityAction onClick) : base(onClick)
    {
        onClick = Die;
    }

    private void Die() 
    {
#if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
        print("I quite the damn game");
#else
    Application.Quit();
#endif
    }
}
#

I'm trying to run the base in in the latter

#

But not sure how to

slender nacelle
#

you cant use a constructor with monobehaviours its done automatically by unity im pretty sure

#

you can only instantiate a monobehaviour

woeful leaf
#

So what I'm trying to do isn't possible?

slender nacelle
#

i dunno what youre trying to do sorry

late lion
#

But if this wasn't a MonoBehaviour, it still probably wouldn't work because it looks like you're trying to set onClick = Die before the base constructor is called. : base(args) will run the base constructor first. There's no way to run the base constructor after the derived one.

woeful leaf
#

Ah so it's an order of execution issue

#

That is unsolvable

late lion
#

But Sirix's point also stands. You cannot use constructors with MonoBehaviours.

woeful leaf
#

Righty, thanks for the info

#

I suppose it's time for me to figure out a different approach then heh

late lion
#

If you instead have an Initialization method, then you can more finely control the order of things

#

Make it virtual in the base class and override it in the derived class. Then you can choose when to call base.Initialize(args) in the derived override

woeful leaf
#

Yeah I suppose I could replace the constructor with a method like that

woeful leaf
slender nacelle
# cosmic rain You can place profiler markers to profile specific piece of code. Check the Prof...
    private void Update()
    {
        Profiler.BeginSample("Unit Update");
        GridPosition newGridPosition = LevelGrid.Instance.GetGridPosition(transform.position);
        if ( newGridPosition != _gridPosition )
        {
            GridPosition oldGridPosition = _gridPosition;
            _gridPosition = newGridPosition;
            
            LevelGrid.Instance.UnitMovedGridPosition(this, oldGridPosition, newGridPosition);
        }
        Profiler.EndSample();
    }

this code was fine previously and i dont think anythings changed but this is like 99.5% of the GC calls

    public GridPosition GetGridPosition(Vector3 worldPosition)
    {
        return new GridPosition(
                Mathf.RoundToInt(worldPosition.x / CELL_SIZE),
                Mathf.RoundToInt(worldPosition.z / CELL_SIZE),
                Mathf.RoundToInt(worldPosition.y / CELL_SIZE)
            );
    }

dunno how else to do this but i dont think this should be that bad?

late lion
slender nacelle
#

yes

#

am i reading this right?

late lion
#

If you change it to a struct, like Vector3, then there will be no GC.Alloc from creating thhem.

slender nacelle
#

like no jk though, a week ago these calls had no issue, what the heck did i change

#

its all the same

#

i switched from an array to a list... but... this code doesn't interact with that

late lion
#

Are there more of them?

slender nacelle
#

yeah, im aware of structs etc , didnt think i needed to use them for this

#

more what sorry

late lion
#

More units

slender nacelle
#

just 1 unit in the game with this test

clever spade
#

@woeful leaf just skimmin a bit through here but Start was ment to be used in place of constructors. You can override the start method

late lion
slender nacelle
#

the heck

woeful leaf
slender nacelle
late lion
slender nacelle
late lion
slender nacelle
#

hmmm

crimson crow
#

GridPosition newGridPosition = LevelGrid.Instance.GetGridPosition(transform.position) this will make a new GridPosition every frame

cosmic rain
#

Also, what's subscribed to the event?

slender nacelle
# cosmic rain What do these remove and add methods do?
    public void AddUnitAtGridPosition(GridPosition gridPosition, Unit unit)
    {
        GridObject gridObject = gridObjects.FirstOrDefault(g => g.gridPosition == gridPosition);
        if (gridObject != null) 
        {
            gridObject.AddUnit(unit);
        } 
        else
        {
            //throw excpetion? 
            Debug.LogError($"No GridObject at position {gridPosition}");
        }
    }
#

i think this is it... right

cosmic rain
#

And remove?

slender nacelle
#
    public void RemoveUnitAtGridPosition(GridPosition gridPosition, Unit unit)
    {
        GridObject gridObject = gridObjects.FirstOrDefault(g => g.gridPosition == gridPosition);
        if (gridObject != null)
        {
            gridObject.RemoveUnit(unit);
        }
        else
        {
            //throw excpetion? 
            Debug.LogError($"No GridObject at position {gridPosition}");
        }
    }

same thing basically

#

nah that can't be it these aren't called often

cosmic rain
#

What are grid objects? Where do you populate the collection?

#

Or, I guess it's not.

late lion
#

With this many allocations with only 1 unit, there must a loop somewhere. Does gridObjects only contain one object?

slender nacelle
#

gridobject has a list of units

#
    public GridObject(GridPosition gridPosition)
    {
        this.gridPosition = gridPosition;
        _unitList = new List<Unit>();
    }
cosmic rain
slender nacelle
# cosmic rain Where do you construct it?
        foreach (Cell cell in world.Cells)
        {
            GridPosition gridPositionOfCell = new GridPosition(cell.X, cell.Y, cell.Size.Z);
            GridObject gridObject = new GridObject(gridPositionOfCell);
            gridObjects.Add(gridObject);
        }

in awake of levelgrid

mental rover
slender nacelle
#

i dunno, was trying to figure it out, havent used the profiler before haha

cosmic rain
slender nacelle
#

checkin

cosmic rain
#

Actually nvm. That doesn't matter much.

slender nacelle
#

400.. not that many i think?

#

which is right for my map anyway

cosmic rain
#

I'd use the memory profiler to see what takes the memory.

slender nacelle
#

whats the memory profiler called?

#

dw ill google it, thanks for the help

cosmic rain
#

Can you share the whole code of GridPosition

slender nacelle
# cosmic rain Can you share the whole code of GridPosition
using System;
using UnityEngine;

public struct GridPosition : IEquatable<GridPosition>
{
    public bool Equals(GridPosition other)
    {
        return this == other;
    }

    public override bool Equals(object obj)
    {
        return obj is GridPosition other && Equals(other);
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(x, z);
    }

    public int x;
    public int z;
    public int yLevel;

    public GridPosition(int x, int z, int yLevel)
    {
        this.x = x;
        this.z = z;
        this.yLevel = yLevel;
    }

    public override string ToString()
    {
        return $"x: {x}; z: {z} lv: {yLevel}";
    }

    //BUG: this isn't checking yLevel
    public static bool operator ==(GridPosition a, GridPosition b)
    {
        return a.x == b.x && a.z == b.z;
    }
    
    public static bool operator !=(GridPosition a, GridPosition b)
    {
        return !(a==b);
    }
    
    public static GridPosition operator +(GridPosition a, GridPosition b)
    {
        return new GridPosition(a.x + b.x, a.z + b.z, a.yLevel + b.yLevel);
    }
    
    public static GridPosition operator -(GridPosition a, GridPosition b)
    {
        return new GridPosition(a.x - b.x, a.z - b.z, a.yLevel - b.yLevel);
    }
}
cosmic rain
#

Oh, so you changed it to struct?

slender nacelle
#

oh.. lol i must have...

#

sorry i forgot

#

ages ago

cosmic rain
#

So is it any different now? The profiler data.

slender nacelle
#

no sorry, i did this change months ago when it was working fine

#

trying to figure out how to install this memory analysis - got it

cosmic rain
slender nacelle
#

is it possible the event is sub'd to something that doesn't show in the code?> i think ive had something like that before

cosmic rain
#

Although... It's weird that the profiler is not being precise about it.

slender nacelle
#

like its an old thing

cosmic rain
#

You can find all references in the ide.

mental rover
#

you can use the profiling markers around specific blocks to narrow it down further

#

can you also remove the Profiling.BeginSample lines and check again (it's likely irrelevant, but you're actually profiling the profiling at the moment as well)

slender nacelle
#

it says this block is also really bad but like...

    private void HandleSelectedAction()
    {
        Profiler.BeginSample("HandleSelectedAction Update");
        if (Input.GetMouseButton(0))
        {
            GridPosition mouseGridPosition = LevelGrid.Instance.GetGridPosition(MouseWorld.GetPosition());

            if (selectedAction == null)
            {
                return;
            }

            if (!selectedAction.IsValidActionGridPosition(mouseGridPosition))
            {
                return;
            }
            
            if (!selectedUnit.TrySpendActionPointsToTakeAction(selectedAction))
            {
                return;
            }
            
            SetBusy();
            selectedAction.TakeAction(mouseGridPosition,ClearBusy);
            OnActionStarted?.Invoke(this, EventArgs.Empty);
        }
        Profiler.EndSample();
    }

its only running when the mouse is down

#

the heck

#

invoking some event on update? i must be

mental rover
#

BehaviourUpdate captures all classes that are using Update()

slender nacelle
#

or is that when i press mouse down? and it runs that event

mental rover
#

you've linked 3 images with different classes using Update

slender nacelle
mental rover
#

just trying to help you identify the issue - your first post was in the update call of UnitActionSystem, but then you linked another in Unit, and this one is in EventSystem

#

I'm not sure if you're shifting code around/renaming it

slender nacelle
#

yeah there is a few going on 😅

#

im not there are just a few GC allocs in a few functions

slender nacelle
# cosmic rain This is not Update though
    private void Update()
    {
        if (isBusy)
        {
            return;
        }

        if (!GameManager.Instance.HasBattleStarted())
        {
            return;
        }

        if (TurnSystem.Instance.IsEnemiesTurn())
        {
            return;
        }

        if (EventSystem.current.IsPointerOverGameObject())
        {
            return;
        }

        if (TryHandleUnitSelection())
        {
            return;
        }

        HandleSelectedAction();
    }
cosmic rain
#

Can you remove the useless profiler samplers and enable deep profiling?

mental rover
#

in the profiler Update() calls will show under BehaviourUpdate as {ClassName}.Update() [Invoke]

slender nacelle
#

yep will do now

#

omg deep is working wonders

#

ok i know where to start looking

#
    private PathNode GetNode(int x, int z, int yLevel)
    {
        GridPosition gridPosition = new GridPosition(x, z, yLevel);
        return _pathNodes.FirstOrDefault(pn => pn.GetGridPosition().x == gridPosition.x &&
            pn.GetGridPosition().yLevel == gridPosition.yLevel &&
            pn.GetGridPosition().z == gridPosition.z);
    }
clever spade
#

That's being called every update?

slender nacelle
#

no

#

wait what

#

it should run this once when i move then thats it

#

not continously

clever spade
#

how many tiles do you have exactly?

slender nacelle
#

~400

#

turn based game though

clever spade
#

im going to assume the best and say that is 20x20

slender nacelle
#

yep

cobalt wraith
#

HEya!
What would be a good way to approach IK for legs?
My goal is to let the feet/legs/knees bend naturally, depending where the character stands.

#

I currently have a ray shooting down from the characters feet, and changing the collider accordingly so the feet match

#

If that made any sense x)

slender nacelle
#

yep ive fucking found it..

cosmic rain
# slender nacelle

Seems like it's your pathfinding system.
The allocation is probably from Linq.

slender nacelle
#

im pretty sure

#

yeah

#

while the unit is moving around im constantly checking for a path

clever spade
#

that and you should cache "GridPosition(x, z, yLevel);"

slender nacelle
#

it should just it once

#

yeah 100% ive recently refactored a bunch and havent finished it cause i ran into this issue

#
           var pathFound = Pathfinding.Instance.FindPath(unitGridPosition, gridObject.gridPosition, out int pathLength);
            if (pathFound == null)
            {
                continue;
            }

its this code im certain

mental rover
woeful leaf
thin aurora
# woeful leaf I've got a question about inheritence, I don't quite understand how to work with...

I did not read anything about this but if you want to create a proper system for this, you might want to create a general "initialization" method that is virtual. You can then call this method and override if needed. You can also go one step further and create your own Instantiate method that will invoke this method using reflection, but this will have a hit on performance. You can look into adding source generation for this if you know how to do it.

thin aurora
late lion
#

And then the derived class just overrides OnClick

public class Quit : MainMenuButton
{
    protected override void OnClick()
    {
        #if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
        #else
        Application.Quit();
        #endif
    }
}
woeful leaf
slow crag
#

What is the best way to get correct world-space coordinates regardless of my camera angle? In this video, you can see that when the camera is top-down, it correctly displays coordinates of tiles in the tilemap. However, when I change perspective, it gets screwed up.

mossy snow
#

project ray onto plane of tilemap, use GridLayout's WorldToCell to get tile coordinates. Hard to provide any other information when you don't say how you're doing it now

lament bear
#

Hello,
I have a 2D grid-based game with some randomly generated levels. I can spawn objects on the grid, but I want to randomly instantiate several 2x2 (grid cell) prefab objects as well, which should fit into valid patches of the cell grid (i.e. playable space, and not cut into walls).

Is there a best practice for evaluating available spaces that the object can go? I can think of many approaches to this, but my ideas all have either flaws or generate more overhead than I'd like.

For example, if I loop through the available cells, I can easily check if there's space, but then I am severely weighting the chance of instantiation towards the earlier coordinates. I want a roughly equal chance to appear at all possible positions. I could loop through and log all possible positions into a list, but that seems extremely cumbersome. I feel like there's a method I'm overlooking.

slow crag
#

Thanks EvilReeper, that worked.

autumn cipher
#

how do you find the point of where the raycastall gets out of the collider?

#

when you shoot a ray through a box, I'm trying to find the end point of the raycast

autumn cipher
past pier
#

Brain twister: how the hell does this method allocate?
private static List<Box> FindBox(Piece piece) => FindSidesOfBoxOrCube(piece, FormValidTwoDimensionalBoxSide, OneSideAllowed);
Not the method it calls. THIS method.

However just in case, for completeness sake:

        private static List<Box> FindSidesOfBoxOrCube(Piece piece, Func<Vector3, Vector3, Vector3, Vector3, bool> isValidSide, int numberOfSides)
        {
            boxes.Clear();
            var boxName = 'A';
            var snapNodes = piece.PrimarySnapNodes();
            for (var i = 0; i < snapNodes.Count; i++)
            {
                for (var j = i + 1; j < snapNodes.Count; j++)
                {
                    for (var k = j + 1; k < snapNodes.Count; k++)
                    {
                        for (var l = k + 1; l < snapNodes.Count; l++)
                        {
                            if (isValidSide.Invoke(snapNodes[i], snapNodes[j], snapNodes[k], snapNodes[l]))
                            {
                                boxes.Add(new Box(boxName++, snapNodes[i], snapNodes[j], snapNodes[k], snapNodes[l]));
                            }
                        }
                    }
                }
            }

            return boxes;
        }

(the boxes list as you see is not initialized but reused from the static context of the struct)

And:
private static bool FormValidTwoDimensionalBoxSide(Vector3 snapNodeA, Vector3 snapNodeB, Vector3 snapNodeC, Vector3 snapNodeD) => snapNodeA != snapNodeB && snapNodeA != snapNodeC && snapNodeB + snapNodeC - snapNodeA == snapNodeD;

woeful leaf
#

That's not normal

scarlet bane
#

Im also getting random spikes in physics

woeful leaf
#

Animation is actually a huge part of it, what are you doing with that?

woeful leaf
#

Curious

scarlet bane
#

Yeah

#

LOL

#

I have a frenzy spawn mode

#

where an enemy spawns every 0.5 seconds

#

and the game just dies

#

that big chunk was from the explosion i told ytou about

#

I have like simple

#

few frame animations

#

for the enemies, explosions

vagrant blade
#

Having that many physics objects is going to kill your performance pretty fast.

scarlet bane
#

What does it mean by physics objects

vagrant blade
#

Objects with rigidbodies

scarlet bane
#

o

#

Just my player and enemies

#

How do games manage large waves of enemies usually then?

frigid anvil
cosmic rain
#

Sometimes both

woeful leaf
#

What does ECS stand for again?

cosmic rain
#

Entity Component System

scarlet bane
woeful leaf
scarlet bane
#

they have a bunch of abilities

#

and huge waves of enemies

#

are spawned

cosmic rain
#

Should be possible with the regular workflow.

trim rivet
#

I am trying to change my post process volume values via c#, but they bounce back to the preset values...
Anyone know what I might be missing?

scarlet bane
#

Yuh i think the main problem, is my explosions

cosmic rain
# scarlet bane

If you look closely, you'll see that "other" is taking most of the time. It's probably the editor loop. Try profiling a build.

scarlet bane
#

Sorry, to sound clueless

#

But how would i go about doing that

frigid anvil
#

So I've never heard of that game, and they don't have their own domain which is...weird, but looking at a quick gameplay video, I'm quite confident those aren't physics objects. Imagine Robotron 2084, which ran on hardware several exponentiations worse than the dumbest smartphone, and it handled that many onscreen easily. You just simplify the AI significantly.

scarlet bane
#

I know how to make an apk

cosmic rain
woeful leaf
#

I'm confused as to why it doesn't exist

scarlet bane
#

So many steps

quaint rock
#

gamedev has many many steps

#

once you follow through and profile something a few times the workflow will seem easy for it

scarlet bane
#

NVM

#

figured it out

scarlet bane
knotty sun
woeful leaf
#

Oh wait I'm stupid it just has to be of type GameObject ofc, my bad

#

Yeah no it makes sense now, my bad

scarlet bane
#

This is what i looks like when i do the large explosion

#

It alot of script lag

cosmic rain
cosmic rain
#

How did it go back to profiling the editor..?😞

#

But either way, seems like it's something with physics.

#

What exactly is happening during your "explosion"?

scarlet bane
#

ya u told me afte rso i unplugged me phone sry

#

I was moving it around

#

and i found this

#

So it might be the damage canvas

cosmic rain
#

460 calls to DamagePopup.Update.

#

Are you sure you need 460 popups?

scarlet bane
#

Yeah thats what i was talking about before

#

Say i have 20 enemies

#

each enemy generates a explosion

woeful leaf
#

What kind of exponential function are you using?

scarlet bane
#

which will hit each other enemy

#

so there are like 400 collision 🤣

cosmic rain
#

What do they have to do with popups though?

scarlet bane
#

Each collision

#

causes damage

#

which creates a damage popup

cosmic rain
#

Then how about pooling them??

scarlet bane
#

Maybe i need to fix my game logic

cosmic rain
#

It seems like Destruction of objects is the main issue

scarlet bane
#

Ill try taking out

violet wing
#

Does anyone who knows about Growtopia know how their world saving system works and how hard it would be to make something like that?

scarlet bane
#

the damage canvas and see if it still lags

#

then if it still does

#

ill check out poolijng

scarlet bane
#

ANd now its just purely the physics thing

cosmic rain
#

Well, why not expand it..?

scarlet bane
#

Sorry im not the brightest

#

Ok I get it now

#

I need to use pooling 😹

woeful leaf
scarlet bane
woeful leaf
#

Oh okay, I was about to say that I suggested it <t:1673857620:R>

scarlet bane
woeful leaf
#

Yeah that's fair

scarlet bane
#

Then used it find out the optimal solution to my conundrum

dapper schooner
#

Is it possible to read the contents of a prefab? Like check how many buttons are contained inside a prefab?

leaden ice
#

they're just not active and in the scene

#

You can freely use the whole of the API with them

silk horizon
#

Anyone else have the same mistake

dapper schooner
#

Thx

candid trench
#

Hello, im having a strange issue where if i am rotating an object and using transform.Translate() in the same frame the object starts to fly in circles sometimes.

public void Move()
{
  Vector3 lookPos = anotherPos - transform.position;       
  Quaternion rotation = Quaternion.LookRotation(lookPos);
  transform.rotation = rotation;

  transform.Translate(Vector3.forward * Time.deltaTime);
}

I dont understand whats going wrong here.

leaden ice
#

if you want to Translate in world space do transform.Translate(Vector3.forward * Time.deltaTime, Space.World);

candid trench
#

well, yea, i wanna translate it forward in whatever direction i have rotated it to tho

#

so should i not translate in localspace?

leaden ice
#

then that's exactly what's happening

#

you are rotating it in a circle

#

so it's moving in a circle

#

Also lookPos is a confusingly named variable. It's not a position vector, it's a direction. Would be more clear as lookDir for example

candid trench
#

fair enough.

#

But i still dont understand whats going wrong

#

Like, i feel like im rotating the object, thereby moving its forward vector. So then when i want to move it i should move it just forward in local space using the forward vector.

What im expecting then is for the object to just rotate towards whatever point i chose and then have it move towards that point.
No moving in circles or whatever.

leaden ice
candid trench
#

no, thats a static point

leaden ice
#

Is the object you're moving towards, for example, a child of the object that this script is on?

#

can you show how you have set things up

candid trench
#

i can try record a small demo, hang on

leaden ice
#

basically you have one of a couple issues most likely:

  • the point you're moving towards is itself moving, resulting in constantly changing directions (e.g. if the target is a child of this object)
  • You're overshooting the point and your object is then having to turn around and double back, ad nausuem
candid trench
#

- You're overshooting the point and your object is then having to turn around and double back, ad nausuem
This could actually be it, currently my margins are 0.1f but im normalizing a vector so i should maybe simply just use 1 insted

#

or i mean, i was using a normalized vector, before i changed to vector3.forward but seeing as both should have a magnitude of 1 maybe my implemented guard clause to see how far i have left to the target should also have < 1 rather than < 0.1f

leaden ice
devout silo
#

I have a script for swimming, and there is a variable that changes between swimming mode and normal mode. Now, I have a if statement that says if the variable is on swim mode, the walk code is disabled.
Until now it was working fine, but suddenly it doesn't listen to the statement and swimming mode runs concurrently with normal mode. I do not know what to do. help?

candid trench
leaden ice
#
public void Move()
{
  transform.LookAt(anotherPos);
  transform.position = Vector3.MoveTowards(transform.position, anotherPos, Time.deltaTime);
}``` @candid trench
woeful leaf
#

Is it possible make custom error mesages have bold text?

#

Or something that gives it more of an emphasis

scarlet bane
#

Using a pool would be very difficult

#

because i would need to pool like 500 objects...

#

Would it be ok to have an object pool of like 1k?

candid trench
#

hang on, why am i not allowed to declare 2 variables with the same name here??

    public void Move()
    {
        if (tilePath.Count() > 0)
        {
            transform.LookAt(tilePath[tilePath.Count() - 1].position);

            if (tilePath[tilePath.Count() - 1].isOccupiedBy == null)
            {
                transform.position = Vector3.MoveTowards(transform.position, tilePath[tilePath.Count() - 1].position, Time.deltaTime * moveSpeed);

                float distanceToNextTile = (tilePath[tilePath.Count() - 1].position - transform.position).magnitude;
                float distanceToCurrentTile = (currentTile.position - transform.position).magnitude; 
                // Why am i not allowed to declare this twice?
                // shouldnt this be going out of scope before i try to declare it again?

                if (distanceToNextTile < distanceToCurrentTile)
                {
                    currentTile.isObsticle = false;
                    currentTile.isOccupiedBy = null;

                    currentTile = tilePath[tilePath.Count() - 1];
                    currentTile.isObsticle = true;
                    currentTile.isOccupiedBy = this.gameObject;

                    tilePath.Remove(tilePath[tilePath.Count() - 1]);
                }
                return;
            }
            else
            {
                FindNewPath(tilePath[0]);
            }
        }

        float distanceToCurrentTile = (currentTile.position - transform.position).magnitude;
        //Same variable name as above. 

        if(distanceToCurrentTile < 1)
        {
            transform.position = Vector3.MoveTowards(transform.position, currentTile.position, Time.deltaTime * moveSpeed);
        }
    }
knotty sun
candid trench
#

wut, is that a C# specific thing?

knotty sun
#

no it is a C language specific thing

candid trench
#

really? I felt pretty confident that it's allowed in C++

#

hm. strange. i must be remembering it wrong then.

teal shard
#

hello, good day to all of you. I have a problem. Its with Unity Package Manager. Whenever I start a new project there is ALWAYS A error: One or more packages could not be added to the local file system I am desperate. I reinstaled Unity 2x time but nothing. Please help

candid trench
plush grove
#

Hello, I wrote a mod for a Unity game that has basic level of mod support ( they provide the injection for my DLL etc). Currently I have a IMGUI ui that I am looking to move to Unity's UI system. I made an Asset Bundle that has prefabs for a Canvas/buttons etc for my new UI and can load that bundle in without issue. I have also setup the scripts for the button/canvas to create the proper game objects, that I add to a root GameObject in my mod. What I'm failing to understand is how would I attach my GameObject/Canvas to the actual UI within the game so it will appear on screen? Right now setting Active "works" in that my debug log will show everything being setup as I'd expect but it isn't visible on screen

karmic stratus
#

Anyone know what this error means? I looked it up on google but still have no idea what it means. I think it's probably an error in my serialization which is here:

[System.Serializable]

public class Words
{
    public string word;
    public string phonetic;
    public string[] phonetics;
    public string origin;
    public string[] meanings;
    public string[] definitions;
    public string partOfSpeech;
}

Also, here is the API text:
[{"word":"among","phonetic":"/əˈmɒŋ/","phonetics":[{"text":"/əˈmɒŋ/","audio":"https://api.dictionaryapi.dev/media/pronunciations/en/among-us.mp3","sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=718864","license":{"name":"BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"}}],"meanings":[{"partOfSpeech":"preposition","definitions":[{"definition":"Denotes a mingling or intermixing with distinct or separable objects. (See Usage Note at amidst.)","synonyms":[],"antonyms":[],"example":"How can you speak with authority about their customs when you have never lived among them?"},{"definition":"Denotes a belonging of a person or a thing to a group.","synonyms":[],"antonyms":[],"example":"He is among the few who completely understand the subject."},{"definition":"Denotes a sharing of a common feature in a group.","synonyms":[],"antonyms":[],"example":"Lactose intolerance is common among people of Asian heritage."}],"synonyms":["amid","amidst","amongst"],"antonyms":[]}],"license":{"name":"CC BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"},"sourceUrls":["https://en.wiktionary.org/wiki/among"]}]
Error is here V

scarlet bane
#

Does this mean checking collisions?

knotty sun
karmic stratus
#

"phonetics":[{"text":"/əˈmɒŋ/","audio":"https://api.dictionaryapi.dev/media/pronunciations/en/among-us.mp3","sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=718864","license":{"name":"BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"}}]

late lion
knotty sun
late lion
karmic stratus
knotty sun
#

what you do is to learn how to define json.

scarlet bane
#

Is their anything i can do to stop large amounts of collision from lagging

plush grove
plush grove
#

ScreenSpaceOverlay

knotty sun
late lion
late lion
scarlet bane
#

Is their anyway to make a large amount of collisions around 500ish not laggy?

leaden ice
karmic stratus
# knotty sun there are lots of websites where you can paste in a json string and they will ge...

Thanks, does this seem more reasonable?

using System.Collections.Generic;

[System.Serializable]

public class Definition
{
    public string definition { get; set; }
    public List<object> synonyms { get; set; }
    public List<object> antonyms { get; set; }
    public string example { get; set; }
}

public class License
{
    public string name { get; set; }
    public string url { get; set; }
}

public class Meaning
{
    public string partOfSpeech { get; set; }
    public List<Definition> definitions { get; set; }
    public List<string> synonyms { get; set; }
    public List<object> antonyms { get; set; }
}

public class Phonetic
{
    public string text { get; set; }
    public string audio { get; set; }
    public string sourceUrl { get; set; }
    public License license { get; set; }
}

public class Root
{
    public string word { get; set; }
    public string phonetic { get; set; }
    public List<Phonetic> phonetics { get; set; }
    public List<Meaning> meanings { get; set; }
    public License license { get; set; }
    public List<string> sourceUrls { get; set; }
}```
#

same error though so probably not

leaden solstice
reef crater
#

I have the ads mediation package installed, but I can't see the settings for it

plush grove
# late lion Yes.

I don't think I understand what you are trying to accomplish with the test? I'm not bringing the entire video game elements into Unity editor... I'm just trying to launch my custom UI at runtime from my mod's dll - it's very easy with IMGUI, but I'm not understanding the complexity of the newer UI elements

verbal grail
#

The #1062393052863414313 won't let me post my question for some reason. Can someone help me here?
There is no support for Animation in Entities 1.0.0 yet? Current latest install via PM is 0.9.0. Are there patches/workarounds out there for this time being? I just need to import a rigged model into ECS so I can attach PhysicsJoints to its bones so I can get some physics-based animations going.

lucid valley
#

I think the current way is to use companion gameobjects for animations

verbal grail
lucid valley
#

So could be a year away

#

we just dont know

verbal grail
#

alright. thx

#

In DOTS/ECS, when adding a skinned mesh from a rig setup, it creates SkinMatrix buffer to the holding entity. Any way to tap into that and manipulate it's "bones" to get the mesh to deform at runtime? I'm on Entities 1.0.0 atm.

vague slate
#

Is there any way to make table's localized string size according to it's size?
Working with large texts is PAIN

craggy gazelle
#

hey guys, can someone help-me?
I'm building an application in unity, and I need to get a 3d object from a website.

    private IEnumerator AddObjectById(int id, string name) {
        string url = GlobalStateData.getInstance().ServerAdress + "bundle/ObjectBundleController/" + id;
        
        UnityWebRequest get = UnityWebRequest.Get(url);
        yield return get.SendWebRequest();
        if (get.result != UnityWebRequest.Result.Success) {
            Debug.Log(get.error);
            yield return false;
        }
        else {
            AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(get);
            GameObject obj = (GameObject)bundle.LoadAsset(name);
            _place3DObjectRef.ArPrefabs.Add(obj);   
            yield return true;
        }
    }

the function always stopping in return get.SendWebRequest(), do someone know why?

regal heron
#

horizontal = Input.GetAxis("Horizontal") * turningSpeed * Time.deltaTime;
transform.Rotate(0, horizontal, 0);
vertical = Input.GetAxis("Vertical") * Speed * Time.deltaTime;
transform.Translate(0, 0, vertical);

I have a code like this, how to limit the rotation of the cube when moving?

leaden ice
#

you'd have to track and drive the rotation yourself in a float and clamp that

knotty flower
#

I dont know what to do guys, I have read the documentation, watched videos but all this research has made me confused. My weapon snaps to the points, it doesnt move smooth to the points.

        Vector3 localPos = new Vector3(0, 0, 0);

        if (Input.GetKeyDown(KeyCode.Mouse1) && isEquipped == true)
        {
            // Move to aiming Position
            transform.localPosition = Vector3.Lerp(localPos, aimPos, 1);

            Camera.main.fieldOfView = 55;
            aiming = true;
            indicatorIcon.SetActive(false);
        }
        if (Input.GetKeyUp(KeyCode.Mouse1) && isEquipped == true && aiming == true)
        {
            //Move Back to Hold Position
            transform.localPosition = Vector3.Lerp(localPos, aimPos, 0);

            Camera.main.fieldOfView = 60;
            aiming = false;
            indicatorIcon.SetActive(true);
        } ```
clever spade
#

@knotty flower Vector3.Lerp(localPos, aimPos, 1); you are lerping to the value of 1 it will always be point b in terms of from point a to point b