#archived-code-general

1 messages · Page 337 of 1

gilded crag
#

oh

#

yea

gray mural
#

Also make sure you read my previous message. Use GetKeyDown for optimization

gilded crag
#

okay

#

So like this? :

#

(Inside Update)

#

it works atleast

ruby estuary
#

Perfect

gray mural
ruby estuary
#

Though use comparetag

ruby estuary
gilded crag
#

wait i thought i had down

ruby estuary
gilded crag
gray mural
gilded crag
gray mural
#

Make sure you know that gameObject reference is not required

#
other.CompareTag("BoxCenter")
#

Component.CompareTag

gilded crag
#

ill be damned

#

cool

#

Thanks for the help guys.

gray mural
#
private void SetTrigger(bool value)
{
    if (other.CompareTag("BoxCenter"))
        InsideTrigger = value;
}
gilded crag
#

Howw 😭

gray mural
#

Shown above

gilded crag
#

oooo

#

thanks

#

forgot brackets

#

right?

gray mural
gilded crag
gray mural
# gilded crag right?

No, the if condition can be used without the brackets if there is just a single line inside of it

gilded crag
#

Like this right?

gray mural
gray mural
#
private void SetTrigger(Collider collider, bool value)
{
    if (collider.CompareTag("BoxCenter"))
        InsideTrigger = value;
}
gilded crag
#

how do i use it now?

ruby estuary
#

So you call the method

#

And inside the parentheses you put the variables or values, and because there are 2 parameters you separate each "value" with a comma

gilded crag
#

Bro i dont get it

#

sorry for my messy shit

#

i didnt know what to type

ruby estuary
#

Okay seems good

#

Just remove the types, i.e. erase collider and bool

gilded crag
#

Alright, i thin i get it!

ruby estuary
#

That's it!

#

Well done

opaque vortex
#

If I take scripts from youtube tutorials and use them for my own projects, is that legal and fine?

naive swallow
#

Check for a license listed anywhere in the video, description, or any page where the source code is posted

slim imp
wraith cobalt
#

Assuming it is their script :D

slim imp
opaque vortex
torpid depot
#

guys whıch unıty versıon you prefers? For good performance.

#

but same time the version should be have some ımportant updates or somethıng

naive swallow
#

The most recent LTS

torpid depot
#

but ı want a good performance versıon

#

because ı open other programs background and sometımes unıty took some much tıme

heady iris
#

there is not a secret "fast" version of unity

#

this is also not a code question

torpid depot
#

@heady iris you thınk whıch channel good for talk about somethıng lıke that?

#

ı dont know much thıs server

heady iris
#

#💻┃unity-talk would be appropriate (but i don't think there's much of an answer for your question)

dawn nebula
#

Boys I have a new hyper fixation. Animations systems in card games. How do they work? I assume animations are added to a queue and executed in order?

#

Each item in the queue is some type of AnimationHandler that manages the movement and coordination of specific objects/effects?

latent latch
#

just tweens

#

more fluid to interupt a tween then to queue them

dawn nebula
#

Marvel Snap is a good reference for this.

latent latch
#

I usually reference slay the spire and I can tell you that game interupts everything

dawn nebula
latent latch
#

that game does seem like it has a bunch of animations when a card is played, so yeah that'll probably need a pause between what's played

#

I was more talking in the general sense of how you move the cards around the screen and how your hand re-adjust when removing/adding cards to it

dawn nebula
#

Maybe have them be mono behaviours and spawn them in as needed?

#

So they bring in the resources they need.

#

Like a movement anim could bring in the spline.

latent latch
#

could just do a prefab route and have all of it on the gameobject

#

then call some Play() method that's custom to the prefab

#

assuming that each card has a different amount of components

dawn nebula
#

Nah I think it’s better to be dynamic with this. Any card can perform any effect/animation.

#

Up to the handler to make sure it has the resources required.

latent latch
#

i usually either go a large prefab variance, or a single prefab of components (which is populated by SOs)

dawn nebula
#

Seems rough for hundreds of cards?

latent latch
#

single prefab idea could incorporate every type of component... you just wouldn't use the components if the blueprint doesn't include it

#

at minimum you have some mesh/sprite, text, and a particle system as to what I'm seeing from that video

#

though you can't really just swap out particle systems like that unless you make some sort of manager system instead... but I like to overly optimize my stuff so instantiating components is always fine, especially in something like a card game anyway

#

vfx graph would however allow you to do that

dawn nebula
heady iris
#

You'd absolutely want something "pluggable"

#

so that it's easy to make lots of cards trigger the same camera shake

dawn nebula
#

need lots of composable elements that execute at specific times

#

maybe it's finally time for Unity Timeline.

#

I'm wondering what the structure is here

#

like a card might have some "effect asset" id

#

that maps to some AnimationHander prefab

#

gets instantiated, loaded into the queue, and then executes its sequences when it gets to it
cleans itself up when done

lean sail
#

well do you plan on ever having more than 64 items? Also do you plan to store literally nothing like a title or description? Unlockable states sounds like something that might grow, quickly. I really wouldnt be too concerned about the space of storing them in memory at runtime. This is just gonna make it harder. You'll also need some mapping from index to the title/description which means you're storing the data anyways but now theres just a bitmask too.

#

the only thing it'd really do here is replace having a bool on each instance of an achievement like

public class AchievementData
{
  string title, description;
  bool isUnlocked;
}

because you would be storing if its unlocked or not in that bitmask

#

and even then, you still need a mapping from achievement to index in the bitmask so im not sure if it would be better

fervent furnace
#

some database support blob, you can store a bitvector
you can store as this

public struct Achievement{
}
Achievement[] achievements;
YourBitVector unlockeds;
ofc the length must be same 
#

yes since you need to load the whole bitvector even if you want to query one archievement only
or check how your database store single bit/boolean value, i guess they have optimized it by compressing the data, then you can convert the true/false value to bit or store it directly

fervent coyote
#

Question- Why isn't this working? It sets the rotation to 90 (Down, for some reason the camera is flipped?) when it goes at or above 0 degrees, and it doesn't even work for the -90
This is supposed to clamp the camera to -90 and 90 degrees
Astro_MainCamera.transform.eulerAngles = new Vector3(Mathf.Clamp(Astro_MainCamera.transform.eulerAngles.x, -90, 90), Astro_MainCamera.transform.eulerAngles.y, Astro_MainCamera.transform.eulerAngles.z);

I also noticed that the camer in unity is... inverted? -90 is instead 90, and vice versa for some reason

spring flame
#

Is there some method for getting a transformation matrix chain from parent transform? Just like unity object to world works, the same principle but from object to target transform

#

That works automatically and doesn't multiply the whole chain each update

cosmic rain
split inlet
#

is this a common issue?

#

the character in the animator is sinking in a weird swim-looking pose

cosmic rain
simple egret
#

GetKeyDown returns true only for the very first frame you hold down the key. GetKey returns true for as long as you hold the key

sleek heath
#

GetKeyDown would be for "Press E to interact" and GetKey would be for "Hold E to interact"

gray mural
#

When marking a script with ExecuteAlways attribute, how would I go about making a variable persistent, so having its value not reset when changing the game mode from play to edit, without serializing it in the Inspector?

#

The thing is that the variable is a List, so storing its every item in EditorPrefs doesn't seem accurate enough

dusk apex
gray mural
leaden ice
gray mural
leaden ice
gray mural
heady iris
#

[HideInInspector] does nothing to serializaiton

leaden ice
gray mural
#

I see, it's not NonSerialized. Got it, thanks

left aurora
#

Hey guys, I'm startng learning Netcode for GameObject from the documentation. So, I went to install it on my project it automatically installs version 1.9 while I was reading the documentation of the version 2.0.

The question is: Which version should I use during my learning journey?
and Which one should I use when building a game?

heady iris
#

2.0 is for Unity 6 Preview

#

also, it's actually 2.0.0-exp

#

so it's an experimental version right now

#

but then again, the docs suggest that they're no longer maintaining 1.x

#

i don't have a good answer 😅

left aurora
#

😂

#

you gave me usefull information anyways. Thank you

heady iris
#

They should be reasonably similar

#

If you're using an editor version that installed 1.9.1 automatically, then just go with that

left aurora
#

Alright I'll stick with 1.9.1 then

knotty sun
#

please do not cross post

mortal dagger
#

Hey, I dont know how to fix the No Autocompletion problem, I watched almost all the YT Videos and followed all the steps, i even tried reinstalling Visual Studio 2022 but nothin helps. Any other uncommon ways to fix it?

tawny elkBOT
spring creek
#

Did you install the workload?

#

Did you set vs 2022 to the external tool?

#

Have you clicked regenerate project files after doing the above?

knotty sun
#

Also Reload with Dependencies in Solution Explorer of VS

mortal dagger
spring creek
#

Show external tools

mortal dagger
spring creek
mortal dagger
#

Klick select Dependecies?

spring creek
#

You do this in VS, through the solution explorer, as Steve said

#

Not in Unity

#

And you click a solution, not a script

mortal dagger
#

Oh, thanks, that seemed to work.

#

Do you know, what I have to do, so that it opens this, when I klick on a script in unity?

somber nacelle
spring creek
#

I asked to see that earlier

mortal dagger
#

also clicked regenerate

spring creek
#

Clicking a script in unity should open visual studio 2022

mortal dagger
somber nacelle
spring creek
#

Click it in that file you JUST sent a screenshot of

finite ferry
#

Used a SmoothDamp to make crouching transition smoother, and it works fine on almsot everything, except when I am standing up while not moving.

tawny elkBOT
finite ferry
mortal dagger
obtuse moat
#

I'd like some input on what would be a good way to implement intractability in my game
currently I have an IInteractable interface, with an "Interact" method

Issue is, there are some functionalities that could be shared by multiple different interactable objects - for example, making these objects produce sound upon interaction, or play an animation

Currently, I'd have to create separate fields for the audio and audio source on each different script that inherits from IInteractable, which isn't ideal
I thought about creating a InteractableBaseClass but to my understanding it's not the greatest practice because it's not very extendable

All the solutions I found online didn't take into account the extendability of the solutions they provided - they showed the simplest solutions (which aren't very extendable as the project grows in size)

Thank you in advance!

heady iris
#

You can use events (UnityEvent to configure it in the inspector, or just plain events in C#) to add behaviors

#

For example, here's what happens when you interact with a lever

#

it tells a RotateMover component to start moving, a SoundMaker component to emit a sound (and generate a noise event for the detection system), and itself to turn off

obtuse moat
#

Ohh I didn't think about that!
I could make that unity event a field on an interface?

#

more specifically the unity event haha

heady iris
#

I just have one big Interactable component -- it's actually just a module that I attach to an Entity in my game

heady iris
rigid island
heady iris
#

The interface describes only the public behavior of something

obtuse moat
#

oh, you mean manually implementing it in each class that inherits from the interface?

heady iris
#

The fact that calling the Interact() method happens to invoke a UnityEvent is irrelevant

heady iris
obtuse moat
#

Fair enough, one line of repeated code really isn't a problem

heady iris
#

Once you extract the consequences of the interaction out of the Interactable component, you don't have to create a new class to add a new feature

obtuse moat
#

just watch me forget to invoke the event on each class lol

heady iris
#

you only need multiple classes if you have multiple fundamentally different kinds of interaction

obtuse moat
#

what would you class as fundamentally different?

heady iris
#

well, the most basic idea would be that you push a button, your character plays an animation, and the interaction is completed

#

but maybe you could have interactions that you have to hold for a while, or interactions that pull up a minigame

obtuse moat
#

some interactions I have are:
picking up objects
inserting them into machines
opening doors

I have a seperate script (class) for each interaction
is there a better way of doing doing these things to avoid having a ton of classes, or is it unavoidable?

heady iris
#

Yeah, those are pretty distinct ideas.

#

A base class that provides the UnityEvent would be reasonable

obtuse moat
#

hmm how do you use the unityevents though? for example, if you want to add sound, do you add an audio script to the object, assign a clip and then set the unityevent to play the sound?
or do you have a central audio manager and you somehow pass the audio clip with the unity event?

heady iris
#

The former.

#

Although the component could also talk to an audio manager, if needed

obtuse moat
#

I see, thank you so much for the help, I seriously appericiate it!

heady iris
#

The idea is to use small components to add individual features

#

rather than trying to mash all of your features into single components

obtuse moat
#

Yeah I don't know why I struggle with doing that so much

light wraith
#

hello,
for some reason I get:
Coroutine 'ResetJump' couldn't be started!
when trying to start a coroutine from a non-monobehaviour.
weird because starting one worked many times in the past.
What I do is get a reference to a MonoBehaviour, and do myMonoBehaviour.StartCoroutine("MyChildClassCouroutine");

here is the executing code on the non-MonoBehaviour:
controller.StartCoroutine("ResetJump");

knotty sun
#

and your ResetJump method signature is?

light wraith
#
public IEnumerator ResetJump()
{
    yield return new WaitForSeconds(0.5f);
    isJumping = false;
}
hexed pecan
knotty sun
#

why start it with a string and not ResetJump()

light wraith
#

odd because Invoke also gave the same error and it didn't work when I tried this way or as a string

rigid island
light wraith
rigid island
#

always start them from their containing class

 public void ResetJump() => StartCoroutine(ReseJumpRoutine());
 private IEnumerator ReseJumpRoutine()
 {
     yield return new WaitForSeconds(0.5f);
     isJumping = false;
 }```
heady iris
#

It doesn't look for a method with that name from the class that's calling StartCoroutine

#

that would be weird

stoic palm
#

Hi im getting an error that says 'Object at index 0 is null' is there a way to fix this
here is the code

knotty sun
tawny elkBOT
light wraith
stoic palm
#

!code

tawny elkBOT
rigid island
merry coral
#

 private void Start()
 {
     fpc = GetComponent<FirstPersonController>();
 }```

Does anyone know why i get a Type Mismatch when a try to add a fpc in the editor? ctrl + click goes to the right class
I am using the modular first person controller from Jess Case
somber tapir
merry coral
#

it says type mismatch

knotty sun
merry coral
#

is there a way to specify which fpc im using in the script?

knotty sun
#

yes, by preceding it with the namespece or adding a using statement for the namespace

hexed pecan
#

Why does it matter that it takes less time to implement the graphics than making them?

#

It's most often the case

#

Well the obvious answer is to practice and get better

#

Or use AI and then wonder why it looks like shit and is inconsistent

fair pebble
#

hey anyone able to help me with this code? my coroutine isnt stopping, but the stop code is getting called private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player") && fog == true)
{
StopCoroutine(TearGas());
Debug.Log("stop Coroutine");
}
}
IEnumerator TearGas()
{
while (takeDamage == true) // Infinite loop
{
takeDamage = false; // Disable damage temporarily
Debug.Log("Player affected by tear gas, cannot take damage for a moment.");

        yield return new WaitForSeconds(1); // Wait for 1 second

        player.TakeDamage(damageAmount); // Apply damage to player
        Debug.Log("Player took damage from tear gas.");

        takeDamage = true; // Re-enable damage

        // Yield control back to Unity until the next frame
        yield return null;
    }
}
#

how do i make it look like its a c# code? btw like the code above mine

tawny elkBOT
fair pebble
#
//    private void OnTriggerExit(Collider other)
    {
        if (other.CompareTag("Player") && fog == true)
        {
            StopCoroutine(TearGas());
            Debug.Log("stop Coroutine");
        }
    }
    IEnumerator TearGas()
    {
        while (takeDamage == true) // Infinite loop
        {
            takeDamage = false; // Disable damage temporarily
            Debug.Log("Player affected by tear gas, cannot take damage for a moment.");

            yield return new WaitForSeconds(1); // Wait for 1 second

            player.TakeDamage(damageAmount); // Apply damage to player
            Debug.Log("Player took damage from tear gas.");

            takeDamage = true; // Re-enable damage

            // Yield control back to Unity until the next frame
            yield return null;
        }
    }
#

there, now, hey anyone able to help me with this code? my coroutine isnt stopping, but the stop code is getting called

fair pebble
knotty sun
#

That is not how you stop a coroutine.

fair pebble
#

oh so im just stupid? i figured it was cause its the opposite from the starting

knotty sun
#
Coroutine cor = StartCoroutine(MyMethod());
...
StopCoroutine(cor);
fair pebble
#

huh?

rigid island
#

StartCoroutine returns a Coroutine object

fair pebble
#

ahhhhh ok

vestal arch
sinful harbor
#

RoomInst = Instantiate(RoomPrefabs[RoomPicker], new Vector3(1, 1, 1));
how come the new vector3 is underlined red. Compiler Error CS1503

vestal arch
#

if you don't want it to be rotated, use Quaternion.identity

knotty sun
vestal arch
#

no overload of Instantiate just takes the object and a position

rigid island
#

Cannot convert a to b
(vector3 to transform)

knotty sun
#

Literally 10 seconds reading the docs would have answered this but, hey, I guess that's too much to ask

rigid island
#

the IDE and the Unity Log window spells it out too

merry coral
#

Does anyone have experience with the Modular FirstPersonController?

vivid halo
merry coral
rigid island
merry coral
#

yes im using the right one

rigid island
#

if you still can't reference the namespace its likely using assembly definitions
or your editor isnt configured lol

heady iris
merry coral
#

i can insert it in the inspector, however when i select it, it gives me type mismatch

merry coral
heady iris
#

I misunderstood your problem -- I thought you meant you were getting a compile error

merry coral
sinful harbor
heady iris
#

well, no, it's a Vector2

#

if it was a Transform it'd be a Transform

sinful harbor
#

so i would i put it

heady iris
#

read the documentation for Instantiate

#

rather than randomly guessing

rigid island
sinful harbor
heady iris
#

That is a valid use of Instantiate, yes

sinful harbor
#

how is that different from mine

rigid island
#

signature?

sinful harbor
#

oh its because i didnt have the Quaternion.identity

heady iris
#

consider reading the code you wrote

#

yes

#

you have to pay attention to the code you're writing

sinful harbor
#

so you were wrong

heady iris
#

what?

rigid island
#

what?

#

look at the signatures

#

where do you see one with Object and Vector3

#

i give you 100$

sinful harbor
#

because i had wrote the transform bit correct

#

it was the fact i didnt use Quaternion.identity

heady iris
rigid island
heady iris
#

You showed us code that tries to pass an object and a Vector3

#

a Vector3 is not a Transform

#

it will never ever be a Transform

#

there is an overload for Instantiate that takes an Object and a Transform as the two arguments

#

But this is irrelevant, because you weren't passing an Object and a Transform

rigid island
vestal arch
sinful harbor
#

thanks for the help anyway

heady iris
rigid island
heady iris
#

rather than just blindly making changes until the compiler stops yelling at you, yes

merry coral
# heady iris no, that's the problem

Still don't understand why GetComponent<FirstPersonController> does not work, however i created a workaround by manually assigning in the inspector

heady iris
#

do you?

merry coral
#

didn't know it had to be on the same object, is there a way to get one from the project in general?

#

explains a lot though 🤣

heady iris
#

that's how GetComponent works, yes

#

you call it on a game object or component

merry coral
#

but then i have to place it in the inspector, right?

heady iris
#

you should just assign it in the inspector, directly

#
[SerializeField] FirstPersonController firstPersonController;
#

no GetComponent call needed

merry coral
#

that explains a lot

#

thanks!

sinful harbor
#

anyone have any good tutorials on procedual generation for 2d platformer , with different room sizes?

warm blaze
#

Anyone know why hardcoding my listeners works, but using a for loop doesn't?

Basically, I'm instantiating 25 Prefab Buttons, and then setting listeners for each button all in code.

Everything works perfect except the following code

 {
 DayButtons[i].GetComponent<Button>().onClick.AddListener(() => LoadDay(i));
}```

But hard coding it does work
```DayButtons[0].GetComponent<Button>().onClick.AddListener(() => LoadDay(0));
DayButtons[1].GetComponent<Button>().onClick.AddListener(() => LoadDay(1));
// etc...```
heady iris
#

Oooh it's this one

#

It's tricky

#

Basically, the anonymous function is capturing the i variable, so they all wind up using the same value

warm blaze
#

Thanks Fen! I think this should make it work 👍

nimble cairn
#

Hi all. For some strange reason whenever viewing a TMP asset at a certain Y axis the submesh is omitted from view. I'm stumped on this one if anyone could tell me what I'm doing wrong.

#

This issue can be replicated both in the editor and during runtime.

#

It only happens when I use the <mark> tag to add the background color effect.

latent latch
nimble cairn
#

Changing transparency has no effect

latent latch
#

oh it's some sort of submesh? Does changing the sorting layer not work with it?

nimble cairn
#

It does, but then whenever I try and update my prefab or built it revers...

latent latch
#

there's obviously some sort of sorting issue problem and usually you see this behavior when objects are both transparent and are on the same sorting layer.

#

rather, there's no depth sorting so it defaults to sorting by pivots

nimble cairn
#

If I change the Order in Layer attribute to 1 from 0 in the TMP_Sub Mesh component class the issue is resolved. I just can't get it to "save" that change which makes me think there's another underlying issue

latent latch
#

as a bandaid just set it at runtime in start maybe

nimble cairn
#

That's not good enough tbh...

#

I really don't understand why the sub mesh's properties (all of them) revert on build/runtime

#

If I set the TMP transform.z to 0 and then the TMP_Sub Mesh transform.z to 0.013 the issue is resolved so it's obviously a z-clipping problem. I just don't understand why using the <mark> tag causes this issue and what an efficient alternative would be.

rigid island
#

sometimes generating a for loop in VS gives this... what gives?

for (global::System.Int32 i = 0; i < length; i++)
{
    
}```
fathom quartz
#

if (!(transform.Rotate(floatV,0,0) > transform.eulerAngles.x)){

#

whats wrong?

#

wait

#

nvm

rigid island
fathom quartz
#

i m doing it wrng

rigid island
#

not shite lol

rigid island
vestal arch
lean sail
rigid island
lean sail
#

seems to be the exact issue i just linked above

rigid island
vestal arch
fathom quartz
rigid island
fathom quartz
#

im trying to limit the rotation

rigid island
fathom quartz
#

this is my new code but now rotation has completely stopped

fathom quartz
rigid island
lean sail
#

just use cinemachine if you're making a camera script. these magic numbers will fail very quickly

fathom quartz
#

cinemachine?

#

but why didnt my code work tho

lean sail
#

because you are using magic numbers, and the code doesnt make sense itself. You are comparing the y angles and then trying to rotate the X axis by some -floatV value

knotty sun
fathom quartz
#

i keep losing my sense of logic

rigid island
#

also when in doubt, debug your values

fathom quartz
#

well i now have a good news and a bad news

#

the good news is that it stops me

#

but the bad news is that i cant move the camera anymore

#

i will use cinemachine anyway! thanks for ur help

rigid island
fathom quartz
#

it works now i changed the code that it looks at float y value

#
     float currentX = transform.eulerAngles.x;
     // Normalize angle to -180 to 180 to compare easier
     if (currentX > 180) currentX -= 360;
     // 
     // Calculate desired change code
     float desiredChange = -floatV;

     // Check if the camera is allowed to rotate up or down, basically
     //desired change > 0 means that its going up // desired change < 0
     // means that going down. 
     if ((desiredChange > 0 && currentX < 45) || (desiredChange < 0 && currentX > -45))
     {
         transform.Rotate(desiredChange, 0, 0);
     }```
fathom quartz
#

The y Rotation is handled by player object, X rotation handled by camera

#

but as i said its pretty bad ig i will go for cinemachine or smthing

rigid island
gaunt holly
#

Hi, tell me does anyone have an example of PlayerAnimator with Idle, Walk, Run, Crouch, Jump management and rotation to the right, left and turn around please? and how could the PlayerMovement script be with this management of animations?? Thank you in advance, please mention me

nova flame
#

what am i doing wrong? I can't seem to put the Player object in the Script slot.

heady iris
#

does a Player component actually exist anywhere?

main shuttle
#

He just didn't set it

heady iris
#

That's not a Player component

#

That is a game object named "Player"

nova flame
heady iris
#

Does it have a Player component attached to it?

nova flame
#

this should go in the slot

#

bu isnt working

heady iris
#

the name of the game object is completely irrelevant

main shuttle
#

But Fen, he doesn't even get the Player component in his script?

heady iris
#

why would you have to use GetComponent<Player>?

#

the field is of type Player

main shuttle
heady iris
main shuttle
# nova flame i cant set it

Well, you didn't set it before, and your not getting the PlayerComponent from anywhere. So it's always null, hence the null pointer reference exception.

hexed pecan
heady iris
#

so it be unreasonable to use GetComponent to assign that field

main shuttle
#

Sure, but he said this, that's what's confusing.

nova flame
heady iris
#

er, wrong reply

heady iris
heady iris
nova flame
primal wind
#

what about PlayerVisual?

nova flame
#

inspector of the empty player object

heady iris
#

There is no component named Player here.

#

If you want to refer to the PlayerInput component, then you need to refer to that, not Player

nova flame
#

uhh okay.. what am i suppose to do now? notlikethis

heady iris
#

do you not understand what this line of code is declaring?

[SerializeField] private Player player;

nova flame
#

its been 2 hours with changing scripts. now my brain isnt catcing up with stuff

#

ughhh

heady iris
#

This is a field that can hold a Player.

#

It cannot hold ANYTHING else.

#

If you want to drag an object into this field in the inspector, it must have a Player component on it.

#

If you want to refer to something else, then you must change the type of that field

nova flame
heady iris
#

Correct, because that game object does not have a Player component attached to it.

nova flame
#

thats is named player. i thought it works like that...

heady iris
#

When you drag a game object into a field that holds a component type, Unity looks to see if the game object has a matching component on it

heady iris
#

C# doesn't care about the exact names you've given to your game objects

#

The type system doesn't even know about those names

#

all it knows is that you said that field holds a Player

#

If I write "dog" on a piece of paper, that doesn't turn the piece of paper into a dog

nova flame
#

i see, so what makes that empty object as the designated object (player for this case)?

heady iris
#

You must attach a Player component to it if you want to be able to drag it into that field

heady iris
#

After all, as we can see in the same script...

#

you run player.IsWalking()

#

obviously you're calling the IsWalking method on a Player object

#

if player was actually a GameObject, then this would make no sense

nova flame
heady iris
#

you can do different things with a Player variable than you can with a GameObject variable

nova flame
#

okay. so how do i add a player component onto the Gameobject in this case. my enpty player object.

heady iris
#

surely you know how to add a component to a game object..?

nova flame
#

yes

heady iris
#

well then, do that

nova flame
#

what is a player object? the script?

heady iris
#

You wrote a script named Player.cs, yes?

#

that defines a class named Player

#

that extends MonoBehaviour, presumably

#

if you don't understand what any of this means you should stop what you're doing and use !learn to figure out how Unity works

tawny elkBOT
#

:teacher: Unity Learn ↗

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

heady iris
#

this is some really fundamental stuff here

nova flame
#

my bad i deleted some shit and i cant figure it out what. maybe that messed up.

#

i definitely had something attacted there xD

heady iris
#

you do in that screenshot, yes

nova flame
#

okay okay. it resolved hhh

#

i somehow deleted the component and i was verifying all the codes n shit for 3 hours T_T

nova flame
#

thanks @heady iris

#

@heady iris NullReferenceException: Object reference not set to an instance of an object
Player.Update () (at Assets/Scripts/Player.cs:14)

T_T

heady iris
#

Then you tried to use a null reference on line 14 of the Player.cs script

nova flame
#

gosh ill create logic from scratch

heady iris
#

What?

#

Look at line 14.

#

Something on that line was null

nova flame
#

Vector2 inputVector = gameInput.GetMovementVectorNormalized();

#

line 14

heady iris
#

sounds like gameInput was null, then

vernal wharf
#

Hi there, I'm trying to spawn GameObjects where I had TreeInstances, but when I try to spawn the tree, it's not even getting spawned on the same terrain

nova flame
#
using UnityEngine;

public class Player : MonoBehaviour
{
    [SerializeField] private float moveSpeed = 7f;
    [SerializeField] private GameInput gameInput;

    private bool isWalking;

    private void Awake()
    {
        // Ensure gameInput is assigned
        if (gameInput == null)
        {
            gameInput = FindObjectOfType<GameInput>();
        }
    }

    private void Update()
    {
        if (gameInput == null)
        {
            Debug.LogError("GameInput is not assigned!");
            return;
        }

        Vector2 inputVector = gameInput.GetMovementVectorNormalized();
        Vector3 moveDir = new Vector3(inputVector.x, 0f, inputVector.y);
        transform.position += moveDir * moveSpeed * Time.deltaTime;

        isWalking = moveDir != Vector3.zero;

        float rotateSpeed = 10f;
        transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * rotateSpeed);
    }

    public bool IsWalking()
    {
        return isWalking;
    }
}```
#

@heady iris i updated the player script

swift falcon
#

for some reason netcode will just not work on andriod for me. it works fine when i test it on my pc but when i build a apk file to test it on my phone it just wont work. my phone dose not want to connect as a host or client. anyone got a idea why this might be happning?

nova flame
hybrid jungle
#

I wanted to set up some rotating platforms with in the middle but something happened and everything now has the same imovable pivot point
I cant see where I am moving my empties becouse of this

primal wind
#

There is a button on the top bar

hybrid jungle
primal wind
#

I don't have Unity open so i can't show you directly

hybrid jungle
# primal wind

what to do with it no mater what I choose its always the same

primal wind
#

try the other one. it sounds like an issue caused by one or both of those

#

If its not then i have no idea

hybrid jungle
#

nothing changed

#

I managed to find a fix

#

its unity glitch

#

selecting this tool fixed the issue

plucky inlet
hybrid jungle
#

gizmo being visually stuck in one place

#

that is unitended behavior

#

aka

#

glitch

plucky inlet
hybrid jungle
plucky inlet
#

Ahhh okay 🙂 Good to know

last sail
#

!bug got a strange bug I'm trying to resolve:
using Unity 2022.3.13 and TMP 3.0.3

TMPInput component keeps breaking....
I create a TMPInput object in a prefab and everything looks fine - when instantiating the prefab, (using Addressables.InstantiateAsync) the input isn't working.
when opening the prefab again, I see "the associated script cannot be loaded" where the TMPInput was....

I have no copile errors in the project...

tawny elkBOT
#

🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.

📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!

💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.

For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting

plucky inlet
plucky inlet
last sail
plucky inlet
plucky inlet
last sail
#

So.... readding it worked (tho i tried this before....) i think im doing something that breaks it.... hold on

plucky inlet
last sail
#

Anyway, seems to work fine now. thanks for the help!

plucky inlet
#

Does anyone know, if iOS/visionOS fires the Application.lowMemory before the app crashes or when it already happened because no new memory could be allocated?

#

Docs say, you can use it to prevent the app of being terminated, but some experience knowledge from someone actually using it here might help

mellow imp
#

I love ScriptableObjects so much

keen oxide
#

Is there any way I can detect a user entering full screen with Alt+Enter?

rigid island
#

since alt-enter is a windows thing anyway

heady iris
#

doesn't alt-enter just resize the window?

rigid island
#

it switches it to full on fullscreen mode from window and vice versa

keen oxide
#

My problem is, that I have a resizable window, but when the user enters full screen it should go to native desktop resolution instead. I've build a way to change the resolution if the user clicks the Fullscreen Toggle button but it's not working with Alt+Enter unfortunately... Guess I'll need to manually check if it is in fullscreen and update the resolution?

rigid island
pallid raft
#

Does anyone know how to handle events when using the Unity Asesprite Impoter? the Docs only show how to add an event not how to call a function with it

heady iris
#

it's just standard animation events

#

so if you add event:Foo to a cel, then any component on the same object as the Animator will get its Foo method called when that frame is hit

clear dragon
#

I just updated to unity version 2023.2.20f1 - can someone explain to me why this gameobject "Text - Header", which is part of a prefab and I disabled its gameobject, is showing up as the default grey text color? Is this a bug or something?

#

How does it make any sense for it to be that color?

rigid island
#

maybe? 2023 is outdated now

#

2023 is now Unity 6

clear dragon
#

Its one of their official releases still, how is that "outdated"? Lol

#

are you saying you have Unity 6 and it doesn't do this with the color?

rigid island
rigid island
clear dragon
rigid island
#

if we want to take the word "official" like its worth a bone . Here

rigid island
clear dragon
#

No, I dont want to use 6

rigid island
#

suite yourself then idk that makes no sense. 2023 wont get updated

knotty sun
rigid island
#

there ya go

clear dragon
spring creek
clear dragon
knotty sun
spring creek
clear dragon
spring creek
#

2023 lts is unity 6

knotty sun
clear dragon
rigid island
#

its a bug because it should not be light gray but faded

clear dragon
#

like give me one good reason why it should be the exact same normal grey color, when they could pick any color? thats why i am confused, lol

clear dragon
knotty sun
rigid island
clear dragon
clear dragon
knotty sun
clear dragon
#

so you just accept anything that happens to you without questioning it? okay

knotty sun
rigid island
clear dragon
#

rofl

#

coming in here wondering why something seemingly got changed for the worse for no reason - trying to see if its a bug maybe, or if there is a reason for it to have been changed - and you guys are suggesting to not care about it?

#

does anyone know why it got changed? is there something I'm missing?

rigid island
#

idk look fine on 6

#

idk what yer yappin about looks fine to me

clear dragon
#

ok somaybe it is a bug, or some other reason/condition for it to be 'grey' colored text

knotty sun
rigid island
#

2023 was literally beta

clear dragon
rigid island
#

you would think it had bugs..

clear dragon
#

Its literally listed in their official releases

spring creek
rigid island
#

their website is dogshit at times cant deny that

clear dragon
#

it is in my hub, but I admittedly have an older version of the hub

rigid island
#

then see its failure on you

clear dragon
#

so its my fault they list it as official on an older version of the hub that they still update? 🤣

rigid island
#

seeya

clear dragon
#

lol coming in here and asking questions is somehow "blaming"?

clear dragon
#

i appreciate that

#

wasn't trying to come in here and argue with people, no clue why you guys jumped to Unity's defense with my question

rigid island
clear dragon
#

my literal question when i came in here was "is this a bug?"

rigid island
#

I did say it probably was so because its an old version and it didn't look normal

knotty sun
clear dragon
#

"is this a bug?"
"maybe"

#

thats an answer? 🤣

#

aight im done, i appreciate you checking @rigid island and sorry that for some reason everyone thinks im being a jerk or something

spring creek
rigid island
#

mate you are in development you outta learn how to test stuff yourself, i told you try unity 6 with that project and you refused what more you want

hexed pecan
#

Everyone could just stop escalating it

clear dragon
#

what channel should I be using?

spring creek
#

This is a code channel

clear dragon
clear dragon
spring creek
rigid island
#

indeed it should've been blue

spring creek
#

Steve is just a community member

knotty sun
rigid island
#

its also blue on 2022

hexed pecan
heady iris
#

huh, I didn't notice that before

#

and i've been using 2023.2.20f1 for a while

#

that is definitely off!

fleet tide
#

Hey !

    void Update()
    {
        if (EnemySelector.Instance.CurrentTarget != null)
        {
            EnemyHealth enemyHealth = EnemySelector.Instance.CurrentTarget.GetComponent<EnemyHealth>();

            if (enemyHealth != null)
            {
                int ratiohealth = (enemyHealth.CurrentHealth / enemyHealth.maxHealth) * 100;
                slider.value = ratiohealth; // Mettre à jour la barre de vie

                // Arrondir le ratio de santé à 1 chiffre après la virgule pour une meilleure lisibilité
                enemyHealthText.text = "Health: " + " (" + ratiohealth + "%)";
            }
        }
    }
}

I dont understand why in my code, when the enemy take 10 damages and his currentheath decreases, "ratioheath" pass from 100 to 0 instantly, no 90. Someone know why ?

rigid island
#

you are doing integer division

simple egret
#

(Dividing two int produces an int)

rigid island
#

so if you did 9/10
it will be 0.9 which gets truncated to 0, and 0 * 0 = 0

fleet tide
#

Oh okay thanks !

mellow imp
#

what stops someone from implementing an interface and then leaving one of the functions in it empty? If nothing is there to stop them, why add the forced function call in the first place?

spring creek
#

Why add it? Because an interface is a contract that it will exist, not that it will do anything

mellow imp
#

granted the performance cost would be very tiny

lean sail
#

empty functions is usually one of the arguments brought up for "composition vs inheritance". at the end of the day, it really doesnt matter and especially as an indie dev it is not worth caring about

spring creek
knotty sun
mellow imp
#

thanks

knotty sun
#

You are the one who has to supply the sense, all the language has to do is compile

vernal wharf
#

Hi, I'm using this to delete the TreeInstances at runtime. But how do I delete them without permanently deleting?

List<TreeInstance> newTrees = new List<TreeInstance>(0);
terrainData.treeInstances = newTrees.ToArray();
mild quail
#

I've created a script that implements IMoveHandler because I wanted custom events for when the user presses up or down, however, this seems to make it so it consumes the event and I can no longer move between any elements with this script and I just want it to interject before the event happens so I can still actually move between Selectables, is there a way to fix this?

#

nvm I got it

hexed pecan
vernal wharf
#

Like store it in a variable then delete them from that variable?

hexed pecan
#

You wanted to not delete the old trees forever?

#

So store them in a variable

vernal wharf
#

But after the game is stopped running, the variable will delete?

hexed pecan
#

If nothing holds a reference to the variable, then yes

#

You want to restore old trees after you quit playing?

#

Is it just in editor or in built game too?

vernal wharf
#

I'm creating them in the editor, looking to delete them at runtime. But if the game stops running, then runs again, I want all the trees from the mass-trees placement to spawn again

#

I found an alternate solution so I don't need a solution for this anymore

#

But just curious at this point if you have a way to not permanently delete treeinstance at runtime

#

It's not important for now

hexed pecan
#

One thing to try is to Instantiate the terrainData (to make a clone of it) at runtime, then assign it to the terrain

#

And modify the instantiated terraindata, not the original

vernal wharf
#

Interesting

#

What happens to the original terrainData. Do I just deactivate it?

hexed pecan
#

If I remember right, terrainDatas are stored as assets

#

So when you reload the scene, the terrain would just use the old terrainData

#

I haven't done this though. Just a theory

vernal wharf
#

Neat idea

#

Thanks @hexed pecan

chrome tendon
#

Hello, I'm having trouble with my raycast Field of View test
there is a buffer in between the mesh and the wall, could anyone help me w/ this?
thank you and i can show the script for it

#

the collider for the box is normal btw

vivid halo
#

I'm not a specialist in this, but I do notice that the raycast is actually going through the top-right corner. It seems to me the hitbox is off-center

chrome tendon
#

when you zoom into the collider of the box it shows this:

leaden ice
chrome tendon
#
public class fieldofview : MonoBehaviour
{
    [SerializeField] private LayerMask layerMask;
    private Mesh mesh;
    private float fov;
    private Vector3 origin;
    private float startingAngle;
    // Start is called before the first frame update
    private void Start()
    {
        mesh = new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;
        fov = 90f;
    }
    private void Update()
    {
        Vector3 origin = Vector3.zero;
        float fov = 90f;
        int rayCount = 100;
        float angle = 0f;
        float angleIncrease = fov / rayCount;
        float viewDistance = 50f;

        Vector3[] vertices = new Vector3[rayCount + 1 + 1];
        Vector2[] uv = new Vector2[vertices.Length];
        int[] triangles = new int[rayCount * 3];

        vertices[0] = origin;

        int vertexIndex = 1;
        int triangleIndex = 0;
        for (int i = 0; i <= rayCount; i++)
        {
            Vector3 vertex;
            RaycastHit2D raycastHit2D = Physics2D.Raycast(origin, UtilsClass.GetVectorFromAngle(angle), viewDistance, layerMask);
            if (raycastHit2D.collider == null)
            {
                // No Hit
                vertex = origin + UtilsClass.GetVectorFromAngle(angle) * viewDistance;
            }
            else
            {
                //Hit
                vertex = raycastHit2D.point;
            }
            vertices[vertexIndex] = vertex;
            if (i > 0)
            {
                triangles[triangleIndex + 0] = 0;
                triangles[triangleIndex + 1] = vertexIndex - 1;
                triangles[triangleIndex + 2] = vertexIndex;
                triangleIndex += 3;
            }

            vertexIndex++;


            angle -= angleIncrease;
        }

        mesh.vertices = vertices;
        mesh.uv = uv;
        mesh.triangles = triangles;
    }

   
}
leaden ice
#

Is the MeshRenderer always at position 0,0,0 with rotation 0,0,0 and scale 1,1,1?

chrome tendon
#

wait the renderer isnt at the origin

#

i'll try to set it rn

#

ayyy it works now

#

thanks 👍

slate imp
#

Hi guys, i have an issue, i'm using UVCS and the main branch have been forgotten, i'd like to push a branch into the main to get a latest version, but when i merge, I have some changes that are kept from the main and does not take all the code from the branch i merge from

I short i want to override all code from main by the code from a new branch

torpid depot
#

guys what ı can do for auto code complete in "Rider" IDE

#

sometımes it not completes and ı dont know why

#

got any prefer?

#

when ı say "kartOzellıkNesnesı.can" or somethıng

quartz folio
#

Rider seems to think you have decompiled that code

torpid depot
#

ıt cant fınd ıt

torpid depot
quartz folio
#

It means something's gone very wrong. It shouldn't say "IL code" anywhere unless you're inspecting someone else's code

torpid depot
#

why there says IL code ı dıdnt undurstand that

#

what ıs ıt

#

so weird

quartz folio
#

Make sure the JetBrains Rider Editor package in Unity's package manager is up to date, and restart Rider

quartz folio
#

That's the newest version anyway

molten crane
#

anyone got any ideas on why my unity packages are gone? I can't reference Unity.TextMeshPro assembly because unity doesn't import UI package for some reason (files are there when I show in explorer, reimport does nothing)
This is on new project on Unity 6000.0.5f1 updated yesterday from 6000.0.1f1, it has been like this on both versions

quartz folio
true sphinx
#

I have a very strange bug with input actions. I have arrow keys for aim and space for shoot, but whenever i try aim diagonally, so like up+left arrow keys, the shoot input DOESN'T trigger anymore. But, shoot DOES trigger when aiming up+right. Any ideas on what could be causing this?

pine carbon
#

shader trancparency not working

fixed4 frag (v2f i) : SV_Target
{
    fixed2 uv = i.uv;
    fixed2 center = fixed2(0.5f, 0.5f);
    fixed sqrDistance = pow(center.x - uv.x,2)+pow(center.y-uv.y,2);
    float angle = atan2(uv.x - 0.5f, uv.y-0.5f);
    if (sqrDistance < pow(.5f, 2) && degrees(angle)+180 < _Angle){
        return _Color;
    }
    return fixed4(0.0f, 0.0f, 0.0f, 0.0f);
}

Tags { "RenderType"="Transparent" }

#

ok i fixed it

lean sail
pine carbon
#

ok

#

i didnt saw that channel

sonic swan
#

Whenever I write code I endup having so many huge if statements

paper spoke
#

I dont know if this is a the right place for this question but im trying to have my enemy prefabs get the player position but i want to use something more efficient then findObjectWithTag

hexed pecan
#

Yeah just tested my cheap keyboard here https://keyboardchecker.com/
And I can see the exact same issue - "Right + up + space" works but "Left + up + space" doesn't

heady iris
#

yeah, it depends on how they detect the key presses

#

some check if a key is pressed on each row and column

scenic hinge
#

So would you guys say directly modify velocity for movement and otherwise use add force?

vagrant agate
plucky inlet
#

Has anyone ever experienced a prefab with a custom editor script not storing its values when exiting prefab mode?

somber nacelle
#

are you marking it dirty

plucky inlet
somber nacelle
#

the prefab when you modify it with the editor script

plucky inlet
atomic whale
#

how do I pack multiple layers into 1 layermask? if I expose a layermask to the inspector and just select the layers I'd like to include there and then print the integer of that layermask its always 0 which obv. means that not a single mask is active.

somber nacelle
#

it sounds like you are possibly resetting the value stored in the layermask if it is just printing 0

atomic whale
#

if so then I have no idea how as its just public LayerMask layerMask; into print((int)layerMask); (print on Start)

plucky inlet
atomic whale
#

nvm, fixed it. I had a list of layermasks before I realized I could just check multiple layers inside the inspector and I was setting the list but printing the singular layermask

runic linden
#

Whats the keyword I am looking for when I want to "clamp" a vector2 within a rect? My use case is a pointer that visualizes the direction of an out of screen POI. If I'd draw a line A from the screen center to the out of screen POI I want to pointer to be where the screen rect intersects with A.

night storm
soft shard
sonic swan
# soft shard If that is something you are trying to reduce, could you provide an example wher...

So im making procedural level generation for a hallway and I have 6 set presets that are different sizes therefore have different vector displacements for them to be attached for each one. They are randomly picked and attached together in a line. Then after 10 unique sectors the game moves onto a new area where 6 others presets are picked and a default level transition prefab is placed where the cycle repeats

#

I have 7 large if statements with 5 if within each

soft shard
# sonic swan I have 7 large if statements with 5 if within each

2 options come to mind that may be situation based, If those statements are iterating over the same type, you can try a switch-case instead (though that wont reduce your code just organize it differently), otherwise if your statements have repeat or similar code, you could create a bool-returning function and pass what you would normally have in the if-statement, as params instead (possibly as a for-loop), though it may depend on why you need those if-statements to begin with/what they are actually doing, are they just checking/comparing vector values?

twin path
#

Hi everyone, I was wondering if someone could help me with particle triggers / collisions. I've been looking and I cant find anything that helps me with what I want.
I have like a toxic trap when spawned a particle starts spreading but it does not detect the enemy, I have colliders in the enemy, I have the script attached to the particle with OnTriggerEnter and OnTriggerExit, but I dont know how particle works. Maybe it could be an stupid error, something that I did not see or something else.
Also I'm new to unity and just started studying it on school and I'm making a project for school 🙃 so dont be hard on me

fleet furnace
vestal arch
#

judging from the output, probably not

#

afaik, it just has to be a clamp for each dimension

#

though, you could make extension methods for it

#

i did, i just don't remember where...

sonic swan
atomic whale
#

is there a way to make the two bone ik from animation rigging work with targets that are being transformed by their parent? the contraint does not care about any movement that isnt done directly by the target object itself and thats really annoying.

modern creek
#

Weird bug for me.. I have a dialog box I wanna show once to a user, but something in player prefs seems to not be working as intended. Code:

        public const string PlayerPrefsShownAsteroidInfoString = "ShownAsteroidInfo";
        private void OnEnable()
        {
            bool hasKey = PlayerPrefs.HasKey(PlayerPrefsShownAsteroidInfoString);
            if (!hasKey || PlayerPrefs.GetInt(PlayerPrefsShownAsteroidInfoString) < 1)
            {
                v($"Player prefs key not detected. Showing info dialog. HasKey:{hasKey}");
                OnInfoShownAutomatically();
            }
        }
        public void OnInfoShownAutomatically()
        {
            InfoDialog.SetActive(true);
            PlayerPrefs.SetInt(PlayerPrefsShownAsteroidInfoString, 1);
            v("Asteroid info showing automatically. Setting player prefs key.");
        }

"HasKey" is false on subsequent runs. I've verified OnApplicationQuit is called (and my understanding is playerprefs are written at that point). What am I missing?

heady iris
#

and that "Setting player prefs key" line shows up in the log?

simple egret
#

Also attempt to use the overload of GetInt() that allows you to specify a default value (pass a value < 1 since you check for that), to rule out whether it's HasKey that has an issue. Doubt it, but worth a try

leaden ice
modern creek
#

Sigh, PB wins the cookie again.

#

🍺

heady iris
#

boing

gray mural
# modern creek

Do you really have a method v to print something into the console?

modern creek
#

Yep.

vestal arch
#

it's an arrow to the next line, clearly. c# 2d language confirmed

gray mural
#

Does is just call MonoBehaviour.print?

modern creek
#

and i(), w(), e(), d()

rigid island
#

omg

modern creek
#

Nah, it does some stuff with my logger DI

#

colors it, writes to files, expands stack traces when needed, etc

gray mural
modern creek
vestal arch
modern creek
#

verbose

heady iris
#

don't forget y()

#

for W H Y

#

😄

vestal arch
#

trace: am i a joke to you

gray mural
modern creek
#

comes from Android world.. Log.e(), Log.d(), Log.v() etc

vestal arch
#

im so glad i left

heady iris
#

yeah, makes sense

rigid island
#

as long as you understand it, all it matters more power to you

modern creek
#

also just a lot less typing imo

gray mural
modern creek
#

bit more functionality than Debug.LogError()

#

I don't type log.info - that's the android method.. i just type i()

vestal arch
heady iris
#

I simply instantiate letter prefabs to spell out my message in the scene

#

O H N O !

#

with rigidbody physics, obviously

vestal arch
#

alphabetical log levels when

heady iris
#

wordart console message support

vale wharf
#

I have a script that's updating a bunch of material's properties. I want to make sure they update otuside of playmode so I can visualize changes to the properties in the editor viewport.

Issue is, if I just set the values of the properties inside OnValidate (which runs when a variable gets changed), they just get reset whenever the scene gets saved (serialization problem?). I was able to solve this by just updating the properties every frame inside Update and adding the [ExecuteAlways] attribute to the script but this causes quite a performance impact because I'm constantly updating a bunch shader properties even when they haven't changed.

How can I make sure the settings won't get erased when saving so I don't have to update them every frame?

#

This is how I set the properties

private void SetMaterialValues()
{
    foreach (Material mat in Materials)
    {
        mat.SetFloat("_Cloud_Density", cloudScale);
        mat.SetVector("_Cloud_Movement", cloudMovement);
        mat.SetFloat("_Cloud_Strength", cloudStrength);
        mat.SetFloat("_Cloud_Cover", cloudCoverage);
        mat.SetFloat("_Cloud_Change", cloudChange);
        mat.SetVector("_Cloud_Step", cloudStep);
        mat.SetFloat("_Shades", shades);
        mat.SetFloat("_Brightness", brightness);
        mat.SetFloat("_MinimumDarkness", miminumDarkness);
    }
}

Which is called by:

public void ApplyChanges()
{
    if (overrideMatValues && Materials.Length > 0)
        SetMaterialValues();
}

Which is called in the update function.

lean sail
leaden ice
vale wharf
#

They're just added from the inspector.

leaden ice
#

if they're direct references to Material assets in your project folder then yeah @lean sail is right

vale wharf
#

Tried changing the code to this, but properties still reset when saving the scene.

foreach (Material mat in Materials)
{
    mat.SetFloat("_Cloud_Density", cloudScale);
    mat.SetVector("_Cloud_Movement", cloudMovement);
    mat.SetFloat("_Cloud_Strength", cloudStrength);
    mat.SetFloat("_Cloud_Cover", cloudCoverage);
    mat.SetFloat("_Cloud_Change", cloudChange);
    mat.SetVector("_Cloud_Step", cloudStep);
    mat.SetFloat("_Shades", shades);
    mat.SetFloat("_Brightness", brightness);
    mat.SetFloat("_MinimumDarkness", miminumDarkness);
    #if UNITY_EDITOR
        EditorUtility.SetDirty(mat);
    #endif
}
leaden ice
vale wharf
#

variables

#

also I should state this is just a monobehaviour with an [ExecuteAlways] attribute

leaden ice
#

could it be that these variables are the ones resetting when you save the scene?

#

Or I guess... you're not even going into playmode?

vale wharf
#

I'm trying to get them to update in editor without having to go into play mode

#

I can see that values of these variables aren't changing in the inspector when the scene gets saved so I don't think they're not serializing properly

vale wharf
#

This is what happening btw. When it turns fully dark green, that's when I'm saving the scene.

vale wharf
#

I can see the properties in the material ARE updating and staying updated too.

#

Figured it out, the script was relying on another script to blit a texture for the clouds which wasn't being called because the other script didn't have [ExecuteAlways]

spring creek
#

I think it is just a wrapper for it. So they can write a single letter instead of potentially like 4 or 5 with autocomplete

rigid island
#

yes but only works within monobehaviour

#

is not static

spring creek
#

Print is a wrapper for debug.log

#

With the exceptions nav mentioned

rigid island
#

no you can only use print() if its inside a mb (or class that derives from one ofc)

spring creek
#

I think it just has to be called from one

#

Whereas, of course, Debug.Log can be called from just about anywhere

#

It's shorter

rigid island
#

thats about it

#

Debug.Log also gives you option to pass in Object so you can click log and see which specific object has printed it

#

print can't do that

#

indeed

#

see "context"

dusk apex
#

Example: cs Debug.Log($"Click here to have {name} highlighted", this);

rigid island
#

no you misunderstanding what it does

dusk apex
#

The object is highlighted in the Unity Editor

rigid island
#

because if you have multiple enemies with same script, you want to know specifically which one printed it that value

#

yeah for debugging is very handy

#

the docs I linked you explains a bit

#

trial and error is perfectly fine

#

with time you want to speed it up, and thats why you begin placing more safeguards and debugs

#

unless its like deliberate though, i hardly use Null checking anymore (for "fixing" null refs)

#

you just find ways to ensure certain objects aren't null for example

#

dependency injection for example, you know for sure all objects are filled

#

usually you print if something isnt giving what you expect

#

my object isn't moving, debug.log the speed of the rigidbody is moving... what is wrong??
has to be something locking the player.. look at the inspector, oh Static is on.. ops

#

you can use Debug mode in the inspector to view private variables without serializing them, just not local ones.

#

acceptable at first, bad habit though imo

dusk apex
rigid island
#

like Visual Scripting?

dusk apex
#

Are you referring to visual scripting?

hard viper
#

sounds like visual scripting

rigid island
hard viper
#

he’s talking about visual scripting

rigid island
#

null reference exceptions

hard viper
#

null reference exception

dusk apex
hard viper
#

you tried to do something with a variable, but it was null

rigid island
#

they are only runtime exceptions

#

so they are harder to debug sometimes

hard viper
#

it’s where you code by sticking together nodes and shit

spring creek
#

Node based programming

rigid island
#

whats GMS?

hard viper
#

visual scripting makes your code look like this

rigid island
#

oh nice, i used Game Maker as one of my first engines

#

but it was back when it was Game Maker 5-8

dusk apex
#

You would still be required to know logical operations but may ignore c# syntax and direct interaction with the Unity API - you kind of still are doing both though, relative to constraints.

lean sail
#

Its shit in comparison, coding will always have more control of what you can do.

spring creek
#

I recommend trying to just code. But yes, it is an option

hard viper
#

well, yes. but also your code will literally look like that

spring creek
#

For any project

rigid island
#

believe me the code will be much easier to pickup

spring creek
#

You need to know code basically in order to use any node based programming anyways

rigid island
#

I came from doing drag and drop of Game Maker and ironically always thought GML and code in general was too complicated

hard viper
#

there is a reason every game dev codes, instead of being that crazy guy that tries to connect shit on a bulletin board

rigid island
hard viper
#

visual coding gets really messy very rapidly, in almost every IDE I have ever seen

#

i remember in game builder garage, where there is a hard 512 node limit, programs were pure spaghetti

rigid island
#

no joke blueprint knowledge is required on a lot of the job posting

hard viper
#

example GBG code

#

not a joke. actual code

#

i did not make this to make a point

dusk apex
rigid island
#

yea

#

thats a nightmare

hard viper
#

hold on

rigid island
#

unreal

hard viper
#

this one has organization:

rigid island
#

but to be fair a lot of people do write code like this, is just isn't as noticeable without the visuals lol

hard viper
#

this is why we tell you to code instead of visual scripting

dusk apex
#

Problem is, most nodes might simply be a type declaration that unfortunately adds so much static (television interference) to the whole picture.

hard viper
#

i have many script folders for a project, organized by topic

rigid island
hard viper
#

i have a physics folder, with physics engine subfolder and collider subfolders…

#

you’re going to have a LOT of everything

#

more folders usually gives better organization

rigid island
#

psht organizing files is the easy part

#

try organizing the spaghetti in th code

hard viper
#

as moving things from their folders can break stuff sometimes

#

unity can be smart about moving monobehaviour files

dusk apex
#

Whereas with code and good conventions, you'd be able to view the types up top (or wherever they're grouped at) and focus on specific methods - having a method call or referencing some data won't obliterate your screen.

hard viper
#

but sometimes it breaks some addons that depended on where the file was

#

not really

#

unity serializes all the asset files with a unique ID

rigid island
#

You dont use the path in code

#

You use their TYPE

#

class is a type

#

if you want a script aka normally a class, you just say the name

#
public class Foo
{
}

public class Bar
{
    public Foo foo;
}```
#

yeah but you make the reference with the type you want but you grab the instance of it

#

so head would be a public property/field of Player class

#

why do you need code for that?

marsh geode
#

Hey, so I'm getting loads of errors when I run my game through a build that are not tied to a specific part of code? Unity outputs them with a really weird format, I am building with Mono and disabled stripping level
at EditorControls.Update () [0x0013f] in <659d7b57dffc4b95b6241f694d9a6632>:0

#

I'd like to know how I can find what the error actually is, since I can't get any info on it

rigid island
#

why would u need code at all?

#

i dont understand how you would need scripting for this

#

I get that but all you need is the sprites inside a field

#

yeah but you would just keep the stored inside an array or something

#

you dont have to grab "assets" via code

#

you can of course use methods like Resource.Load but its unnecessary

#

yeah but you can just drag and drop them into the inspector of that script

#

pain

#

also its very fragile, what happens if somehow you change name or change folders

#

thats why you normally make a field that is serialized in the inspector so you can drop any resource directly there and if its renamed its still there, or moved

#

assuming you moved them within unity ofc. Unity stores them by ID not by names

#

You can use anything, the question becomes.Why

#

if its 2D its frame by frame, if you have a skeleton yo ucan use IK

#

actually I think unity has 2DIK too so you can technically move it also by code

#

you mean a delay between switching clips? thats something you can do in the animator already though no ?

#

its great, it organizes all your animations into a single state machine

#

idk anything about your game to make a suggestion

#

so topdown view?

#

so what do you mean by frame by frame then

#

the animator could let you bind specific animations to certain direction of char

#

I'm sure Unity compensates for that with animation, though dont take my word as this is not relly code related

#

I have no idea about 2D /animation aside from basics 😅

#

yeah if they are same animations, topdown is easier to get away with that

#

it probably does same thing you're doing now

#

takes in a direction input can output different animation

#

so you're saying you're manually switching feet animations instead of animation clips?

#

yes thats what 2D blen does on the Animator

lean sail
#

you should learn what an array is, you shouldnt require a line of code per object. in response to the part for 3d coding, the only coding for animations is really just setting the state or animation rigging. Unity already handles animations, its literally just plug and play.

#

if you're implying 2 lines per object, you're doing something wrong

spring creek
#

It will be the same amount of code no matter how many objects you do that to

#

By simply looping the array

fleet orbit
#

I have a question. Does anyone know if it is possible to load a scene before switching to it? I need to run a script in a scene to prepare a level.

pliant spade
#

Hi, quick question, why on the navmesh the auto generated links are not bi directional, they only go down not up

dusk apex
pliant spade
#

Maybe use the LoadSceneAsync function and then set the scene to enabled

fleet orbit
#

I guess. Is it possible to save a level's state and go back to it? because i just reload the scene currently but i might not want to repeat the loading process.

#

its to load a tilemap from a file btw.

dusk apex
lean sail
pliant spade
#

Oh did not scroll down far enough, sorry about that, the "code" part will come next

wispy raptor
#

I need a good terrain system for 2D games, basically i need that a player can collides with any type of terrain, slopes, etc. and the player must know which side is blocked by the terrain, someone knows about a good one?

cosmic rain
latent latch
#

also not a coding question :)

wispy raptor
wispy raptor
radiant scaffold
#

Alright fellas! I figured this might be the best place to help me with this issue as I've been facing it for a lil bit, as you can see with the first 2 shots there's a pretty significant spread but tight enough but the moment I try to shoot a close target the spread somehow hits the roof making it feel like an uncontrolled spread. This isn't a matter of the spread itself though else the spread would be huge during the first two fires. My bullets have a rigidbody with continuous collision detection and interpolation

#

It may have something to do with the speed but it just seems like the bullets are bouncing off the colliders and not registering the collision event which doesn't make sense to me

#
                GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity);
                currentBullet.transform.forward = directionWithSpread.normalized;
                currentBullet.GetComponent<Bullet>().Damage = Damage;

                currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
#

The code literally just spawns it in and hits it with a force

#

The attack point is the barrel of the gun and I prevent the player from shooting if they are too close so the gun can't be fired when it's just inside the target

wide terrace
wispy raptor
#

uhm but that is for artists

wide terrace
cosmic rain
#

Assuming they want to develop their own system, this channel is good enough for such a question

wide terrace
radiant scaffold
#

I had the same theory at one point but I don't think it'd explain the roof hits, especially if I keep my spread under 1 but here's the entire calculation

Vector3 directionWithoutSpread = targetPoint - attackPoint.position;

float x = UnityEngine.Random.Range(-spread, spread);
float y = UnityEngine.Random.Range(-spread, spread);

Vector3 directionWithSpread;

Vector3 right = fpsCam.transform.right; 
Vector3 up = fpsCam.transform.up;

Vector3 spreadDirection = (right * x + up * y);
directionWithSpread = directionWithoutSpread + spreadDirection;
#

targetPoint is just the result of a raycast hit

latent latch
#

for testing, try using set velocity on the spread over the force

#

also try drawing gizmos where the bullets spawn

leaden ice
cosmic rain
wide terrace
leaden ice
#

since you're not normalizing directionWithoutSpread

#

honestly it's jsut not a good idea to be using position displacement to do spread

#

you should use rotation angles

latent latch
#

oh yeah always normalize direction* calcs

leaden ice
#

But at the very least, you need to normalize that direction vector

radiant scaffold
#

Huh, okay

leaden ice
#

a looooong vector with your offset will not be perturbed that much in angle
a short vector will be perturbed a LOT

#

hence what you see

radiant scaffold
#

Alright thanks!

latent latch
#

yeah may want to funnel the bullets and use rotational spread cause you'll run into issues where it'll hit the walls on the side of you probably

leaden ice
#

Really I would do this:

Vector3 directionWithoutSpread = (targetPoint - attackPoint.position).normalized;

float x = UnityEngine.Random.Range(-spread, spread);
float y = UnityEngine.Random.Range(-spread, spread);
Quaternion randomRotation = Quaternion.Euler(x, y, 0);
Vector3 directionWithSpread = directionWithoutSpread = randomRotation * directionWithoutSpread;```
latent latch
#

then again up to preference. I've seen guns in games that do kinda do positional spread (flak cannon in unreal)

leaden ice
#

or maybe just:

Vector3 directionWithoutSpread = attackPoint.forward;```
wide terrace
# radiant scaffold Huh, okay

Just because I haven't gotten to use paint in a minute, here's an illustration of the original code (assume spreadDirection to be constant for the two scenarios):

radiant scaffold
#

I do run into an issue where if I'm facing a certain direction there's like no spread on the y but I can for sure figure that out on my own 😂

radiant scaffold
#

Thanks for all the help gang! Immediately the spread is better

cursive wing
#

i was trying to make some kind of 2.5D view but, why do my sprite randomly disappear when the camera is further away from ground?

leaden ice