#💻┃code-beginner

1 messages · Page 140 of 1

fringe plover
#

i had same problems before

sleek notch
#

You can't convert float to bool. But where is any value of float?

swift crag
#

well, let's check the documentation!

sleek notch
#

I saw

swift crag
#

public static float GetAxis(string axisName);

#

That doesn't look like a function that returns a bool to me.

fringe plover
# sleek notch I saw

well, youre getting value, but doing nothing else
you need to check, like, GetAxis(string axisName) >= 0.1

wanton canyon
#

I am trying to make fireflies randomly appear on my map at night. I took some code off the internet (see here: https://pastebin.com/pzfqGmFZ) and it does work - I was able to put a random game object in it and it spawned. However, when I put the fireflies particle system in it it does not work. I only have like three other lines effecting fireflies, by making them only appear at night in my program that manages the day/night cycle. Any ideas?

ionic zephyr
#

Can I use OnCollsion enter to check teh Collision between a character with CharacterController and an object with Capsule Collider? (With duckTyping)

swift crag
#

If you want to detect when a CharacterController tries to move into a collider, use this:

swift crag
#

beat me to it!

#

This will fire when your controller tries to move into a solid collider

fringe plover
#

someone?

#

pls...

ionic zephyr
#

and what about if I want the other object to be the one that checks the collision for example

swift crag
#

The other object must have a non-kinematic rigidbody, and it must actually hit you

#

So a stationary object that you walk into won't fire OnCollisionEnter, because the character controller will never actually collide

#

the controller sees the obstacle and positions itself in a valid, non-overlapping position

ionic zephyr
#

then why do I get this

swift crag
#

because your code is wrong

frosty hound
#

Because you didn't implement the function correctly

swift crag
#

did you read the error message

frosty hound
#

Take the time to look at the implementation/example in the docs.

wintry quarry
polar acorn
summer stump
#

The parameter of OnCollision and OnTrigger are different

deep robin
#

Can you not use operators on shorts? Why's it red? It shouldn't need casting.

swift crag
#

did you read the error message

ionic zephyr
#

and I dont want that

summer stump
ionic zephyr
#

can´t do this check

summer stump
polar acorn
summer stump
#

collision.gameObject or collision.collider

Like we said, the parameters are different, they work different. You need to read the docs

swift crag
#

I'd have to look at the IL to know which it is

ionic zephyr
#

I read the document

#

and still isnt working

swift crag
#

did you actually understand it, or did you just skim through the page and then give up reading it

summer stump
swift crag
#

the documentation makes it extremely clear what you can and can't do with these types

wanton canyon
#

~~I never understand unity documentation ~~

summer stump
swift crag
#

and if you don't understand something, ask about it

west sonnet
#

I'm trying to make a reload slider bar to show the reload progress in my 2D game. I've got it working, it's just that rather than the slider gradually increasing, it just jumps from 0 straight up to 1. I've tried to figure out how to make it work myself but I can't. Anyone have any ideas on how I could go about doing this?

swift crag
#

A coroutine would work.

#

You'd increase the value by a little and then yield return null; to wait until the next frame

#

and you'd do that in a loop until the value reaches 1

swift crag
#

and you're spawning that prefab with the ResourceGenerator component?

wanton canyon
#

yes

swift crag
#

Does the prefab work if you drag an instance of it into the scene while the game is running?
i.e. does it spawn firefly particles

wanton canyon
#

yes

#

but only at night

swift crag
#

if you don't try to turn them off at night, do they work correctly when spawned by the ResourceGenerator?

#

if so, you have a problem with that logic

west sonnet
swift crag
#

and then you need to pass that IEnumerator to StartCoroutine

wanton canyon
#

Just tried commenting out the stop() and play() code - still didnt work. Wondering if code I stole off internet just wont work with particle systems

swift crag
#

StartCoroutine(MyThing())

swift crag
ionic zephyr
#

Okay so I have accesed .collider.GetComponent<CharacterController> but still the collision isnt being detected, could it be problem of the CHaracterController collider then?

west sonnet
wanton canyon
swift crag
#

If a method doesn't return void, it must explicitly return a value

swift crag
wintry quarry
swift crag
#

So you write yield return statements instead.

west sonnet
#

Is it possible to use IEnumerator and Void? Or IEnumerator must always return a value?

swift crag
#

I think you need to read about coroutines

#

this has examples that line up very closely with what you're doing

west sonnet
#

Okay, thank you!

wintry quarry
#

IEnumerator IS the return value

west sonnet
swift crag
#

yes, it's not some kind of special keyword

swift crag
#

There is some compiler magic going on here. You never explicitly return an IEnumerator from the method.

whole sapphire
#

which property do u change to make a game object go unactive

west sonnet
swift crag
#

that doesn't exist

#

and activeSelf is read-only

whole sapphire
#

thats whta im going to say

swift crag
#

you need to call SetActive

#

activeSelf tells you whether or not the object itself is activated. It ignores parents.

#

whilst activeInHierarchy tells you if all of its parents are active

#

that's what determines if the object actually counts as being active

#

(both of these are read-only)

west sonnet
#

Does yield in tell Unity to wait until the next frame to execute code?

#

and does return null make the code return nothing?

fringe kindle
#

The 'current swingable' variable is used to make the vine itself swing when the player comes into contact with it, and I need it as a 'Transform' type

swift crag
#

When Unity sees this, it waits until the next frame to ask for another value (by default)

#

There are certain values you can yield that make Unity behave differently

#

for example:

#
yield return new WaitForSeconds(1f);
west sonnet
#

Ahh, I see. So Yield is essentially what keeps the enumerator repeating itself?

swift crag
#

this tells Unity to wait one second before it resumes

whole sapphire
#

how do u get the gameObject's name

swift crag
fringe kindle
#

As for my answer to the second part, for context, this script is for the vine swinging and player jumping off it. It's based on a tutorial video I watched where it worked with an object that had ConstantForce. I'm trying to achieve a similar jumping effect but with a third person controller, which doesn't have a rigidbody as it is kinematic.

I hope this gives you enough info on my situation

swift crag
#

foreach gets an enumerator and then repeatedly asks it for values until it runs out

vocal fable
#

why do i get this error? CS1656 Cannot assign to 'AddForce' because it is a 'method group', this is the code

swift crag
#

Imagine that, instead of just asking over and over, you only asked once -- and then waited for a while before asking again

#

That's exactly what Unity is doing

swift crag
#

did you mean to call that method?

vocal fable
#

oh shit

#

i realised

icy coyote
#

lol

vocal fable
#

there is a plus

west sonnet
#

Is return null making the code return nothing?

swift crag
#

yield return null makes the enumerator produce a value of null, yeah

#

IEnumerator is allowed to yield literally anything

#

and null is the most convenient way to yield something unity doesn't care about

west sonnet
#

Why do I need return null? Why couldn't I have just yield?

vocal fable
swift crag
#

yield break ends the enumerator immediately

#

Hence the need for yield return instead of just yield

#

personally, I wouldn't have minded if it was yield ... and yield break, but whatever

rich adder
#

oh nvm u had response

west sonnet
#

I see. Thank you

vocal fable
#

thanks anyway

swift crag
#

I dunno if there's a single complete list of every kind of thing you can yield from a coroutine to get special behavior

sleek notch
#

How to set point of rotation. I want to set point of rotation in turret

swift crag
#

You probably have your scene view on "Center" mode

#

Switch it to "Pivot" mode in the top left

#

This won't actually change how the game works. It just changes how the scene view shows the handles

west sonnet
#

This is my code at the moment. When the player shoots, the bar goes from 1 to 0.1, but doesn't increase

rich adder
west sonnet
#

The enumerator isn't repeating

swift crag
swift crag
sleek notch
#

I have in right way but I can't set the point

swift crag
#

if you want to do something many times, you need to use a loop

west sonnet
#

Ooh

swift crag
#

no, I never said that makes something repeat

rich adder
swift crag
#

I said that yield makes the enumerator produce a value and suspend itself until you ask it for another value

west sonnet
#

I see

swift crag
#

Now, if you do that in a loop, you'll produce many values

rich adder
#

you have to select the Move tool, gizmos first of all to see your true Pivot direction @sleek notch

swift crag
#

and the loop will repeat every time a value is asked for

opaque hare
#

I am creating a first person car driving game. i want the camera to move and rotate according the car. how do i make the camera rotate as the car rotates.

sleek notch
rich adder
#

You would have to find out where is the middle of that turret

#

you can do it in Unity as well but its harder

vocal fable
#

bruh i spent like a lot of time thinking why my movement doesnt work and then realizing that i didnt even call the movement function

sleek notch
#

It's in middle

rich adder
#

did you make sure ur in Local Pivot mode

swift crag
#

I don't think you set the scene view to "Pivot" mode.

buoyant knot
#

Raycast2D is just overused for physics, when Collider2D.Cast generally does that smarter

#

i have a couple of times where I use Physics2D.Raycast, but not very many

swift crag
#

well, it's certainly not relevant for figuring out which 2D object you're clicking on

polar acorn
swift crag
#

where is the ray being casted from and to?

#

a 3D raycast goes from the camera through a point on the screen

#

a 2D raycast can't...do that. it's 2D

buoyant knot
#

i’ve checked by benchmarking before. I suspect a lot of the cost comes from filtering shapes based on bounds, which both have to do exactly once anyway

stuck palm
#

is there a way to check if the Item class is an inherited class? like can i see if grabbedItem is of type HeldItem which is inherits "item"?

buoyant knot
#

in my testing, if you have a BoxCollider2D, using .Cast has a cost between 1 raycast and 2 raycasts

#

but it gives you a proper full query of that shape’s collision

rich adder
#

if(grabbedItem is HeldIem)

stuck palm
#

oh thats interesting

#

thanks

buoyant knot
#

also, in my testing, I tested a worst case of having like 200 colliders all in a blob, where 100 of them are not relevant to the query (filtered by ContactFilter2D)

swift crag
#
if (foo is Bar bar)
#

very handy

buoyant knot
#

oh cool

swift crag
#
            if (objective is SingleObjective singleObjective)
            {
                var display = Instantiate(displayPrefab);
                display.objectiveRenderer = this;
                display.Setup(singleObjective);
                return display;
            }
            else if (objective is ProgressObjective progressObjective)
            {
                var display = Instantiate(progressPrefab);
                display.ObjectiveEntry.objectiveRenderer = this;
                display.Setup(progressObjective);
                return display.ObjectiveEntry;
            }
#

for example

#

the objectives are inheritance-based whilst the objective displays are 100% composition with no common parent type, hence the mild ugliness

#

maybe I should extract a few things out...

west sonnet
#

I've got a reload bar which I currently have following my cursor position. How can I get it so that it stays just slightly below my cursor position?

polar acorn
west sonnet
#

How can I add a value to an objects position?

polar acorn
west sonnet
#

Input.mousePosition is a Vector3. It doesn't let me add a value to it using +

west sonnet
#

I can't add a Vector3 and a float together. It's also not letting me add a Vector3 and a Vector3 together

polar acorn
#

You have to add a vector3

west sonnet
gaunt ice
#

this is not how you create a vector3

polar acorn
west sonnet
#

How do I do it?

#

Is this correct?

stuck palm
#

why am i getting a null error when im trying to set the player script value from the held item?

keen ridge
#

how can I check if the pointer is over an UI element without using IPointerEnterHandler interface? Can it be done with raycasts for example? I'm using the interfaces, but there is one case when I need to detect in a single frame if the pointer is on the object

stuck palm
#

i might be stupid

#

never mind just reread my code

lament portal
#

Hey, not sure if thats correct channel to ask. correct me if im wrong pls. I Have a script to move an object with WASD and a script to rotate the camera up and down. However rotating left and right doesnt affect the WASD movment. Both scripts are attached to the same game object so i guess its rotating, but how to i make the rotation affect the movement?

timber tide
#

How are you moving your character inthe first place

#

such that are you using world direction vectors or via transform

fringe kindle
#

Good news, I managed to get the jump working but it doesn't give me any forward velocity from the swing automatically. Instead it's like I'm jumping normally

thorny prawn
lament portal
timber tide
#

ok, but still not sure what those vectors contain in gameInput.GetMovementVectorNormalized() because if you're strictly using world coordinates for movement then you're not taking in account of your transform rotation

#

though you've not really said why it's not working

timber tide
#

ah ok, it's probably world then so Pumpkin's solution there is one idea

lament portal
#

it does seem to affect the movement direction now, just not in the right way. I guess ill have to play around with it. Is there A way to start with WSAD input affecting the x and z that would be local to the game object?

#

works

timber tide
#

transform.left / right, ect

#

actually, there's not transform.left

lament portal
#

Pumkin stuff was good but I had to do transform direction instead of inversetransformdirection

timber tide
#

so -(transform.right) ;)

lament portal
#

thanks, ill look into it as well. It works the way it is but why not learn something new

celest holly
#

can anyone explain to me what the singleton pattern is good for?

rich adder
cosmic quail
#

😄

rich adder
#

example a GameManager, AudioManager

#

but yes google has an insane amount of examples

buoyant knot
#

are there any tools to help refactor code? I have some super tightly coupled code that I’d like to break up

rich adder
#

good design patterns

buoyant knot
#

i’m going back to address sins of my past

#

from following tutorials too closely

cosmic quail
# rich adder example a GameManager, AudioManager

yeah for example with AudioManager, you can emit audio from any script just by putting an AudioManager.Instance.PlayAudio() anywhere. the alternative to singletons is... dragging a reference to the AudioManager into every one of your scripts that you want to emit audio from? 🤔 oh delegates could be used for this too cant they? which would be better? wouldnt delegates be more performant actually? idk

rich adder
#

is just a method that runs another method when said event is invoked

queen adder
#

A singleton is just to ensure you have exactly one instance of something. Events are something else entirely

cosmic quail
rich adder
#

unless you made the event static which then would make it a singleton (sorta)

cosmic quail
queen adder
#

Not if it's a static event

eternal needle
buoyant knot
#

I don’t need a tool to try to do it for me, but to maybe visualize dependencies so I can untangle them

rich adder
#

oh there was a tool like that in asset store

#

it shows you all the branching in your components / dependencies

cosmic quail
buoyant knot
queen adder
#

Singletons aren't really a replacement for static events. You sometimes want to make sure you only have one instance of gameobject that's what singletons are for

rich adder
#

yeah Im trying to find the github link

#

someone posted some asset like that

rich adder
#

if an event needs to be static , it doesnt need a singleton class for it

buoyant knot
queen adder
#

What are they for then?

buoyant knot
#

singletons are so you only have one instance of a class

#

they don’t need any relationship to a gameobject at all

queen adder
#

Well in a unity context??

#

I meant an instance of a class sorry I said gameobject

buoyant knot
cosmic quail
queen adder
#

Exactly ^^^

eternal needle
#

Usually that one instance of a class would mean you also have 1 gameobject, the usual way to deal with duplicate instances is to destroy the duplicate gameobject

rich adder
buoyant knot
queen adder
#

Right

#

We / I meant instance

#

I used the wrong terminology my apologies

last fern
#

i need some help with a bit of math

if (rotationAxis.y > 0) {
            curx = cos(angletot);
            curz = sin(angletot);
            newx = forward->x * cosf(rotation) - forward->z * sinf(rotation);
            newz = forward->x * sinf(rotation) + forward->z * cosf(rotation);
            
            if ((angletot >= 0 && angletot <= 180) || (angletot <= 0 && angletot >= -180)) { //rotating left
                if (newx > 0) {
                    newx *= -1;
                }
            }
            
            *forward = {newx, forward->y, newz};
        }

i am trying to find the new normal vector after a rotation. i am using a formula currently to find the new x and new z values but the values i get dont look correct at all?

x: -0.224394 rotation: 0.258349 total: 67.7706
x: -0.995662 rotation: 1.2513 total: 69.0219
x: -0.993595 rotation: 0.206422 total: 69.2283
x: -0.180614 rotation: 1.27595 total: 70.5042
x: -0.0545774 rotation: 0.236213 total: 70.7404
x: -0.994916 rotation: 1.61707 total: 72.3575
x: -0.990943 rotation: 0.0338062 total: 72.3913
x: -0.315979 rotation: 1.11462 total: 73.5059
x: -0.0367984 rotation: 0.284685 total: 73.7906
x: -0.929816 rotation: 1.23072 total: 75.0213
x: -0.991815 rotation: 0.24885 total: 75.2702

the x values should be changing smoothly from 0 to -1 and then back to 0 but that is not happening 🤔 not sure if i am using the equation wrong or if the equation is wrong

buoyant knot
#

because it’s just false

swift crag
last fern
#

i am not using unity 😆 so i have to do it this way

swift crag
#

Quaternion.Euler(1, 2, 3) * Vector3.right produces a rotated vector

buoyant knot
#

“peanut butter is a shit condiment because you have to put it with jelly”

swift crag
#

then this isn't a unity question

queen adder
#

Bro it does lmao. An instance of of a monobehavior would be connected to a gameobject therefore if u have one instance of a monobehavoir you have one gameobject

last fern
#

ik but it is game programming related so i thought some people here may know

swift crag
#

a singleton of Component type will be related to a GameObject, yes

#

singletons can be of any type you want

polar acorn
buoyant knot
queen adder
buoyant knot
#

you are adding things to the definition of a singleton that do not exist

polar acorn
queen adder
#

Right I agree singletons don't have to be tied to monobehaviours they're used outside of game development

polar acorn
#

An object being a Singleton does not provide any information, either for or against, that object being related to a GameObject

true yacht
buoyant knot
#

just because you are in unity doesn’t mean you need to turn your POCO singletons into monobehaviours

queen adder
#

They are used outside of game development 💀💀

swift crag
queen adder
#

Like what are you on???

swift crag
#

not because they're used in other contexts

buoyant knot
#

there is zero relationship

true yacht
swift crag
queen adder
swift crag
#
        if(angle * Mathf.Deg2Rad <= deltaTime)
        {
            _isRotating = false;
            rotating = false;
        }
#

this is really suspicious to me

buoyant knot
#

it’s just wrong, you mean

#

if (# in radians <= # in seconds)

#

you should not compare values with different units

swift crag
#

You may be getting framerate-dependent behavior here, depending on exactly how the rest of your code works.

swift crag
cosmic quail
#

is there a reason to make non-monobehaviour singletons in unity?

swift crag
#

sure

#

I have lots of singleton ScriptableObjects, for example

#

I also have singleton plain-old classes

#

er, "plain old C# objects"

#

that's the more common name

#

A singleton is something of which there is only one.

#

That's it.

rich adder
cosmic quail
swift crag
cosmic quail
swift crag
#

by definition, there's exactly one instance

cosmic quail
#

ok that makes sense

buoyant knot
#

you should not mix up static classes and singletons

#

while technicallt true, that’s a really dangerous equivalency

#

most people do not consider static classes to be singletons

swift crag
#

oh yes, I should really say a static field

#

I misread.

#

A static class is just a class that has no non-static members

#

there aren't any instances in the first place

#

I guess it kind of works as a singleton, but that's really stretching the definition

buoyant knot
#

it’s just not a singleton, because there are zero instances

cosmic quail
# swift crag I misread.

oh. so a static class isnt a singleton? why not use a static class then instead of a singleton class

swift crag
#

Mathf is a static..struct, for example

#

It's just a way to ensure you don't accidentally put instance members in something you never intend to create instances of

buoyant knot
swift crag
#

I wouldn't say they have "downsides". It's just a way to have the compiler check your work.

cosmic quail
buoyant knot
#

static classes (vs singleton):

  1. stored on heap (instead of stack)
  2. No instance => hard to debug
  3. Keep changes to variables everywhere
  4. can’t be destroyed
swift crag
#

points 1-3: what?

summer stump
buoyant knot
#

there are several parts I’m forgetting

buoyant knot
summer stump
#

Just because YOU don't instantiate it doesn't mean it is NOT instantiated

swift crag
#

there is, indeed, a static constructor that executes before the first usage of any static members

summer stump
buoyant knot
#

but i’m not sure it’s fair to call it an instance

swift crag
summer stump
swift crag
#

It's just before you actually get to use it

swift crag
rich adder
buoyant knot
#

the members of a static class belong to the definition of the class, and not to any instance

swift crag
#

the class itself is not an instance of the class

#

so I would agree on that

rich adder
#

would not say the class IS the instance

swift crag
#

Note: Generally speaking, it is useful to think of static members as belonging to classes and instance members as belonging to objects (instances of classes). end note

buoyant knot
#

“A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for null object references. However, most…”

swift crag
#

you know, now that I've thought about it

buoyant knot
#

meaning, calls to methods in a static class are not calls to an instance

swift crag
#

a static class is absolutely a singleton: it's the platonic ideal of a singleton, in fact

summer stump
swift crag
#

all of its members are guaranteed to exist, and they're guaranteed to exist exactly once

buoyant knot
#

because a static class has no instances by definition

swift crag
#

it is impossible for the definition of a singleton to be violated

buoyant knot
#

and therefore, a static class cannot be a singleton, which requires exactly one instance

rich adder
#

this conversation is hilarious 😆

languid spire
#

This whole conversation is moot.
If you could define Monobehaviours as static, you would, as you cannot you use the singleton patttern.
In normal C# if 'There can be only one' then its a static class

buoyant knot
#

you can’t have 1 instance if there are zero instances to be had

swift crag
#

of course, this is all more-or-less meaningless bikeshedding

rich adder
#

semantics

swift crag
#

it's a singleton if it looks and feels like one to me!

#

🦆

buoyant knot
#

wiki, for whatever it is worth: “In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to a singular instance”

#

static classes are not singletons

#

they are zero-tons

#

i don’t undersrand why this is controversial

wintry quarry
#

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new operator to create a variable of the class type.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members

#

in other words - no instances. Just a named holder for static members

swift crag
#

the question is whether it's a meaningful distinction

wintry quarry
#

Yes because you can't put the thing into a collection. You can't call .HashCode() on it

#

it's literally not an object by the C# definition of objects

swift crag
#

Hm, that is true. There's no thing there in the first place.

#

and that has meaningful implications

wintry quarry
#

if you did MyFunction(object x) a static class could not be passed into that

swift crag
#

you can't pass it around

true yacht
swift crag
#

yeah, that's a vital difference

buoyant knot
swift crag
#

to combine the two things

#

not necessarily in the exact same class :p

timber tide
#

big benefit of singleton is controlling its instance for each scene

#

as static would still exist between

swift crag
#

also I'm going to make a thread for this because I think it's clogging up the chat

wintry quarry
buoyant knot
#

one distinction I forgot is that singletons allow inheritance and implementation of interfaces

timber tide
#

that too

#

more of a limitation to static though imo

true yacht
timber tide
#

later .net versions have more to static classes

swift crag
true yacht
#

i just change this one

#

and it does not works

swift crag
#

if you don't check your values, you're going to get nowhere

buoyant knot
swift crag
#

no matter how many times you tell us it's not working!

timber tide
#

right, that is true

true yacht
buoyant knot
#

eg even if the language let you put an interface on a static class, you could not exploit that in any way

timber tide
#

Not that I've tried to really pass singletons around or contain them but I could see some usage

buoyant knot
#

i’m currently working with a collection of singletons that all implement an interface

#

collection of custom draw logic, where each one is a singleton, which corresponds to exactly one unique class with an ICustomDrawLogic interface.

#

so I can iterate through all singletons with the interface and call their interface methods

#

can’t do that with a static class

#

and the individual singletons do things like Move the start point, move the goal flag, handle text input boxes,…

rich adder
#

yes plz

buoyant knot
#

i’d like to keep this static, so I’m done

#

0 instances of threads plz

timber tide
true yacht
swift crag
#

OnAnimatorIK can get run multiple times in a single animation update.

#

that is probably what caused your problem

true yacht
swift crag
#

but did you ever actually try logging anything...?

#

I feel like you haven't been doing anything that's been suggested to you

#

maybe you just haven't been showing us what you were doing, but,

buoyant knot
#

looking into service locator pattern, I’m not exactly sure what the big deal is against it

swift crag
#

it was very frustrating to watch you ask for help, say it's not working, and then just...leave again

buoyant knot
#

it’s like a strategy pattern with persistent instances

true yacht
timber tide
#

You can think of "Local Player" in multiplayer games

buoyant knot
#

i don’t see the issue

#

or rather why there is hate

#

you just have a collection of an interface, and keep tabs on a “current index”. idk where the problem arises from

ionic zephyr
#

When you load a scene what are the things you loose exactly?

timber tide
#

everything that was destroyed in your previous scene

buoyant knot
timber tide
#

but you can mark objects so they aren't destroyed when the scene is unloaded

ionic zephyr
#

DontDestroyOnLoad, right?

timber tide
#

ye

buoyant knot
#

the only thing you keep are:

  1. gameobjects maked dontdestroyonLoad
  2. scriptable objects, and other assets that are just always around
  3. variables in static classes
  4. C# objects not tied to gameobjects
swift crag
#

basically, anything that was in the scene is lost

buoyant knot
#

#4 i’m pretty sure is true as long as it isn’t only referenced by gameobject-tied objects that would be GC’d

swift crag
#

When the scene unloads, there's a nice long GC pause

#

grumble

#

my game's loading sequence feels so good if I just never unload any scenes

buoyant knot
#

just do what I do, and make your whole game in 2 scenes: main menu scene, and the everything else scene 👍

buoyant knot
#

i might make 2 more scenes tops for menus, but not much more tbh

twin bison
#

HI boys. Is there like a shortcut like in javascript for doing something like this in c#?
healthBar != null && healthBar.SetHealth(amount);

#

if healthbar is not null, call the sethealth func

wintry quarry
#

that's valid C# right there

#

but yes there's a shortcut

#

however. it is not friendly with Unity objects.

fringe kindle
#

I think I know how to make the jump happen:

I gotta trick the game into thinking I'm grounded whilst on the vine collider.

Is there a way to add that in my vine script under 'OnTriggerEnter', from my ThirdPersonController code?

wintry quarry
#

SO it is not recommended to use it

twin bison
languid spire
#

healthBar?.SetHealth(amount);

wintry quarry
# twin bison
if (healthBar != null) healthBar.SetHealth(amount);```
twin bison
slender nymph
#

null conditional does not handle destroyed objects though so you'll run into MissingReferenceExceptions

#

so go with the if statement that praetor suggested

wintry quarry
#

This would be the shortcut but if HealthBar is a MonoBehaviour it isn't a good idea:

healthBar?.SetHealth(amount);```
buoyant knot
#

a destroyed object == null, but not is null

#

unity overrides == null for gameobject

polar acorn
# twin bison

Your function returns nothing. If you want to and it with a bool it'd need to return a bool

twin bison
#

So if an object is destroyed healthBar? would be truthy?

buoyant knot
twin bison
buoyant knot
#

so destroyed?.DoX()
would try to call DoX because destroyed is not null. It just == null. Then it will throw an error

ionic zephyr
#

this is the before and after of the load, should I use DOntDestroyOnLoad in all this objects and scripts?

wintry quarry
slender nymph
# twin bison So if an object is destroyed healthBar? would be truthy?

c# does not have a concept of "destroyed". when you destroy a UnityEngine.Object it happens on the c++ side then the overridden == operator will return true when comparing to null but the object isn't actually null until you assign null to the variable.
So using the null conditional operator and other operators that check against true null will return false when an object is destroyed but if you still try to access it you'll get a MissingReferenceException (which is one of unity's exceptions) that will basically be like "you're trying to use a destroyed object"

buoyant knot
#

i’m 7 months into a project, and I have 1 gameobject with 3 monobehaviours that are do not destroy on load. And that is fine

ionic zephyr
#

Also script links are missing at the top, how can I preserve them

twin bison
wintry quarry
#

It really depends what you're trying to do and what the lifecycle of all these objects is

ionic zephyr
wintry quarry
twin bison
#

I create my game world via tiles and tilemap but in code. When I'm in editor not in play mode i dont see that world obviously. Now i know there is some unity trickery to generate the world also in editor mode - but i can't find it also don't know how its called for googling it. Can somebody guide me into the right direction please?

wintry quarry
#

Also why do you have multiple InputManagers. @ionic zephyr ?

wintry quarry
ionic zephyr
#

Not really, why?

#

it is the inspector for the GameManager

buoyant knot
#

out of curiosity, is it possible to tell unity to request a big block of working memory from OS, to save on allocation time? or is this already a part of unity

#

like if I know my game is going to be consistently using 10 MB of RAM or whatever, is there a way to articulate this so I can just ask for 10 MB of RAM, and we only try to allocate more if it isn’t enough?

twin bison
#
[ExecuteInEditMode]
public class CreateGround : MonoBehaviour
{

....

Omg that all it took to generate the world in editor mode. Holy hell I love unity 😄

ionic zephyr
royal ledge
#

How do i assign a prefab to a variable in a script which is applied unto prefabs during runtime, but never exists on prefabs in the editor? Meaning i can't use [SerializeField]

slender nymph
buoyant knot
#

prefab reference needs to be serialized somewhere, and script gets reference from their, to pass on like box described

royal ledge
#

Ah ty guys

polar acorn
ionic zephyr
#

a LoadScene

#

it says it in the message

polar acorn
#

Okay, so it is a DDOL

ionic zephyr
#

the thing is I lost the references because it is referencing components of the previous scene

polar acorn
ionic zephyr
#

There is no gameObject UI Manager

polar acorn
ionic zephyr
royal ledge
#

When I use AddComponent<randomScript> is this creating a object of that class? Meaning I could do the dependecy injection in the constructor?

polar acorn
slender nymph
polar acorn
#

Making your UIManager a DDOL

ionic zephyr
polar acorn
#

That persists between scenes

#

without having a UI that persists between scenes

ionic zephyr
languid spire
polar acorn
royal ledge
#

@languid spire You sound like my father, he always hits me with the "yes and no's", I see thanks

ionic zephyr
#

so maybe the solution is making another gameObject that contains the UI Script

#

which isnt DDOL

languid spire
toxic latch
#

if bob.age = 87 is declared in a script, and in another script we declare string name = bob, will name.age return 87?

swift crag
#

none of this would compile

languid spire
#

no

swift crag
#

That code might make sense in something like GameMaker with a big pile of global variables

#

and no static types

languid spire
#

JS or TS

toxic latch
swift crag
#

I've had the opposite problem when looking at gamemaker code

#

"how on god's green earth do people make games this way?"

eternal needle
swift crag
#

in Unity, you're going to want to assign references in the inspector to let one component know about another component (when both are in the scene)

#

You don't make a ton of globals.

#
public class Person : MonoBehaviour {
  public int age;
}

public class Car : MonoBehaviour {
  [SerializeField] Person driver;

  void Start() {
    if (driver.age < 16) {
      Debug.Log("Kids can't drive!");
      Destroy(driver);
    }
  }
}
#

..that might be a little too draconian

polar acorn
rocky canyon
#

lmao

orchid trout
#

What are possible reasons why an editor script in unity is not changing the appearance of the associate script in Inspector?

  • its in 'Editor' folder
  • no errors in the console
  • scripts recompiled correctly
  • It works as expected in one project, when copied over to a new project, the same code in the same version of unity under the same folder structure path doesnt work
languid spire
#

missing asset

swift crag
#

it provides a custom editor for all monobehaviours

orchid trout
swift crag
#

It's a library to add things like buttons to component inspectors

orchid trout
#

Oh in that case if its some kind of package I had to install, I dont think so

#

Ill check though, im not the one who set it up

swift crag
#

I would do a search for CustomEditor

#

I'm not sure what happens when there are several custom editors to pick from

orchid trout
swift crag
#

ah, I mean in your code editor

toxic latch
orchid trout
#

Oh like in visual studio

swift crag
toxic latch
#

Like I can drag and drop whatever I want into the serialized field in the inspector, but couldn't seem to figure out how to get a different driver's age.

orchid trout
swift crag
#
public void GetIn(Person driver) {
  if (this.driver != null) {
    GetOut(this.driver);
  }

  this.driver = driver;
  // do anything else you need at this moment
}
#

if you need to see who's driving the car, you could either make the field public (which means you can't force GetIn to be used, which is lame)

#

or you could make a property that only tells you who's driving

#
public Person Driver => driver;
orchid trout
#

I will try to restart unity, thats always a candidate 🤔

swift crag
#

or you could write a method that just returns it

#
public Person GetDriver() { return driver; }
#

hang on

#

the cat is clawing me

toxic latch
#

I was trying to do so in the context of instantiating a prefab.

swift crag
#

solved. he was starving to death (food bowl not 100% full)

orchid trout
#

after restarting unity, now I get this error when I select my asset that im trying to have a custom inspector for

toxic latch
#

Like I can instantiate whatever prefab is loaded in the SerializedField in the inspector no problem, but couldn't figure out how to instantiate something else — i.e. change the prefab loaded into the serialized field in the inspector

swift crag
#

why not just instantiate another field?

#
if (makeCar)
  Instantiate(carPrefab);
else
  Instantiate(bikePrefab);
edgy prism
#

Hello, I have quite an important method in one script "CalculateStats" that is private, I want to call it from another script but it does what it says on the tin and feel like making it public might give people an easy way to mess with their stats. What is the standard way of calling it from another script without making it public? subscribing to an event?

#

Alternatively should I even worry about just making it public?

polar acorn
#

that's literally the definition of public

slender nymph
#

and if you are worrying about people who are modifying your game, they will likely be able to call it via reflection anyway so there's no sense in worrying about making it public just to prevent modding or whatever

edgy prism
polar acorn
#

if another script needs to call it it needs to be public

edgy prism
languid spire
#

in terms of protecting your code, that would make no difference

slender nymph
edgy prism
#

Thanks everyone for your help I appreciate it ❤️

languid spire
#

there is one thing that you can do although it will make little or no real difference, use internal rather than public

toxic latch
#

GameObject newDagger = Instantiate(_prefab) spawns the dagger no problem

edgy prism
polar acorn
swift crag
#

i don't understand what the problem is. If you want to have multiple choices, you need multiple references.

polar acorn
swift crag
#

You should either have several fields -- one for each weapon -- or should have a list of weapons

toxic latch
swift crag
#

If you're handling all 50 in a similar manner, then yes, make a list

empty dagger
#

Hello, I'm trying to make it so there's seperate animations for jumping and falling, but it's not triggering the fall animation and IDK what I could possibly be doing wrong, the Debug.Log is working when it should be so IDK what the problem could be

https://gdl.space/cunobodoqu.php

halcyon summit
#

Does anyone know any common things to look for when a public override in a subclass isn't being called even though the main class's function is being called?

slender nymph
#

make sure it is actually an overriden method and not just hiding the base class's method

swift crag
#

the parent class's method must be virtual, and the child must override it

#

and, of course, the runtime type of the object must be the child class!

halcyon summit
#

Yeah I'm using virtual and override. In fact, a different subclass of the same base class is working just fine - but this copy/pasted alternative subclass isn't working, despite all the code being identical. Is there somewhere I should look elsewhere?

slender nymph
#

check for errors in the console and if you are still having trouble, show the relevant code

edgy prism
#

Going back to my previous question about making a method public if I just found a way to do the same thing but allowing me to keep the method private is that something I should do or does it not make much notable difference?

swift crag
#

Private members make your life easier.

#

I've been doing some refactoring of old code. Whenever I stumble into a public field, I have to shift-F12 it to find out all of the places that read it

#

...and that write it

languid spire
edgy prism
#

I mean as far as I can tell this will be the only other place that intentionally calls it

edgy prism
languid spire
#

yes

edgy prism
#

Ok damn that's good news for me then I was under the impression it was bad practice to make anything public unless absolutely necessary

languid spire
wintry quarry
edgy prism
swift crag
#

Access modifiers get a lot more important once other people start depending on your code.

#

changing things that people depend on can break their code

edgy prism
swift crag
#

and "you from six months ago" is pretty close to another person (:

rocky canyon
edgy prism
rocky canyon
#

i have a tendency to always add a multiplier when i use a value... multiply it by (1) even if i never use it again lol

ionic zephyr
#

the condition for the method to work is a Mouse Input

polar acorn
ionic zephyr
#

I supposed that but the check is also being done every frame

#

I tryed this

modest dust
#

your last else if is basically an else since it's a negation of the previous else if statement

stuck palm
#

how can you apply rotational force in code? to make like an object start spinning

rocky canyon
#

AddTorque if its a RB

#

or AddRelativeTorque

#

if not u gotta manipulate its rotation propertie

stuck palm
rocky canyon
#

its a force..

queen adder
rocky canyon
#

a float.. and integer

queen adder
#

why does this happen when i build my app?

stuck palm
queen adder
#

this never happens in the unity editor

rocky canyon
queen adder
#

it is

#

and the movement is broken

rocky canyon
#

ull have to probably share the code.. sooo many things that could be

queen adder
#

alright

rocky canyon
#

im betting the movement w/o the camera logic works

ionic zephyr
queen adder
ionic zephyr
rocky canyon
queen adder
#

alright

rocky canyon
#

if it works fine w/o the cam movement then you know for sure its in that code somewhere

sacred egret
rocky canyon
#

if the problem still exists even with teh camera stuff gone.. then its something bigger

ionic zephyr
queen adder
#

it seems like

#

the rigidbody isnt freezing its position

#

ill go fix that

slender nymph
ionic zephyr
#

Oh sorry, a Mouse Input

#

GetKeyDown

languid spire
polar acorn
rocky canyon
#

^ im thinking the same..

ionic zephyr
slender nymph
# ionic zephyr GetKeyDown

oh well if you aren't getting any mouse input or key presses in this class, it's likely due to the lack of actually checking any input in the class you shared

polar acorn
rocky canyon
# ionic zephyr I tryed this

that Input only happens 1 frame... meaning when u press the mouse button the attackanimation goes true.. but the very next frame.. it goes back to false..

ionic zephyr
rocky canyon
#

even if u never even release the mouse button

#

b/c the ifstatement only returns true the exact frame u press the mouse button..

ionic zephyr
rocky canyon
#

if u want it to be continously true u probably want just the GetKey() or the mouse version

polar acorn
#

So, with that resolved, question: Why do you have a single variable that seems to be controlling like three different kinds of animations instead of actually having parameters related to the animations and proper use of state transitions?

ionic zephyr
#

yeah, I tryed the Attack with bool and worked right, Im just trying another way

honest haven
#

https://gdl.space/zanidasebo.cs i am alittle lost. im trying to make my player run while holding the left shit and w key. it works if i press w and then left shift. on line 68 the direction magnitude is 0. So this is where im lost how does line 44 work?

polar acorn
rocky canyon
#

it evaluates whether the player's input (horizontal and vertical axes) results in a movement direction that has a significant magnitude.

honest haven
polar acorn
#

if it's greater or equal, it runs the condition starting on line 45. Otherwise it reaches line 68 and prints 0

#

If it's not greater and it's not equal, it must be less

honest haven
#

so why does line 71 not print yet line 68 does

rocky canyon
#

he's saying ur leftshift doesnt run. b/c its nesting in an else statement that doesn't run at the same time ur moving

polar acorn
rocky canyon
#

ur condition is just twisted up

polar acorn
#

I'm not sure why you expect line 71 to run

#

it physically cannot be greater or equal to 0.1, you just checked that

honest haven
#

yh my conditions are wrong just throw me off

rocky canyon
#

u can put conditions Inside other conditions

#

instead of confusing urself with else if and else..

#

u can ```cs
if (direction.magnitude >= 0.1f)
{
if (Input.GetKey(KeyCode.LeftShift))
{
currentState = PlayerState.Running;
_animator.SetBool("isRunning", true);
controller.Move(moveDir.normalized * speed * runningSpeedMultiplier * Time.deltaTime);
}
else
{
currentState = PlayerState.Moving;
_animator.SetBool("isRunning", false); // Reset isRunning when not running
controller.Move(moveDir.normalized * speed * Time.deltaTime);
_animator.SetBool("isMoving", true);
}
}

#

u can do something like If( u have direction) inside this block do another check IF u have movement AND if u have leftshift pressed. etc

#

but, the more experience u have with them.. the more it makes sense on how to structure them

#

if, if else, if else, if else, else... etc gets nasty and hard to read lol

honest haven
#

i think im lost. if line 44 if (direction.magnitude >= 0.1f) { and line 71 if (direction.magnitude >= 0.1f) are the same and all i have done is left shift. why does line 71 not work. yet if i let go of shift key and press W my code works inside line 44

rocky canyon
#

u dont even need the other if.. tbh

#

if it isnt a magnitude greater then it has to be a magnitude lower

polar acorn
honest haven
#

yes if first condition is not meet else will always run

polar acorn
rocky canyon
#

yup, so if ur not moving.,. the else in ur case runs.. which is where u also check for leftshift..

polar acorn
#

What conditions must be true for this if statement to never execute

rocky canyon
#

that doesnt make any sense lol.. if ur not moving.. why even bother checking if shift is pressed?

#

not like ur gonna sprint while idling

honest haven
#

it will be idle

rocky canyon
#

ya, no reason to have ur leftshift check WHILE ur idle.

polar acorn
# honest haven it will be idle

If you are specifically only running this block of code when the magnitude is less than 0.1, why would you expect an if statement checking if it's greater than 0.1 to ever execute

rocky canyon
honest haven
rocky canyon
#

actually it'd look more like this..

honest haven
#

to idle

rocky canyon
#

the orange block all would be running if ur moving

#

the else statement would be if ur not moving..

polar acorn
#

You're checking "If this thing is less than 0.1 and also greater than 0.1" which makes no sense

rocky canyon
#

please delete this and try again !code

eternal falconBOT
honest haven
rocky canyon
#

the code part of it anyway.. no ones gonnna read that code like that 😦

rocky canyon
#

but in the else statement is if ur not moving.. it doesnt matter if ur left shift is pressed in that case

#

ONLY if ur moving (THE FIRST IF)

earnest tendon
#

hello, im trying to make a vampire survivors type game and rn im trying to set it up so whenever the player moves out of a loaded chunk it loads another chunk, but for some reson i keep getting this error whenever i move my character
this is the code thats currently giving me issues:

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

public class MapController : MonoBehaviour
{
    public List<GameObject> terrainChunks;
    public GameObject player;
    public float checkerRadius;
    Vector3 noTerrainPosition;
    public LayerMask terrainMask;
    PlayerMovement pm;

    // Start is called before the first frame update
    void Start()
    {
        pm = FindObjectOfType<PlayerMovement>();
    }

    // Update is called once per frame
    void Update()
    {
        ChunkChecker();
    }

    void ChunkChecker()
    {
        if (pm.moveDir.x > 0 && pm.moveDir.y == 0) //right
        {
            if (!Physics2D.OverlapCircle(player.transform.position + new Vector3(20, 0, 0), checkerRadius, terrainMask))
            {
                noTerrainPosition = player.transform.position + new Vector3(20, 0, 0);
                SpawnChunk();
            }
        }
        else if (pm.moveDir.x < 0 && pm.moveDir.y == 0) //left
        {
            if (!Physics2D.OverlapCircle(player.transform.position + new Vector3(-20, 0, 0), checkerRadius, terrainMask))
            {
                noTerrainPosition = player.transform.position + new Vector3(-20, 0, 0);
                SpawnChunk();
            }
        }
        else if (pm.moveDir.x == 0 && pm.moveDir.y > 0) //up
        {
            if (!Physics2D.OverlapCircle(player.transform.position + new Vector3(0, 20, 0), checkerRadius, terrainMask))
            {
                noTerrainPosition = player.transform.position + new Vector3(0, 20, 0);
                SpawnChunk();
            }
        }
        else if (pm.moveDir.x == 0 && pm.moveDir.y < 0) //down
        {
            if (!Physics2D.OverlapCircle(player.transform.position + new Vector3(0, -20, 0), checkerRadius, terrainMask))
            {
                noTerrainPosition = player.transform.position + new Vector3(0, -20, 0);
                SpawnChunk();
            }
        }
        else if (pm.moveDir.x > 0 && pm.moveDir.y > 0) //right up
        {
            if (!Physics2D.OverlapCircle(player.transform.position + new Vector3(20, 20, 0), checkerRadius, terrainMask))
            {
                noTerrainPosition = player.transform.position + new Vector3(20, 20, 0);
                SpawnChunk();
            }
        }
        else if (pm.moveDir.x > 0 && pm.moveDir.y < 0) //right down
        {
            if (!Physics2D.OverlapCircle(player.transform.position + new Vector3(20, -20, 0), checkerRadius, terrainMask))
            {
                noTerrainPosition = player.transform.position + new Vector3(20, -20, 0);
                SpawnChunk();
            }
        }
        else if (pm.moveDir.x < 0 && pm.moveDir.y > 0) //left up
        {
            if (!Physics2D.OverlapCircle(player.transform.position + new Vector3(-20, 20, 0), checkerRadius, terrainMask))
            {
                noTerrainPosition = player.transform.position + new Vector3(-20, 20, 0);
                SpawnChunk();
            }
        }
        else if (pm.moveDir.x < 0 && pm.moveDir.y < 0) //left down
        {
            if (!Physics2D.OverlapCircle(player.transform.position + new Vector3(-20, -20, 0), checkerRadius, terrainMask))
            {
                noTerrainPosition = player.transform.position + new Vector3(-20, -20, 0);
                SpawnChunk();
            }
        }
    }

    void SpawnChunk()
    {
        int rand = UnityEngine.Random.Range(0, terrainChunks.Count);
        Instantiate(terrainChunks[rand], noTerrainPosition, Quaternion.identity);
    }
}
#

this is the error
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.

honest haven
rocky canyon
#

lol, thats a bit better

honest haven
#

my animator is set up like so

#

So i would have to add another tranisiton. but im not sure if i should stick to this and walk first frame or go straight to run

rocky canyon
#

eitehr ur trying to access a negative number of that list.. or an index thats ABOVE the amount of elements in the list

polar acorn
rocky canyon
#

but like he said ^ if its empty even a 0 will be out of bounds

rocky canyon
#

so.. i set it to Walk speed. and then run an if() check to see if the left shift is pressed if it is i change it to my run speed

honest haven
#

Thank you.

rocky canyon
#

then after all that it uses w/e i chose for that value and just passes it into my Move() function

honest haven
#

many thanks spawn and digiholic

rocky canyon
#

so u can do all ur checks and set up ur variables then at the very end u can use those values

earnest tendon
earnest tendon
#

how do i log them? been a while since ive tried that

rocky canyon
#

well with this collapsed its ur word that theres a Chunk in there

earnest tendon
#

danm cant use gifs

rocky canyon
#
foreach (int item in myList)
{
    // Do something with each item in the list
    Debug.Log(item);
}```
earnest tendon
rocky canyon
#

foreach loop would work to debug all the things in the list

#

or array

polar acorn
#

Just logging the count is fine

earnest tendon
#

its either because im getting tired of looking at unity all day or something else cuz i did not see that colapsed part

rocky canyon
#

lol

polar acorn
#

we don't need to know what is in it, just how much

earnest tendon
#

true

#

i didnt have enough coffee in the afternoon

cerulean quest
#

dude i forgor c# syntax

rocky canyon
#

an extra set of eyes is a common fix for coding..

polar acorn
rocky canyon
#

thats why theres the RubberDuck debugging folklore

earnest tendon
#

yeah that part was empty

rocky canyon
#

just talking it out and looking over things uve already looked over can instantly pop up new information

#

lol

rocky canyon
earnest tendon
#

now it loads a chunk but this happens

cerulean quest
rocky canyon
cerulean quest
#

lemme try for a bit actually

rocky canyon
#

that error tells u exactly how to fix it tho

polar acorn
cerulean quest
#

wait wait i am looking it up

polar acorn
#

There's no way you're running into a syntax error that has never been encountered before

misty hedge
#

I may be stupid, but I'm stumped on getting a boat to rock back and forth.
I thought it'd be pretty simple: Boat.transform.Rotate(0,Mathf.Sin(Time.time),0);, which does, in fact, look very nice - but it only rocks it to the right, of course, because sine goes negative only enough to return it to its original position.
I really am struggling to figure out a simple way to make it rock to the left, too.

earnest tendon
#

oh wait they aint, wtf, i could have sworn i assigned them earlier

rocky canyon
#

computers usually dont tell lies 😉

cerulean quest
#

wait i did write the syntax right

#

why is this error showing up

polar acorn
cerulean quest
#

i am trying to make a struct with 2 vector3 in it

earnest tendon
polar acorn
rocky canyon
cerulean quest
polar acorn
#

What is FirstPoint then?

cerulean quest
#

it cannot be

#

i will add a defualt value then

polar acorn
cerulean quest
#

like east west north south

polar acorn
cerulean quest
rocky canyon
#

Enum

cerulean quest
#

oh yeah enum i havent ever used it

polar acorn
rocky canyon
#
public enum Direction
{
    North,
    South,
    West,
    East
}```
rocky canyon
#

but that would mean changing alot of ur code

polar acorn
# rocky canyon Enum

Even Enums are just ints, it will only produce a runtime error when you try to cast it, it'll happily let you do (Direction) 5 in a case block

earnest tendon
#

KEKLEO progress

rocky canyon
#

ahh true true

cerulean quest
rocky canyon
#

a lot easier to read and work with tho 👍

polar acorn
#

So you'd still need a default case to assign a value to any local variables in the switch

cerulean quest
#

i have only been writing since today

polar acorn
#

But yes definitely use Enums over magic numbers

cerulean quest
misty hedge
polar acorn
rocky canyon
#

you can copy ur rotation value into a variable

#

edit that variable and put it back in

#
   // Get the current rotation
    Quaternion currentRotation = transform.rotation;

    // Modify the X component of the rotation
    Quaternion newRotation = Quaternion.Euler(150f, currentRotation.eulerAngles.y, currentRotation.eulerAngles.z);

    // Apply the modified rotation to the object
    transform.rotation = newRotation;```
#

something like that.. but theres even a shorter way to do it i cant think of rn

polar acorn
rocky canyon
#

aye! lmao thats it ^

queen adder
#

does unity recompile unchanged codes?

rocky canyon
#

coffee is jetlagged

queen adder
#

like redo everything when you reload the editor

polar acorn
queen adder
#

i see

polar acorn
#

At the very least to separate out any included assets from your own code

queen adder
#

i should restudy how to set up assemblies

#

tried it before, just feel too much work setting it up

#

does that package manager automatically separate your installed packages?

cerulean quest
#

how do you get a randomised enum?

polar acorn
queen adder
timber tide
#

that's quite the piece

polar acorn
#
(Direction) Random.Range(1,5)
queen adder
polar acorn
#

(Assuming you've explicitly changed the numbers in your enum to 1,2,3,4 instead of the default 0,1,2,3)

cerulean quest
#

i cant test my code i have to trust the code for now

queen adder
#

        public static T GetRandomFromList<T>(this IList<T> list)
        {
            return list[UnityEngine.Random.Range(0, list.Count)];
        }```this is the other method btw
cerulean quest
timber tide
#

Actually not that bad idea to getvalues then randomize it

#

so in this case it doesnt matter if you label them

#

or what for that matter

polar acorn
queen adder
#

yea, it took 7 peeps and 20 mins to figure out the most efficient way to do this job

polar acorn
#

So (Direction) Random.Range(0,4)

queen adder
#

just so you can lazily do ```cs
Direction.RandomEnum()

cerulean quest
#

thx so much

rocky canyon
# rocky canyon https://gdl.space/femibiquwa.cpp

The standard sine function oscillates between -1 and 1, and if you only use Mathf.Sin(Time.time), it will oscillate between 0 and 1, causing the rotation to only go in one direction.
To make the rotation go in both directions, you need to multiply the sine result by a larger value to increase the range and introduce negative values.

honest haven
#

cheers for your help i changed them to triggers and tidy the code up. Now transitions between all 3 states.

rocky canyon
#

solid animation graph

#

this looks basic and clean

fluid remnant
#
 if (hitInfo.collider.TryGetComponent(out IDamageable dmg))
   {
       dmg.Damage(hitInfo.point); // Null Reference error?
   }

How can this line give Null Reference ?
I am Hitting the if statement, how can it be null?

rocky canyon
#

If the IDamageable component is attached to the game object but is not initialized (set to an actual instance), then calling dmg.Damage(hitInfo.point) would result in a NullReferenceException.

fluid remnant
#

IDamageable is an interface

rocky canyon
#
    if (dmg != null)
    {
        dmg.Damage(hitInfo.point);
    }
    else
    {
        Debug.Log("IDamageable component found but instance is null!");
    }```
#

try that and see if it debugs the log

slate gale
#

I'm trying to use the Video Player component to play videos on an object. I can't seem to figure out how to change the video file at runtime, if possible at all. Anyone any leads?

rocky canyon
#

the inspector should show a slot for the video file..

#

u just grab a reference to that VideoPlayer and set the file

fluid remnant
slate gale
#

Setting it at runtime doesn't seem to actually change it

#

or at least

rocky canyon
slate gale
#

I dragged and dropped another video file into the inspector field at runtime, not via code

#

I'll try via code next

fluid remnant
rocky canyon
#

its VideoPlayerComponent.VideoClip

misty hedge
#

Odd. Even if I do Boat.transform.eulerAngles.Set(100, Boat.transform.eulerAngles.y, Boat.transform.eulerAngles.z);, I see no change to the X component.

rocky canyon
fluid remnant
#

This was my error 😦
var dir = limbInfo.hitPoint- Camera.main.transform.position;

rocky canyon
#

hate when Unity decides to be stupid on me like that lol

fluid remnant
#

My Camera was deleted

teal gulch
rocky canyon
slate gale
#

thx

fluid remnant
rocky canyon
fluid remnant
#

so my enemy

#

their head flies back

rocky canyon
#

but i dont see those functions on it .. so just test it out and see lol

rocky canyon
fluid remnant
#

big knock

slate gale
#

thanks mate

rocky canyon
#

np 👍

misty hedge
#

Doing this:


 // Modify the X component of the rotation
 Quaternion newRotation = Quaternion.Euler(currentRotation.eulerAngles.x, Mathf.Sin(Time.time), currentRotation.eulerAngles.z);

 // Apply the modified rotation to the object
 Boat.transform.rotation = newRotation;```
the boat uh, spins in circles.
#

not ideal!

rocky canyon
#

i sent code that works

#

just put the sinepart on w/e axis u want

#

(x, y, z)

misty hedge
#

Yes that is indeed what I did.

#

Surprised you don't recognize your own code!

#

But yes - putting it on the X component causes strange vertical rocking, the Y component causes it to rotate around the Z axis, and the Z component causes some weirdness.

teal gulch
#

2D game?

misty hedge
#

3D.

rocky canyon
#

i have timeElapsed * rotationSpeed

#

u ahve none of that.. just Time.time like u did last time

teal gulch
misty hedge
rocky canyon
#

https://gdl.space/femibiquwa.cpp <---- CODE again..

  // YOUR CODE
 Quaternion currentRotation = Boat.transform.rotation;

 // Modify the X component of the rotation
 Quaternion newRotation = Quaternion.Euler(currentRotation.eulerAngles.x, Mathf.Sin(Time.time), currentRotation.eulerAngles.z);

 // Apply the modified rotation to the object
 Boat.transform.rotation = newRotation;``` is not my code..

it doesn't 
- set a start time
- doesn't update the elapsed time
- doesn't use either of those in the rotation modification
- doesn't construct the angle variable with a Speed Modifier
teal gulch
#

works for me

#

nvm

teal gulch
rocky canyon
#

im a Var junkie..

#

i just prototype code for the most part.

#

i'll delete this before days over

rocky canyon
teal gulch
#

yeah, it should be around y axis, not z

misty hedge
#

it is

rocky canyon
#

thats rotating on teh Z axis btw

misty hedge
rocky canyon
#

got to use local Rotation

#

b/c ur boat is all flipped upside down n shit

#

if it matched the world coords it would work

#

transform.localRotation

misty hedge
#

Flipped upside down?

#

It's in the same position it started the scene in

rocky canyon
#

u see this?

#

thats correct.. thats the way the world faces

#

spot the difference?

misty hedge
#

wtf

#

why is it like that 😭

rocky canyon
#

the way the modeller exported it.

misty hedge
#

The modeller is me

rocky canyon
#

u can use a parent container and orientate it correctly

#

and just use the ship as a child of it (rotated to match the way it should face)

#

and put the code on the parent instead

misty hedge
#

That is so scuffed but alright

#

It still doesn't work 🙂

rocky canyon
misty hedge
#

oh never mind. We got it

dark oak
#

good evening, guys Can i ask a question?

misty hedge
#

That is a really stupid solution and I don't like it but I'll keep it in mind

teal gulch
rocky canyon
#

PENDULUM

misty hedge
#

pendulum...

rocky canyon
#

i might keep this script around

#

im sure i can use it for something

dark oak
# teal gulch sure

i just installed unity 2019.4 and it is not opening on windows 7 What should i do?

rocky canyon
#

first off restart your PC and try it again

misty hedge
#

Oh, and since this always trips me up: how can I make this rotation work frame-independently?

rocky canyon
#

it'll save u alot of heartache if it boots up

#

you can use time.DeltaTime

#

multiply it with the rotationSpeed multiplier

teal gulch
#

do it in fixedupdate

misty hedge
#

Already is

#

but being in FixedUpdate doesn't always garuntee frame-independence

rocky canyon
#

if its running in fixedupdate then its already frame independent

#

yea it does

#

fixedupdate runs at a fixed rate

#

doesnt change at all

#

doesnt matter if ur running 5fps or 340fps

#

fixed timestep.. is a constant

misty hedge
#

🫡

rocky canyon
#

stock settings are 50 frames/second

#

on the physics (FixedUpdate)

#

lower the number the faster the calculations

sacred egret
rocky canyon
#

do you have "e" set up as an input?

timber tide
#

update doesnr run when it's inactive

rocky canyon
#

but he's activating some other object i believe

#

NailBehiviour should be active

#

for the code to work

timber tide
#

ah, right, so question would be is if the log is printing