#archived-code-general

1 messages ยท Page 338 of 1

cursive wing
#

if the sprite is close to ground it dont render

#

if its farther away it can render

#

weird

leaden ice
#

You're talking about the strip at the bottom of the game view where the object is not visible?

#

That's definitely the near clipping plane

cursive wing
#

farther away, sprite visible

#

close, its gone

leaden ice
cursive wing
#

the grey slime looking one, barely visible near the UI at the bottom

leaden ice
#

show it's inspector

#

etc

#

"sprite" isn't really a thing.
SpriteRenderers
UI Images
MeshRenderers

THese are actual things^

#

Sprite is just an asset in your project folder

cursive wing
#

also the ground is a tilemap

leaden ice
#

Is it not just no longer in view of the camera?

leaden ice
#

If you disable the ground is the other thing behind it?

cursive wing
cursive wing
leaden ice
#

You need to set their sorting layers/orders in layer if you want to control which object appears in front of the other for SpriteRenderers

cursive wing
#

im just gonna try making the ground instantiate 3d objects to use as ground instead

#

nevermind i have no idea how to get the gameobject i instantiates

#

trying mesh rendering

leaden ice
cursive wing
#

i mean the gameobject of the tiles

#

tiles can instantiate objects

#

but i got it working it think

#

i changed the rendering layer as i noticed i wouldnt actually have caves etc

rocky basalt
#

Is Physics.Raycast unreliable for registering clicks on an object this size on your screen?

Once I push the cube to about this distance/screen size, the raycast stops being reliable... even though my cursor is still enveloped by the cube.

#

I'm doing this:
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition); RaycastHit[] hits = Physics.RaycastAll(ray, Mathf.Infinity, snappableLayerMask);

rocky basalt
#

I thought it should be... not sure why it's not working

#

might be something else going on

rigid island
#

what exactly you expect to happen with clicks?

#

also worth checking Debug.DrawRay with longer duration

rocky basalt
#

Well I have Input.GetMouseButtonDown event, and I'm reading Debug.Logs. When it "doesn't work" I don't get any Raycast hits

rigid island
rocky basalt
#
 void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            MouseClick();
        }
    } 

 void MouseClick()
    {
        Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
        RaycastHit[] hits = Physics.RaycastAll(ray, Mathf.Infinity, cubeLayerMask);

        foreach (var hit in hits)
        {
            Debug.Log(hit.transform.gameObject);     
        }
    }
#

So, sometimes I get the Debug.Log results, sometimes I don't

#

I'm always clicking on the same object btw

rigid island
#

yeah don't see anything that stands out here, do try drawing the ray each time and see where it is when its not detecting , you never know

#

Debug.DrawRay(ray.origin, ray.direction * Mathf.Infinity, Color.green, 2);

rocky basalt
#

Thanks, I've always gotten confused by Debug.DrawRay the few times I've tried using it

#

Well, what the heck, the DrawRay' isn't showing, and I have Gizmos turned on ๐Ÿ˜ฎโ€๐Ÿ’จ

rocky basalt
#

nop

fervent jacinth
#

can i see the code

rocky basalt
#

it's exactly what navarone shared above. i put that line inside MouseClick method and I even tried putting it in update but nothing

rocky basalt
#

i dont know what that is

fervent jacinth
#

where'd you put the drawray?

rocky basalt
#

I answered that above

fervent jacinth
#

you cant Debug.DrawRay() outside of the OnDrawGizmos() function

somber nacelle
#

yes you can

fervent jacinth
#

fr? ๐Ÿ˜ญ

somber nacelle
rocky basalt
#

anyway i might just go back to the drawing board tomorrow because this is stupid. never thought clicking stuff would be the rabbit hole i wasted my evening work hours on lol

somber nacelle
#

have you confirmed that your code is actually running?

fervent jacinth
fervent jacinth
#

the elevator intro sequence where the buttons where clickable but 3d

rocky basalt
#

but when i go into gizmos and check, they're perfectly aligned with the cube so idk

dense estuary
#

How can I change gamma amount via script in HDRP? I can't seem to figure out how to access the LiftGammaGain override. This is what I attempted: https://hastebin.com/share/cufifuleha.csharp. But this isnt setting the gamma amount when I adjust my UI slider, is the gamma variable a copy of the one I am trying to access?

spring creek
fervent jacinth
#

whats the difference between gizmos.drawray & debug.drawray

rocky basalt
#

OK yall don't hate me for not thinking of this sooner, but my MainCamera was originally a prefab for Meta VR. I just swapped it for a vanilla camera and clicking seems to be more reliable now

#

Now I can go to bed less frustrated. #winning

rancid frost
#

does unity have an ID for every Object such a texture's that is persistent across runtimes?

vestal arch
#

yeah, try looking in your .asset/.meta/.scene/.prefab files

rancid frost
#

how can i access via script?

vestal arch
#

they're in yaml

vestal arch
rancid frost
#

which references?

#

instanceID is not persistent

rocky basalt
#

I think perhaps they mean why not make a reference in a script, drag the texture in via the inspector, then reference that when you need it

rancid frost
#

ahh

#

thanks got it @vestal arch @rocky basalt

dense estuary
#

I've tried switching to using gamma.gamma = new Vector4Parameter(new Vector4(value,value,value,0));

#

That changed nothing

swift falcon
#

I am building an android project. But the buttons doesn't work at all when I try the build in a phone.
I've tried unity buttons, (custom) event buttons, Input System On-Screen Buttons. Still doesn't work on phone but works fine in editor.
version 2022.3.29f1

swift falcon
#

okk ty

pastel patio
#

Hi guys I wanna make some sort of "smooth" movement, it's originally done by simply moving x% to the target position constantly...

#

But it's not working well with time, or more specifically, the framerate

#

Does anyone know how to make it framerate-friendly?

#

I tested smoothdamp and it's not what I want at all, the speed feels too even...

#

Eh, one obvious way is to put it in fixed update ofcourse, but any better ideas?

main shuttle
pastel patio
#

Cus moving the vector from current to target position multiplied by 0.02

#

Will mean that if framerate is high, it will simply move many more times than it's supposed to

lean sail
#

0.02 is fixed delta time. Not deltaTime

plucky inlet
#

If you use deltaTime in update, it will be independent from frames, cause the deltatime changes the higher or lower the frames are

pastel patio
#

But multiplied by deltatime instead means that if you're lagging for example and accumulated 0.5 as deltatime, you'll instantly move half way

lean sail
#

what else do you want? This is frame rate independent behaviour as you asked for

pastel patio
#

K try moving 0.2 5 times or moving 0.5 2 times

plucky inlet
pastel patio
#

Moving the offset * 0.2 will be significantly less distance

pastel patio
#

Each time you move, the offset changes

lean sail
#

you are saying you want frame rate independent movement but now you dont because it may move more at one frame.

pastel patio
#

Geeez no

#

If you multiply by deltatime, you'll end up far less the higher your framerate

#

If you don't, you'll end up further the higher your framerate

plucky inlet
#

than you are using it wrong

pastel patio
#

OFCOURSE

lean sail
#

you're using deltaTime wrong then. Or somehow you're a genius and every game out there needs to be fixed

main shuttle
#

Like I said, show your code....

plucky inlet
#

yeh, lets step into some code instead of theorizing ๐Ÿ˜„

pastel patio
#
transform.position += 0.02 * (targetX - transform.position.x) * Vector3.right
#

For example this

#

I just want a movement where they do a burst and slow down the closer they are

lean sail
#

show the actual code you have, rather than examples. No point in obfuscating because this is clearly wrong

versed loom
#
var spriteAssets = TMP_Settings.GetSpriteAsset();
            var spritesInfo = spriteAssets.spriteInfoList;
            Debug.Log(spritesInfo[0].name);
            Debug.Log(spritesInfo[0].sprite);```
why do i get the name but null for the sprite?(its the default TMP sprite asset
pastel patio
#

If you multiply it by deltatime, in 1 second:
If there's 2 update calls of 0.5 deltatime, you'll end up at 75% of the way
If there's 1 update call of 1 deltatime, you'll end up at 100% of the way

#

If you don't multiply by deltatime it'd obviously move faster the higher the fps is

main shuttle
#

There are literally 3 people telling you the same thing, and your adamant that we are all wrong.

pastel patio
#

Copy that code and try it at different framerates.

main shuttle
#

And even worse, lol no facepalming and geeez noing our comments.

#

Good luck with it, making something frame rate independent is one of the first things you learn in Unity.

pastel patio
#

Test it if you think I'm wrong

#

Y'all taking me for stupid rn

thin aurora
#

Why are you in here asking for help if you ignore the help

main shuttle
#

You are wrong, I already read your code.

lean sail
#

this is literally basic multiplication

chilly surge
#

0.02 is not delta time.

#

You are hard coding 0.02, people are telling you to replace that with delta time.

pastel patio
#

If, let's say, in 1 second you're meant to have moved 99% to the target

#

That's framerate independant, right?

#

Now, if you don't multiply by deltatime, and move 50% each frame
If you update with 1 fps, you'll end up 50% of the way in 1 second
If you update with 2 fps, you'll end up 75% of the way in 1 second

If you multiply it by deltatime, then:
If there's 2 update calls of 0.5 deltatime, you'll end up at 75% of the way
If there's 1 update call of 1 deltatime, you'll end up at 100% of the way

lean sail
#

the code you shown and this last problem are completely different

pastel patio
#

The code I show move a certain percentage per frame

#

And it's useeed... Lemme fetch the recording

#

The movement of the enemies

#

Notice how they move quickly but slow down as they approach the target? Yeah I want it to be moving by bursts '^^

#

That's the reason for all this...

#

SmoothDamp nor lerp does this kinda bursts...

#

And the only way to make it work correctly is to update during FixedUpdate, as it has a constant framerate

vestal arch
#

FixedUpdate doesn't have a constant framerate, it's not used for frames

pastel patio
#

Ooops this recording is wrong, it runs faster on pc

#

Or... Uh, oh, must've been the recorder bogging performance down too much

lean sail
#

you werent even using deltaTime in that code, but really no ones staring at that 2 minute video to try and see what you were referring to.

pastel patio
chilly surge
#

You would just set up a curve and lerp between start time, end time, and current frame time.

vestal arch
#

if you're hardcoding 0.02 in FixedUpdate you should use fixedDeltaTime instead

chilly surge
#

There's no need for any of the frame rate shenanigans.

pastel patio
#

Although I think that it's probably inefficient to compute a curve instead

#

But thanks anyway... Sorry about the outburst tho

pastel patio
chilly surge
#

Modern CPUs run billions of cycles per second, plugging a value into a math equation is nothing.

#

Better to do it right than worrying about non existent performance problem.

pastel patio
#

In fact I can post every way I tried... If you're really interested in those

vestal arch
#

hmm what happens if physics can't run at its fixed rate due to hardware or performance issues

lean sail
lean sail
pastel patio
#

FixedUpdate is basically execute for every x amount of time passed

plucky inlet
wintry gust
#

Quick question, but can public methods still be called from a component that's disabled? Not the game object, but just the component.

plucky inlet
wintry gust
#

I'd like to disable the component just to stop the Update loop on it, but still access some Raycast methods on it

plucky inlet
wintry gust
#

Because that's still running a loop

plucky inlet
#

An empty update()

fervent furnace
#

you can still call your component methods

#

disable is just telling the engine dont handle your component

wintry gust
#

Thanks, that's what I assumed

plucky inlet
fervent furnace
#

no

plucky inlet
#

nothing? If you dont do it on update

cosmic rain
#

Nothing particular. It's how you use it that might be a problem.

plucky inlet
#

There is no issue in using getcomponent in start

wintry gust
#

It's not what's wrong with it, it's dependant on how you're using it.

#

If you're using GetComponent quite frequently, it's very expensive. But if you're using GetComponent once and caching it, it's perfectly fine.

lean sail
#

directly referencing the component if you can. If the component is on the same object u can drag it in with a [SerializeField]. You cannot avoid it if you are trying to get a component on a completely different object. Like a projectile trying to get access to some health script on a character

wintry gust
#

You could do this, but you can also just have a direct reference

cosmic rain
#

Well, it's mostly because using a serialized field is more convenient. It's really a lot about preference though.

#

One minus I can think about is that if you're using it to initialize everything, that might increase your scene init time.

wintry gust
#

Assuming you're using GetComponent to get a component that's on the same GameObject or even a child GameObject. You can 100% do this. But it would be less costly if you just use a Serialized field and directly reference it in inspector.

#

Great, that's a perfect example.

#

So in your PlayerCollision script, you can definitely do this:

private Rigidbody rb;
    
private void Start()
{
    rb = GetComponent<Rigidbody>();
}
#

It's not that expensive, since you're caching it

#

But this is not a necessary cost

#

You could easily just do this

thin aurora
wintry gust
thin aurora
#

A component can be disabled or even removed but the C# code will still be valid and exist

#

It will not exist if disposed or there are no more references, unless the code had static variables

#

The only thing disabling a component does is turn off Unity's event driven system where it invokes Update and all that

wintry gust
plucky inlet
thin aurora
#

You could completely destroy a gameobject but still use its scripts if you had some reference to the game object basically

#

But obviously this is not a good idea

wintry gust
#

Correct. Although it's bad practice to use public variables unless necessary. You should be doing this:

[SerializeField] private Rigidbody rb;
#

public variables can be accessed and modified from other scripts. That can be problematic.

thin aurora
#

The point is encapsulation. Keep everything as inaccessible as possible until it must be more accessible for some reason. It keeps your code clear.

#

Is your question how to reference the player for this?

wintry gust
#

Yeah, that's a bad way to do it

#

Because you'd have to use GetComponent on every single collision in that instance

plucky inlet
#

you could for example use the oncollision methods to get the other collider or you could have a static reference to the player.

wintry gust
#

Which is very expensive

#

Yes, what twentacle said

lean sail
#

you would likely GetComponent here, because you cannot drag in the player to every wall. Also doesnt work if you're spawning the player at runtime. Otherwise you would be relying on like a singleton but its not really good to just have a shitton of singletons

wintry gust
#

You should be doing it the reverse Dread

lean sail
#

also u dont need to GetComponent on every single collision. U can use layers to ignore everything else, put your player on a layer which only characters are on.

plucky inlet
#

Use it to setup

wintry gust
#

Do the collision event on the player

#

Because you don't need to search for a rigidbody in that case.

thin aurora
#

Assuming your game only has a single Player, then what you can do is implement something called a Singleton. See the Singleton explanation here -> https://unity.huh.how/references
Using a singleton is an easy way of referencing something that only has a single instance without using too many static references.

wintry gust
#

Yep yep, I know ๐Ÿ™‚

thin aurora
#

if you use a singleton then you can just store the component in the player class

wintry gust
#

When you have something a little more dynamic and you're not sure what exactly the object is

plucky inlet
#

Or when you have more than one player for example

wintry gust
#

But in all the examples you gave, you already know what the object is.

cosmic rain
#

Collision events is a good example when you might want to use get component

plucky inlet
#

creating players from one prefab but with the same script would share static references for all players. you dont want that to lets say modify the username or something

lean sail
# wintry gust Do the collision event on the player

this is situational, and arguably worse. I know its an example, but sometimes you end up with cases where you dont want this logic to happen with every wall. Then you start needing to adjust the walls, and the player script which is completely unrelated.
Like if an enemy AI wants this logic too, it either needs to add the same logic, or you move the script to the wall.

wintry gust
#

No, you can still modify if you direct reference

#

Yep

lean sail
wintry gust
#

In his specific example, there is literally no reason to use GetComponent.

#

I'm not saying there aren't cases for it

#

But it's objectively slower. Again, in that specific case.

#

Collision in general can be very complicated, so I agree with what you're saying @lean sail

lean sail
#

your movement shouldnt really be using collision events. It may not be an issue if you're just using standard RB movement but for sure doesnt work otherwise. Usually you'd want raycasts/capsule casts

wintry gust
#

You can to set your rigidbody to Continous or Continous Dynamic to fix that

#

Then you will still collide at high speed.

lean sail
#

No matter what you do, at high speeds you will get unexpected results. If you expect to go decently fast, swap to physics casts

#

even with any of the rb settings

wintry gust
#

The more you do it, the more you'll figure out cases for it ๐Ÿ™‚

#

In general, it's not that taboo if you use it.

#

Only if you use it frequently

#

Nah, you can serialize the rigidbody here too

fervent furnace
#

you will get compilation error

cosmic rain
#

You will get complications

wintry gust
#

You can't define rb in Start method and use it in Update.

#

Should be like:

public class Enemy : MonoBehaviour {
    [SerializeField]
    private GameObject explosionPrefab;
    private Rigidbody rb;

    void OnDestroy() {
        if (explosionPrefab != null) {
            Instantiate(explosionPrefab, transform.position, transform.rotation);
        }
    }
    void Start(){
        rb = GetComponent<Rigidbody>(); 
    }
    void Update(){
        if (rb != null) {
            rb.AddForce(Vector3.forward * 10);
        }
    }
}
#

But you can also do this:

public class Enemy : MonoBehaviour {
    [SerializeField] private GameObject explosionPrefab;
    [SerializeField] private Rigidbody rb;

    void OnDestroy() {
        if (explosionPrefab != null) {
            Instantiate(explosionPrefab, transform.position, transform.rotation);
        }
    }

    void Update(){
        if (rb != null) {
            rb.AddForce(Vector3.forward * 10);
        }
    }
}
#

Optimization nitpick, but if null checks are a bit expensive too >.<

lean sail
wintry gust
#

we all have lines of code in our project that test whether it's something is null or not, so which way is best to get the null reference?

๐Ÿ”ฅSimple Trajectory Prediction 3D/2D Unity - Without LineRenderer - Perspective and Orthographic: https://youtu.be/sDFCHTIdSIw

๐Ÿ”ฅFlora Assets Review - Ultimate Vegetation Solution for Unity - Render millions ...

โ–ถ Play video
lean sail
wintry gust
#

When I say "expensive" I don't mean it's going to take several seconds to compute. We're talking milliseconds of difference haha

tidal shadow
wintry gust
#

But fact is that it is slower and it can potentially add up.

lean sail
fervent furnace
#

i wont check if it is null if it must exist

wintry gust
#

Which part is wrong?

fervent furnace
#

missing it is a fatal error, just stop the application and check

vestal arch
vestal arch
#

stuff gets worrying when you have millions of those operations, then it can add up to milliseconds. that's what benchmarks and profiling are for

lean sail
# wintry gust Which part is wrong?

Wrong to even suggest it as an optimization. It does not even take milliseconds. Your focus is completely on the wrong target. Optimization should be only looked at after profiling. If you're running enough such that a null check is costly, well the logic you're about to do on those unity objects after are gonna be horrendous * 100.

#

This is like saying "my program slows down when I add 2 numbers, 100000000 times." The question is not how to speed up addition, it is how to reduce the amount of logic you're doing.

vestal arch
wintry gust
vestal arch
#

yeah, it wasn't clear what exactly you were proposing

#

i'd remove it regardless of any expense though tbh. let it be an error so it isn't a silent bug.

lean sail
#

If your point was just "it's more expensive compared to not doing it" then that can be said about literally anything. But you did explicitly say it is expensive and linked resources about it.

#

There are cases where u do need to null check, but it isnt something I commonly do either

wintry gust
#

I do null checks literally all the time. It's necessary in cases.

#

But I don't consider it necessary at all in the above case. And because it's unnecessary, I do consider it a meaningless expense.

#

But that's just me

thin aurora
#

Seems pointless to check something that won't be null unless there is undefined behavior

#

Also, it was already mentioned, but a check like this makes a nanosecond difference. Please don't do optimizations here

#

Always do null checks for things your use that are set publicly. I'd argue it's optional when you talk about private data since these are unlikely to be set to null by accident

thin aurora
#

Also

#

One way to check if the state is still valid is with Debug.Assert

#

Your IDE will call a breakpoint on it if the boolean predicate returns false

#

And this is purely for DEBUG, so builds won't have it (assuming you build in RELEASE mode)

#

I usually add these in private code, and use proper if-statements in anything public

cosmic rain
#

What resource?

wintry gust
#

Can you show what you mean?

#

Different materials that use the same shader should usually get batched together

knotty sun
#

@swift falcon Please write in full sentences

tidal shadow
#

line1
line2
line3

knotty sun
tidal shadow
sleek bough
#

And then post the error in plain text so others can do a more thorough search if you failed to find anything

tidal shadow
hard viper
#

the animator has a GUI which it uses to define a graph for how animation states play into each other. then you use code to set animator variables, and the animator component swaps to the right state

#

you will need a tutorial

hasty wave
#

It's a [System.Serializable], it is working before, but it for some reasons stopped working

#

alright, thanks so much. I've been stuck with this bug for a whole day now... I couldn't progress t all

sleek bough
dusk apex
#

Are you getting an error or just your log that is null? Looks pretty safe otherwise - trying to determine where it might have gone wrong, if it had.

hasty wave
#

none

#

the problem is, I get this error when I use the Save method

#

looked through it and

#

looks like "data" is showing null, that's why I couldn't pass staminaBar.value to it

#

no...

knotty sun
hasty wave
#

if I placed

if(data != null){
  data.stamina = staminaBar.value;
}```

it skips stamina and proceeds to my moneyManager, which also has "SaveData"
hasty wave
dusk apex
#

Well, you aren't handling it if it's null cs public void SaveGame(string dataFileName) { if (this.gameData != null) { Debug.Log("Gamedata is null at DataPersistenceManager"); } foreach (IDataPersistence dataPersistenceObj in dataPersistenceObjects) { Debug.Log("Pass: " +dataPersistenceObj); dataPersistenceObj.SaveData(ref gameData); } dataHandler.Save(gameData, dataFileName);//game data was null }

hasty wave
#

how do I fix that?... I swear everything was working properly until it stopped working

dusk apex
hasty wave
#

GameManager script?...

thin aurora
#

Please properly share your !code

tawny elkBOT
hasty wave
#

ohhhh

thin aurora
#

Read the bot message

#

๐Ÿ˜Ž

hasty wave
#

it didn't--

#

btw this checked

#

but it initialized

thin aurora
hasty wave
#

the thing is, if I removed the save in StaminaManager.cs it will error on other managers (timeManager, moneyManager) etc.

thin aurora
hasty wave
thin aurora
#

It is unclear what exactly is null here

#

Can you log data and staminaBar inside that method, and see what is null?

hasty wave
#

I tried printint out gameData and it's null even in DataPersistenceManager.cs

thin aurora
#

Then what calls SaveData? please share that

#

Also, if GameData is a class then ref is not required to be part of the parameter

hasty wave
#

and the error is right there at data.stamina = staminaBar.value; because data is null

thin aurora
#

So then the issue is that whatever calls this method passes a null reference

#

So you should make sure it isn't

#

Or share the code and I can also look

hasty wave
#

it strings off to here

hasty wave
thin aurora
#

It should check if(this.gameState == null)

#

Not that it would fix anything but at least the logging works

#

Oh, you have the check twice

hasty wave
thin aurora
#

Considering you pass ref, this means it is eligible for reassigning

#

Perhaps you should just get rid of the ref altogether

#

It makes no sense to have that there

#

How does this help?

#

Your code isn't even valid because the behavior works with multiple classes implementing the interface, not a single one

#

That's not fixing the issue of the variable being null

hasty wave
#

uhm, the whole DataPersistenceManager.cs will collapse if I changed the SaveGame to that

thin aurora
#

It's likely a reassignment in one of the SaveData methods because ref is used

#

Hence why I wonder if removing it would fix the issue

#

One thing you can also do is put Debug.Log(gameData) before SaveData to see when it becomes null

#

@hasty wave

hasty wave
#

the same place where I get confused, why is gameData not null outside but null when SaveGame() is called

thin aurora
#

Just a simple check, no if-statement

thin aurora
# hasty wave
foreach(...)
{
  Debug.Log(gameData);
  dataPersistenceObk.SaveData(ref gameData);
}

Like this

thin aurora
#

Wait, so it is null in general

#

Then why did the previous code have a proper if-statement that would prevent this, and now it doesn't?

#

No wonder it's confusing

#

So where is gameData assigned? please share the whole manager

hasty wave
hasty wave
thin aurora
#

But now it's gone

#

So the code here properly handled the null check and logged an error

#

So either you return; in the current if-statement, or you fix the issue where it's not assigned

#

And as far as I am aware you haven't shown where you assign it so idk what the code does

hasty wave
#

checklist?

#
  • check that gameData is initialized in GameManager
    ~~- staminaBar is assigned in the Unity Inspector ~~
    - add null checks and debug logs in StaminaManager's SaveData method to verify that both gameData and staminaBar are not null before accessing them
    ~~- check that StaminaManager is attached to staminabar ~~
  • make sure gameData is initialized in GameManager.Awake() and make sure references are correctly set up
thin aurora
#

This is not helpful in the slightest

#

@hasty wave Please share the code that assigns gameData

#

I.e. the method and relevant field/property or the whole manager. The latter is more convenient

hasty wave
thin aurora
atomic whale
#

is there a way to refresh a gameobject? in our project I've made a blood system that paints blood onto a rendertexture to be used for masking in shader graph. we have 60 floor tiles that all use the same material but in code all create their own "blood mask" und assign it to their material. if I bleed onto a tile some other tiles randomly will also show the blood splatters (only from certain angles and it flickers) and once I open the material of the bugged floor tile its like the mask texture is refreshed and from then on actually uses the texture given in code instead of randomly using one from another tile. idk if this made much sense but I basically need to open the material tab of each floor material to refreh its mask...but not manually obv.

hasty wave
thin aurora
#

This likely sets it as null

hasty wave
#

it loads the data

thin aurora
#

I am guessing you have fallen victim to the shitty JsonUtility parser

#

Either that or the file does not exist, so it returns null

hasty wave
#

I prints out in every loaded data it did

thin aurora
#

Does it never return null?

hasty wave
thin aurora
#

Maybe a better check would be to see if it is returning null, because the code is not supposed to return it judging by your code?

#

Or maybe it should return an empty GameData object if it's returning null?

hasty wave
#

It..did

#

oh my god.. I think I know why now

thin aurora
#

I mean the default is null

#

So if the file does not exist, or deserialization failed, it returns null

#

And your manager relies on a valid object, not null

hasty wave
#

how do I fix this issue?

thin aurora
#

An easy way is changing return loadedData to return loadedData ?? new();

#

It will assign an empty GameData object when returning null

heady iris
#

Or to correctly handle this method returning null

thin aurora
#

An easier syntax is this:

if (loadedData != null)
{
  return loadedData;
}

return new GameData();
hasty wave
thin aurora
#

But as Fen mentioned, your lack of proper nullabillity handling is the bigger issue here

heady iris
#

I would rather not have a "load save data" method return a valid-looking (but empty) game data object if it fails to load something

thin aurora
hasty wave
thin aurora
#

You should probably use the easier one

#

Especially in Unity it might actually do something different, it's a complex topic

heady iris
#

Destroyed Unity objects compare equal to null, but aren't actually null.

hasty wave
#

omg it finally worked! thank you so much! ToT)

heady iris
#
destroyedObject ?? new GameObject(); // will give you destroyedObject, even though it compares equal to null
missingGameData ?? new GameData(); // will give you a new GameData object
thin aurora
# hasty wave omg it finally worked! thank you so much! ToT)

Please take some time to read about nullabillity in C#. I think this article is pretty relevant https://wildermuth.com/2023/02/13/nullable-reference-types-in-csharp/

#

There are pretty good ways to make sure you don't fall victim to NullReferenceException issues

#

It's a very common issue

hasty wave
thin aurora
#

Especially in Unity which (I think) still lacks proper nullabillity support, but the article explains how to enable it

#

Glad it works now ๐Ÿ˜Ž

heady iris
#

sigh

thin aurora
# hasty wave

Also, please still get rid of ref. It is not a good idea to use this

heady iris
#

for a reference type, all that ref does is let the called function reassign your variable

#

it doesn't really achieve anything else

thin aurora
# hasty wave why tho??

ref is a way to pass the parameter directly instead of by reference/value. It only makes sense to do this when code directly modifies parameters, or require a reference from an otherwise value type

#

In your case, you set the content of an object reference and not the reference directly

heady iris
#

It could make sense if GameData was a gigantic value type (a big struct)

#

but it's not!

hasty wave
#

oooh alright! thanks gain! :D

heady iris
#

layers.

halcyon steppe
#

Is there a way to access or rather set the emission property of a material through code? I would like to make a script that turns that emission on or off.

leaden ice
halcyon steppe
#

Ohhhhhh thanks, thats a really good tip!

halcyon steppe
#

Right, that worked perfectly, now the question is for objects with multiple materials, how do I access all materials and not just the first one in the array?

heady iris
#

well, you'd iterate over the array

halcyon steppe
#

How though? I believe this code only returns one thing and not an array.

#

even when i set material as an array it doesnt accept it

heady iris
#

see the materials property

pastel patio
#

When playing on android, on initial launch of the game, the inputType is shown as "Touchscreen"

#

But it behaves like I'm actually using "Mouse"

#

And then if you relaunch it, or reload the game, it will actually be shown as "Mouse"

halcyon steppe
pastel patio
#

Maybe I made a mistake and isOn doesn't trigger the events linked to the toggle?

#

But then I crashed with an infinite loop before cus of it... That's why I assume it did

heady iris
#

setting isOn on a toggle causes a change event, yes

#

you can use SetValueWithoutNotify to avoid causing an event

pastel patio
#

Any idea why the ui have touchscreen active while it appears that mouse is active PlayerPrefs-wise?

#

It only happens on the first time the InputHelper spawns in tho, it's as if the initial playerprefs setting doesn't work correctly even though I don't see any mistake in this

heady iris
pastel patio
#

They trigger SetInputType when clicked

heady iris
pastel patio
#

I thought that it's somehow a latency in the initial setting at line 15 ~ 17

pastel patio
#

Literally every launch of the game afterwards works normally

#

Only the first time you launch it there's this bug...

heady iris
#

hm, that would not be consistent with it being a toggle problem

#

maybe Input.touchSupported is false at the moment that Awake runs

pastel patio
heady iris
#

log the values of mouseToggle.isOn and touchscreenToggle.isOn before and after you set one of them

pastel patio
#

Which shouldn't have been the case is Input.touchSupported has gone wrong

heady iris
#

as well as Input.touchSupported and the value of PlayerPrefs.GetInt("InputType") before and after you check if you need to initialize it

pastel patio
#

Eh, sorry, I might've been mistaken about the scope of the bug

#

It actually seems to happen whenever you start up with touchscreen as choice...

heady iris
#

ah, that sounds more plausible now

pastel patio
#

I think I can guess the location of the bug now, it seemed absurd before

heady iris
#

maybe something else is reading inputType in its own Awake method

#

or otherwise reading it before InputHelper is created

#

(although that'd cause the opposite problem: using touchscreen behaviors when you wanted mouse input!)

pastel patio
#

Or at least on the editor it functions completely normally

pastel patio
#

Whichever toggle you have enabled by default will be the one visually active, despite something setting isOn at some point (Probably before the toggles)

#

However the playerprefs do exist and stay

#

That's my observation on the editor at least, on mobile it seems weirder than that

#

But it does seem to work correctly after I switched both toggle off

heady iris
#

It's possible that the ToggleGroup hadn't yet had a chance to start listening for changes

#

since you were doing that in Awake

pastel patio
#

Maybe...

#

Tbh yeah, normally these kinda things that link to other stuff are best left to Start

edgy bough
#

What could be the reason of headers not showing in the inspector?

dusk apex
#

Did you save the script?

waxen socket
edgy bough
#

it works ingame

dusk apex
#

What do you mean by works ingame? Are you saying that the Editor inspector changes during the play session?

edgy bough
#

no, the actual script is doing what it's supposed to do

#

it's just that the headers aren't getting displayed at all which makes navigating the inspector much harder in more complicated scripts

dusk apex
#

The inspector will not update if you've got errors or if you did not save the script.

edgy bough
#

there aren't any errors, and the script is saved

dusk apex
#

Try restarting Unity

edgy bough
edgy bough
dusk apex
#

Did you disable automatic reloading in preferences to reduce load times between Visual Studio and Unity?

edgy bough
#

not sure what that has to do with the problem

#

the script is literally saved in unity and works properly, it's just the headers that aren't rendering in any script

dusk apex
untold hemlock
#

Because that could be the problem.

#

If you're using OnInspectorGUI.

dusk apex
#

If you've disabled auto reloading you'll have to import each modified script individually or reimport all etc

edgy bough
edgy bough
#

as indicated by the thing working in game

#

and not having any issues except the headers

dusk apex
untold hemlock
#

See if the headers show up.

edgy bough
dusk apex
#

Those are my best guesses. There isn't much else it can be.

edgy bough
edgy bough
untold hemlock
edgy bough
#

normal mode

untold hemlock
edgy bough
#

it does work in another project

#

there is an editor script though, which has a CustomEditor for Object

#

looks like it came from the FishNet networking library

#

it's a fallback one though too

#

it does seem to work when commented out for some reason

heady iris
#

what seems to work, exactly?

heady iris
edgy bough
heady iris
#

I know that it adds a custom editor for all MonoBehaviours. I'd expect it to correctly draw [Header] attributes though

heady iris
edgy bough
heady iris
#

and it applies to every single kind of unity object

edgy bough
#

yeah

#

I don't think commenting out a random class from a networking library is a good solution, so I asked about it in their Discord server

fiery stream
#

Hey, i am having trouble with my camera following the wrong object in unity. Could someone help me real quick?

heady iris
#

ask your question

fiery stream
#

idrk how to ask it without showing

#

give me 1 sec

heady iris
#

explain what you wanted to do, what actually happened, and what you've tried

rigid island
spring creek
#

Obligatory "use cinemachine"

Ah dang, you were in before it!

fiery stream
#

so im trying to add a new enemy to my (very) small fps game that i just made, so i made another enemy in blender and i imported it into unity, then i made it a prephab and i put it as an enemy in my code, but when that new enemy spawned the camera locks onto it for some reason and i have no idea why. ive tried to delete it and put it back again and ive even tried a different blender file

rigid island
#

you probably have a camera leftover from blender

fiery stream
heady iris
#

yeah, that's likely

spring creek
#

Be sure to delete the camera and lights from blender before exporting

spring creek
#

Serialized Reference whenever possible

rigid island
#

you can declare them anywhere in the class

heady iris
#

not just at the "start": you declare a new field in one of your classes

rigid island
#

just don't put it in a method

heady iris
#

(you do typically put them at the top, though)

#

read the page you were linked to.

leaden ice
#

Variables need types.

heady iris
#

this is very wrong. compare this to what the above-linked page has you do

#

No, I'm not going to spoon-feed you the answer. The page I linked you to explains everything.

#

You can't just "stop learning" for half of the day

leaden ice
#

You don't reference variables. You reference objects (in the C# sense of "object", not GameObject). You can read their variables from your reference.

heady iris
#

you've spent several minutes arguing with me instead of reading the page I linked you to, which teaches you exactly how to do what you asked about

leaden ice
#

Because spoonfeeding the answer means you'll be back to be spoonfed 8 times.
If you just learn to do it you won't need to come back

#

yes

heady iris
rigid island
#

lol. feels

heady iris
#

If I didn't want to help you, I would not have said anything.

spring creek
#

No one is condescending. And they did help you

rigid island
#

@swift falcon not the best attitude to have if you plan on getting help here..
Also "learning" would be part of working on things

heady iris
#

there is no distinction between "learning" and "working". You learn as you work, and you work so that you can learn.

rigid island
#

telling you to actually read something that might help you isn't "belittling"

spring creek
#

No one belittled you

#

That is not condescending or belittling or even rude

rigid island
#

very true though? hows that belittlement hough

#

having "timezones" for learning is weird..

#

there i said it

spring creek
#

You were given the resources you needed and got upset and mean someone didn't actually write code for you

rigid island
#

to me it implied exactly what I said, its natural to learn at all times of the day.

spring creek
#

Well that is an incorrect analysis imo

#

Be nicer to the people helping you. That's what.
Don't jump to conclusions
Text can be read many ways. Assume the best

rigid island
#

anyway. Point being no reason to take offense when you aren't directly fed an answer.

#

whatever lets move on

primal wind
#

I'm going insane. My multiplayer lib works fine outside of Unity but as soon as i import it and start using it in Unity, weird stuff happens, like the clients never connecting to the server

leaden ice
primal wind
#

oh nvm

#

i'm targetting multiple .NET versions so i'll need to modify some things

heady iris
#

A key thing is that you shouldn't touch unity objects from anywhere but the main thread

primal wind
#

the only objects that get potentially touched in events are 2 Vector3

#

Iirc Vector3 can be used anywhere right?

#

But even then it doesn't do anything before getting connected

heady iris
#

those are structs, and they don't touch any other unity objects, so that ought to be fine

#

(structs can be deceptive: they can have properties that wind up touching other unity objects)

#

see ParticleSystem modules

neon harbor
#

hello, is anybody able to help me with update the billing library for play store and unity?

#

got this huge warning 2 weeks ago:

We are introducing changes to the lifecycle of Play Billing Library and its associated deprecation timelines. Because you currently use an older version of the library, we wanted you to be aware of new key dates youโ€™ll need to adhere to:

By Aug 31, 2024, all new apps and updates to existing apps must use Billing Library version 6 or newer. If you need more time to update your app, you will be able to request an extension until Nov 1, 2024.

Learn more about the deprecation here.

Update before these dates to avoid a disruption in app publishing and updates. Publishing and updating apps that use Play Billing Library version lower than 6 will be blocked in Play Console on the dates mentioned above.

Next steps: More information on how to migrate to the latest version of Play Billing Library can be found on our developer website.
#

but im kinda confused, i tried updating the IAP version and re upload the .aab

#

i still get this warning though

neon harbor
rigid island
neon harbor
leaden ice
#

It's good practice to organize cohesive units of code into methods yes.

spring creek
#

If it is very short and will neve need to be used elsewhere

leaden ice
#

Vague question- depends on what you're doing. But usually you'd use Quaternion.RotateTowards or Slerp

spring creek
#

It makes absolutely no difference at all except to readability
Favor what is most readable to you

heady iris
#

Vector3.Slerp/Lerp will not behave correctly for euler angles

leaden ice
#

it really depends on what you're trying to do.

#

Using euler angles you get weird stuff

#

like if you want to go from angle 340 to angle 10

#

the natural shortest way is to rotate clockwise by another 30 degrees

#

using euler angles you end up rotating the other way

#

back around down from 340 all the way around the circle back to 10

#

one of many reasons euler angles are not good.

#

no

#

transform.rotation/localRotation is a Quaternion

#

eulerAngles exists only for occasional convenience

heady iris
#

Quaternion.Lerp gives you a rotation that's between two input rotations. It should be used to linearly move from one rotation to another, or to blend two rotations

#

this is a simple way to do random spread, for example:

#
transform.rotation = Quaternion.Lerp(Quaternion.identity, Random.rotationUniform, 0.1f);
#

this moves 10% of the way towards a completely random rotation

#

If you want to apply a rotation, use Quaternion.AngleAxis

#

You give it an angle and an axis to spin around.

#
transform.rotation *= Quaternion.AngleAxis(90, Vector3.up);
#

this spins you by 90 degrees around the vertical axis

#

* combines two rotations

#

so you can do transform.rotation *= anotherRotation

#

the Quaternion methods make it very clear what is being done

leaden ice
#

for what

heady iris
#

vs. directly manipulating euler angles

#

i mean, it's probably fine, but I almost never use euler angles directly

#

i use Quaternion methods to compute rotations

leaden ice
#

For moving diagonally up/right when pressing WD? You wouldn't use either one.

heady iris
#

they were asking about rotating with WASD

leaden ice
#
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 direction = new(horizontal, 0, vertical);```
heady iris
#

For input, you might want to store the desired angle

#
            yaw += lookInput.x;
            pitch -= lookInput.y;

            yaw = Mathf.Repeat(yaw, 360);
            pitch = Mathf.Clamp(pitch, -87f, 87f);

            var turnRot = Quaternion.AngleAxis(yaw, Vector3.up);
            var lookRot = turnRot * Quaternion.AngleAxis(pitch, Vector3.right);
#

this is part of my player control code

leaden ice
#

WD implied movement to me, not rotation.

heady iris
#

If you want the car to point the direction you're moving, you'd compute a vector for the direction you want to go

#

then rotate the car to face that direction

#

fun shortcut: you can just set transform.up = someVector

leaden ice
#

Ok then:

float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector2 inputDirection = new(horizontal, vertical);```
#

but it really depends how you want the controls to work

#

do you want it to be steering with AD and throttle with WS?

#

or something else

#

there are many ways to design a car controller

#

Well GetAxis will add smoothing automatically

#

beyond that, Vector3.RotateTowards exists and works fine for Vector2s

heady iris
#

oh huh, I didn't know about that one

#

that'd be perfect here

leaden ice
#

this is way overcomplicated

spring creek
#

There are many errors here

leaden ice
#
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector2 inputDirection = new(horizontal, vertical);

transform.right = inputDirection;```
knotty sun
#

but your logic is flawed

leaden ice
#

Then to add smoothing you'd add like Vector3.RotateTowards to the mix.

shell scarab
#

Why don't doesn't this code change anything about the textures?

    public Image image;
    public SpriteRenderer spriteRender;

    private void Update()
    {
        DrawCircle(image.mainTexture as Texture2D, Color.clear, 256, 256, 12);
        DrawCircle(spriteRender.sprite.texture, Color.clear, 256, 256, 12);
    }

    public static void DrawCircle(Texture2D tex, Color color, int x, int y, int radius = 3)
    {
        float rSquared = radius * radius;

        for (int u = x - radius; u < x + radius + 1; u++)
            for (int v = y - radius; v < y + radius + 1; v++)
                if ((x - u) * (x - u) + (y - v) * (y - v) < rSquared)
                {
                    tex.SetPixel(u, v, color);
                    Debug.Log($"set ({u}, {v}) to {color}");
                }
    }

Also doesn't work with Color.red. There are no errors or warnings. I can see the debug statements in the console. I expected at least the sprite to work.

rigid island
#

did you apply

shell scarab
#

silly me

#

thank you let's see

#

that works. So is the only way to use setpixel to modify the actual texture file?

#

there's no sort of like runtime image? Or I guess I'd have to diplicate it myself?

leaden ice
shell scarab
#

sounds good ๐Ÿ‘

leaden ice
#

Instantiate would do the trick

inner yarrow
rigid island
#

center of gravity mass maybe

#

your tow has a collider? that also contributes to the weight

leaden ice
inner yarrow
#

I get that that's what's causing the inbalance, but I don't see why that imbalance should cause it to roll away.

inner yarrow
leaden ice
#

Unity's physics engine doesn't respect things like conservation of momentum/energy properly

#

it's optimized more for speed than accuracy

#

somehow it's concluding a net force on your thing probably between friction and the collison between the wheels and the body

#

I would also try adjusting the center of mass to see if that helps

#

(which you need to do in code)

heady iris
#

You have created the troll physics magnet car

rigid island
#

had the same issue with my scooter

#

center of mass helped

inner yarrow
#

By the way, the physics that I'm using is with the same approach as the one in very very vallet https://www.youtube.com/watch?v=CdPYlj5uZeI which is probably affecting it.

A detailed look at how we made our custom raycast-based car physics in Unity for our game Very Very Valet - available for Nintendo Switch, PS5, and Steam.
BUY NOW!! https://toyful.games/vvv-buy

~ More from Toyful Games ~

โ–ถ Play video
heady iris
#

i enjoyed that video

rigid island
heady iris
#

really nice breakdown of the mechanics

rigid island
#

i use the same thing for my scooter

#

also might need to rethink how you setup your colliders

inner yarrow
#

I think the problem is that the suspension points in the up direction for the wheels, so when it's angled, then the force points slightly in the direction it's tipped, but I feel like the force should be in that direction.

#

I don't know if there's another force that should be conteracting that movement (possibly friction).

heady iris
#

oh no, it's the other kind of troll physics car notlikethis

#

i guess it might help to look up why a tilted car doesn't roll forwards

rigid island
rigid island
#

yeah basically

heady iris
#

The force should be the exact opposite of the ground's normal vector

#

It shouldn't be pointing along the direction it'd go if you weren't sloiped

inner yarrow
heady iris
#

That's actually what you want, I think!

inner yarrow
heady iris
#

The force will be out of alignment with the vehicle's suspension

#

but the force gets applied nonetheless

#

you'll just wind up with a "bending moment" (i think) ((my sister is a mechanical engineer; i don't know this stuff))

#

imagine the extreme case of the car being tilted 90 degrees forward

inner yarrow
#

I drew up a thing in paint to help think about it, and I think the problem comes from the fact that we are only applying forces to the car when in reality, the car is also pushing on the tires. So if we were accounting for the force on the tire, then the force along the suspension would be correct, but since we aren't, the normal will be more accurate.

#

I also haven't thought about it for long enough, but I'd like to think that it actually does cancel out and point along the normal.

heady iris
#

The force won't get "bent" to be parallel to the suspension

#

that's the important bit

#

The part of the force that is parallel to the suspension will compress the spring, and the part that's perpendicular will just...well, in real life, it'd eventually break the suspension

#

(you can use Vector3.Project and Vector3.ProjectOnPlane to separate those two parts out!)

inner yarrow
#

Yeah that makes sense.

heady iris
inner yarrow
heady iris
#

it would work because of angles

#

๐Ÿ˜

#

finally, my vague recollection of "troll physics" memes from 2011 comes in handy

zenith timber
shell scarab
#
    private void Awake()
    {
        spriteTexture = Instantiate(spriteRender.sprite.texture);

        spriteRender.sprite = Sprite.Create(spriteTexture, spriteRender.sprite.rect, spriteRender.sprite.pivot);
    }
```Why when I run this code does the sprite get set a crazy distance away from its pivot?
zenith timber
leaden ice
rigid island
#

oh wait thought it was UI

#

nvm

leaden ice
shell scarab
#

pivot mode

#

the sprite is correctly positioned before I hit play

zenith timber
#

nothing I think I fixed it

leaden ice
#
spriteRender.sprite = Sprite.Create(spriteTexture, spriteRender.sprite.rect, spriteRender.sprite.pivot, spriteRender.sprite.pixelsPerUnit);```
shell scarab
#

I had the constructor with a ton of arguments before, i didnt try with just the ppu added, let me try it.

rigid island
shell scarab
#

it's something to do with the pivot, when I set the pivot to Vector2.zero the sprite is aligned so that the bottom left of the image is exactly where the pivot of the game object is.

#

im not sure why copying over the old pivot is screwing it up like that though

shell scarab
#

oh maybe I ddin't think of that

#

no, same deal

#

doing this:

spriteRender.sprite.texture.texelSize / 2
```gives the same result as this:
```cs
Vector2.zero
```I feel like those should give different results.
rocky basalt
#

Is there no built-in way get a sprite image of an empty grid cell (so transparent except for the square outline) ?

#

I'm trying to make a grid using ui

shell scarab
rocky basalt
#

i'm sure it is... i just have zero photoshop/image editing software experience and was trying to quickly prototype something

leaden ice
#

it's 9 pixels

#
WWW
WTW
WWW```
#

Well I guess paint doesn't support transparent pixels

#

W = white
T = transparent

#

or just find one on google

heady iris
#

tada

#

that is very hard to click on

rocky basalt
#

so annoying all these websites want you to make an account to download images

heady iris
# heady iris

you'll want to use a pretty low PPU value for this

#

given that it is 3 pixels across

rocky basalt
heady iris
rocky basalt
#

โค๏ธ learning new skills kicking and screaming

tepid brook
#

Hi guys how can i make a cube like this eco game ? i saw a minecraft tutorial and know how a chunk and cube work but how to make this grass rounded cube ? someone know or have a forum or something ?

tired shard
#

wallahi

maiden fractal
# tepid brook Hi guys how can i make a cube like this eco game ? i saw a minecraft tutorial an...

It's hard to tell where exactly the grid edges are so it's hard to identify the bricks needed but I'd assume it's just couple premade 3d models for each piece type (inner corner, outer corner, straight edge, etc.) needed to construct any shape. The right meshes to construct the block could then be decided based on the surrounding blocks or lack thereof. if you have multiple 3d models for single piece (like straight edge), you can pick one by random, you just have to make sure the models match together seamlessly (connection points must be identical)

true sphinx
#

Is there a way to have "persistent" actions on an action map? such as moving and pausing which will be present in all action maps

true sphinx
#

i have different action maps for each mode, so in a boat, in a car, just normal walking around. but all of these will have a move action and a pause action that work the exact same way

#

maybe im doing something else wrong

tepid brook
leaden ice
vocal raptor
#

Can anyone explain me how to get rid of this?
I tried exporting the Unity Playground Character via Export -> Custom Package and Imported it the same way.. but idk what "already" is supposed to mean in that Error message.. like yeah.. its the only location where that's defined...!?

silent tapir
#

why does this not apply blur

sleek bough
spring creek
silent tapir
#

okay

weak venture
#

Would this be the right place to ask about sprite shape? I have one main sprite shape im updating every frame (growing vine) which seems fine for my pretty good dev computer but I suspect its the root cause of reports of performance issues on computers with lesser capabilities. Is there anything I can/should do to get a similar effect of a sprite shape growing over time without per-frame internal calls of BakeMesh frying some users' computers?

cosmic rain
weak venture
#

yeah i cant really observe any spikes running on my good computer

#

I do see a solid amount of time in the sprite shape bake mesh but its like 2ms out of 4ms

#

i guess on another computer that might be like 30ms out of 60 though?

cosmic rain
#

It's really unlikely that both values grow linearly depending on the machine performance.

#

Did you actually ask your users what hardware they have?

weak venture
#

its definitely the single most expensive thing im doing but I suspect maybe its hitting memory limits or something else causing a significant slowdown?

#

nah these are just internet strangers from newgrounds

cosmic rain
weak venture
#

sure one sec ill try to find a good example frame. But basically, the official SpriteShape package checks if the spline input data has changed, and if it has, rebakes the geometry of the sprite shape

inner yarrow
#

Does OnCollisionEnter require both objects to have a rigidbody?

somber nacelle
weak venture
#

so here's an example call stack where my sprite shape usage is using up a lot of the frame time (3.33/8.71)

weak venture
#

it might just be the case that this type of usage where its being dynamically updated every frame or almost every frame isnt intended/well-supported but I'm wondering if there are maybe some settings I can change or ways I can change my approach to make my usage of this package more efficient

cosmic rain
#

How big is the spline?

weak venture
#

it grows over time and probably ends on like a few dozen control points. I dont see much appreciable difference in cost as spline gets longer

#

ignore pink thats soemthing else

cosmic rain
cosmic rain
weak venture
#

i only have update collision as an option in debug inspector, theres no collider on the spriteshape though. weirdly it seems slower with update collision disabled. It looks like it just is too many points maybe, it just turns into BezierPoint math im assuming, bezier expanded is just multiplication

raven basalt
#

In blender, I made an animation and there is an object, colliderObject, that represents the collider. Throughout the animation, the colliderObject, which represents the collider, changes size. In unity, I then attach a collider to this colliderObject, in hopes that when the animation runs, the collider changes size along with this colliderObject, but it doesn't. How do I go about fixing this issue?

cosmic rain
weak venture
#

I just plumbed that through to a UI so I'm gonna see if that makes any differnce on a low power laptop I got the back of a closet

#

Best thing to do is probably just profile on that machine that's actually reproducing the serious perf problems

cosmic rain
#

If you have that option, that's the best

lean sail
#

In response to that deleted message
You are using euler values in a quaternion, you shouldnt directly assign it. Use Quaternion.Euler

frosty coral
lean sail
somber nacelle
frosty coral
lean sail
#

well yes that much was clear. Start debugging to see if the line even runs

frosty coral
somber nacelle
#

the only reason your sound wouldn't play is if either audioSource or gunshotSound is null or you have other errors in your console preventing that code from running. if you have absolutely no errors in the code then you have your answer

somber nacelle
#

also once you start shooting you just don't stop shooting until you are out of bullets? is that intentional?

somber nacelle
#

that was not what was in question

frosty coral
#

oh

somber nacelle
#

you currently do not stop shooting until you run out of ammo no matter what because you continuously invoke the Shoot method from within the Shoot method as long as you have ammo left

frosty coral
#

i certanily do

somber nacelle
#

yes, so if you do not want to keep shooting even after you have released your shoot button, you need to not invoke the Shoot method like that.

frosty coral
#

oh

#

i already have that implemented but ok

#

i dont shoot when i dont click

maiden fractal
# tepid brook So its not a mesh created in unity script you think ?

It could be but I think just storing the information about which pieces to draw and where (and draw them procedurally in shader) could be comparable in terms of performance. I think it depends on the amount of the map you need to draw at once and the sizes of the chunks (higher chunks for example means more expensive to generate) as well as the amount of rounded blocks compared to regular cubes whether generating the mesh would be worth trading generation time for faster render

stoic ledge
#

What could be the reason for a crash right after the build is launched?
The error is ".../globalgamemanagers.assets' is corrupted! Remove it and launch unity again! [Position out of bounds!]

The build is DedicatedServer build, on Linux.
Unity version is 2023.2.20f1

swift falcon
#

This has been a problem for very long time now.. How to do these properly? Make a layoutgroup calculate it's content size and positioning properly?


    private IEnumerator StartAnimation()
    {
        canvasGroup.alpha = 0;
        // yield return null;
        SetLayoutGroups(true); // enables layout groups
        yield return null; // hoping the layout groups adjusts their size

        SetLayoutGroups(false); // turn off layout groups
        yield return null;```
kind cloak
#

Hi ! it might be weird but, i got a vector3 and i want to convert it as an unique int but it must be between 0 & 360. I'm struggling a bit to find a way to do this :/

swift falcon
kind cloak
#

yep

swift falcon
#

vector3 is infinite tho

#

do you mind having 2 vec3 that returns same id?

#

cause it's impossible to not have overlaps

#

the real question is what is you gonna use it for UnityChanOops

slim seal
#

What is a good unity extention for VSCODE

swift falcon
tawny elkBOT
swift falcon
#

autocompletion is fine enuff to do things without stressing too much

kind cloak
placid summit
#

Hi in ugui is there a simple way to sort child elements at runtime by name for draw order? Rather like a layout group but an order group?!

swift falcon
lean sail
#

If you state the use case, itll be way easier to suggest what you should actually do

swift falcon
devout hornet
#
private bool IsColliding(Vector3 targetPos)
{
    Vector3 start = targetPos + Vector3.up * (_capsuleHeight / 2 - _capsuleRadius);
    Vector3 end = targetPos + Vector3.down * (_capsuleHeight / 2 - _capsuleRadius);

    RaycastHit[] hits = Physics.CapsuleCastAll(start, end, _capsuleRadius, targetPos - transform.position, 0.1f);

    if(hits.Length != 0)
    {
        Debug.Log($"{hits.Length} : amount of hits registered");

        foreach (RaycastHit hit in hits)
        {
            float angle = Vector3.Angle(hit.normal, Vector3.up);
            Debug.Log($"{hit.collider.name} : name of hit, {hit.normal} : normal of hit, {angle} : angle of hit");
        }
    }

    return false;
}

Hello again, I am trying to figure out how I can detect floors/slopes from walls dynamically with a CapsuleCastAll.
As I currently have layermasks in my prototype world that can differentiate for me what is a wall and what is a floor. But when I am going to make my world full of different models and heights, I don't want to lose time placing layermasks and collisionboxes everywhere.

In this current debug setup, I can can see all the collsions of my Cast but there is an issue:
Ground (which should have an angle of 0) says it has an angle of 90 with a hit.normal being Vector3(1.00, 0.00, 0.00) or Vector3(0.00, 0.00, -1.00) (based on walk direction).
Walls (which should have an angle of 90) says it also has an angle of 90 with the same hit.normal values.
Only slopes partially work, with them showing a hit.normal of Vector3(0.00, 0.80, -0.60) and an angle of 36.88[...]

#

What might I be missing?

kind cloak
devout hornet
#

Here is are some references

placid summit
swift falcon
#

Afaik there's none builtin

placid summit
devout hornet
#

Soooo dug a little deeper ... Sphere and Capsule casts just don't work like a regular RayCast would when hitting a point ...

#

That's stupid yet logical ... maybe?

#

I managed to make it work, but what would be the best route to take if I will be needing regular RayCasts when trying to detect walls?

Should I do 3 casts (foot, middle, head)?
I don't want my player to walk through walls still but don't want to overload someone computer with thousands of checks...

vocal raptor
placid summit
lean sail
#

The only way would be if the value was like bit shifted which doesnt apply here

placid summit
novel bough
#

I am building the project for the web and enabling the Development Build option my project runs smoothly on Development Build so I keep it but there is a label at the bottom right corner. can I remove this label while keeping the Development Build option enable?

hard tapir
#

I'm reading some docs and is it okay to use string as ID for items? Like SODA, SHIELD...

waxen socket
thin aurora
#

The reason is "magic strings"

hard tapir
harsh rapids
#

when i load scenes it breaks the entire game, why??? (it works perfectly fine if i just run that scene by itself)

thin aurora
#

Another reason is avoiding allocation of strings but honestly storing stuff in constants or persisting variables kind of omits this issue anyway

loud sedge
#

Can i use assets that are free on the unity store, and the sell my game?

thin aurora
#

Also, this is a coding channel

loud sedge
#

oh

#

oops

hard tapir
thin aurora
harsh rapids
#

is that not the proper channel

thin aurora
#

The whole point is avoiding performance issues and magic strings

thin aurora
harsh rapids
#

i believe it is

hard tapir
thin aurora
#

Seems more like visual issues

harsh rapids
thin aurora
#

Usually a minor difference but it can add up

#

Numbers don't have this

thin aurora
hard tapir
#

Like case "SODA" do something

thin aurora
#

That's fine as long as you don't write it twice

#

Point is, if you happen to change the id of the thing to SODA2 for example, then the check will suddenly be SODA2 == SODA

hard tapir
thin aurora
#

If you store these things in constants, i.e. internal const string SODAKEY = "SODA", then the code just needs to use this constant when assigning the id, and comparing them

#

Same for enums, yes, but enums are limited to what is defined at compile time

#

Technically you can use different numbers, but it becomes unclear what it does and you might as well use constants then

hard tapir
thin aurora
#

Constants represent the id by text, and you can continue using numbers

hard tapir
thin aurora
#

I would honestly advice you use constant numbers

#

Strings are nice, but it's pointless to use these when numbers work

hard tapir
thin aurora
#

Also FYI, basically all games use numbers. If you need to do comparisons, use them with constants, or implement proper comparisons on other things on the item. For example, Soda might also have a unique label to specify its name that you can check

hard tapir
#

I understand that now

#

Using constants is very smart

#
{
    public const string SODA = "soda_01";
    public const string SHIELD = "shield_01";
    ...
}```
thin aurora
#

You can also just define it in the item

#
public class Soda
{
  public static int ItemId = 10;
}
#

Soda.ItemId == 10

waxen socket
thin aurora
#

Then you can write an implementation in an actual interface

hard tapir
thin aurora
#

You can still use an interface, but it would not be static otherwise

#

Example:

public interface IItem
{
    static abstract int ItemId { get; }
}

public class Soda : IItem
{
  public static int ItemId => 10;
}
waxen socket
waxen socket
#

I think if you have an id field it means you don't set it up in the code. I think @hard tapir has it as a field in ScriptableObject

final solar
#

yo guys is it easy to code a point and click game?

waxen socket
final solar
#

yk i just care about the part of code that sais: if i click this thing anither picture appears yk?

#

i wanna make an escape room type of game nothing too serious

waxen socket
final solar
#

im trying to do something fun but a bit scary at the same time, im going for a 15 minute experience just for laughs with friends

indigo frost
#

[Photon Pun] I can't figure out how to set a variable from one Client to another.

leaden yew
#

I want to set "const Money = await api.setItem(projectId, playerId, {
key: "Money",
value: 0,
});" as protected not as default. How do I do this in unity cloud code js?

vocal raptor
#

I'm trying to transfer the basic Unity character from the Playground into a existing Project of mine..

I selected all references to the player character, exported them as a custom package.. so far so good..

However when I import said package, some of the scripts prompt me with this weird error.. implying that its already there... any suggestions?

loud zenith
#

My Android app crashes randomly and in the logs I can see this error keep repeating many times:

[EGL] Failed to create window surface: "EGL_BAD_ALLOC": EGL failed to allocate resources for the requested operation.

What is this? Is this a memory leak issue?

#

I'm using Unity 2022.3.25 and I have plugins like AdMob with mediations, Firebase, Facebook etc.

cosmic rain
#

What OS are you using?

cosmic rain
loud zenith
#

apparently EGL means Embedded-System Graphics Library. I didn't know that either.

cosmic rain
#

One possible cause is that you're just running out of memory

cosmic rain
loud zenith
cosmic rain
#

Use the profiler or the dedicated profiling tools for your device to measure the memory consumption

loud zenith
loud zenith
cosmic rain
#

Might need to use dedicated profiling tools then.

loud zenith
leaden yew
cosmic rain
supple pewter
#

if the code reaches return does it just completely stop

spring creek
# supple pewter

It returns from that method, meaning the execution of that mwthod ONLY will end

supple pewter
#

thankyou

#

its hard to test this now

flat cloud
#
//Drop if equipped, "Q" is pressed and fpsCam is playing the "Idle" animation 
if (equipped && Input.GetKeyDown(KeyCode.Q)) Drop();

how Do I do This ??
I wanna call the drop function if the fpsCam is playing the Idle Animation

thin aurora
flat cloud
#

Basically this is a pickup and drop script for my first person shooter guns
I don't want to allow my guns to be dropped when I am aiming down so I want my drop function to be called only when the camera is not zoomed in (Idle animation)

spring creek
mild orbit
#

I feel like I am going crazy, I am profiling some of my code and this method has a ton of String.memcpy() invocations. But I can't for the life of me figure out where they would be coming from. Any ideas? It is all pretty straight forward...
https://gdl.space/urapovugoh.cs

#

(For context, the method generates a bunch of mesh quads for UIToolkit, to denote milliseconds in a timeline UI)

heady iris
#

well, it's a bunch of entries in the list, but each one is just a single invocation

leaden ice
heady iris
#

it looks like String.memcpy shows up when large structs are copied

#

it's not actually string-related

leaden ice
#

Ah - that may also make sense

heady iris
#

it's just where memcpy happens to live

leaden ice
#

That would be the most effective way to copy structs

mild orbit
#

Ahh both SetAllIndices and SetAllVertcies are doing a nativeSlice.CopyFrom() internally. I guess it would be that then?

#

Nope, that is it's own entries.

#

So... would it be the assignments of the structs to the arrays then...?

heady iris
#

Any time a struct get assigned to anything, really

#

(a big struct, that is)

#

unclear on the definition of "big"