#💻┃code-beginner

1 messages · Page 139 of 1

buoyant knot
#

but I would like to restrict visibility while retaining architecture

#

well, it was worth asking

ionic zephyr
ionic zephyr
#

It has NullReferenceError while setting the Vector

slender nymph
#

why is your charactermovement a singleton?

ionic zephyr
#

so I can use it as a static variable

slender nymph
buoyant knot
#

that doesn't need to be a singleton

polar acorn
slender nymph
#

static and singletons should not just be thrown around all willynilly just because you don't want to get a reference the right way

ionic zephyr
#

but if I don´t make the CharacterMovement component static then I cant use the PlanarVelocity vector

ionic zephyr
#

look

slender nymph
ionic zephyr
slender nymph
#

it's like you don't even listen to anything anyone tells you

ionic zephyr
summer stump
polar acorn
#

And use the value you want in the actual function

rocky canyon
#

you have to run in a Initialization method of some type i believe

summer stump
# ionic zephyr

To be clear, you are trying to use _characterMovement before start runs. Thus, it is null. And you can't do it that way anyways

ionic zephyr
#

Oh, now it seems so obvious

rocky canyon
#
    private CharacterMovement _characterMovement;
    private Vector3 _bulletVector;

    private void Start()
    {
        // Assuming you have a reference to the CharacterMovement script
        _characterMovement = GetComponent<CharacterMovement>();

        // now that you have a reference to your CharacterMovement class you can set the Vector
        _bulletVector = _characterMovement.PlanarVelocity;
    }```
#

you would need to assign the reference to the class first..

#

beit thru the inspector with an exposed variable..

#

or grabbing it at runtime in a script or something

ionic zephyr
#

yes okay,

#

thanks a lot you all

rocky canyon
#

but ya, unless your using the vector over and over.. (getting rid of it is a good tip)

#

you can just use _characterMovement.PlanarVelocity; whenever u wanna use that value

#

otherwise (not knowing ur use-case) you may have to access that everytime you need to use the vector to make sure its updated to the correct value..

slender nymph
#

or could have just added a funky little > to that assignment operator and turned it into a readonly property to fix the issue

rocky canyon
#

is it bad practice to use public variables and NaughtyAttributes [ReadOnly] attribute?

#

i have it public as to be able to modify it from external classes..

#

but it only ever gets read anywhere else.. and also keeps me from changing inspector values by accident

ionic zephyr
rocky canyon
#

if u have a reference to it.. not really..

#

ur just reading.. but its just an extra variable u dont need.. and to keep up with

#

but if it helps you read and understand the script better, leave it

polar acorn
rocky canyon
#

^ math-person knows whats up

ionic zephyr
#

And what if I do that search in Update?

rocky canyon
#

gross

ionic zephyr
#

because the vector is constantly changing

rocky canyon
#

if its constantly changing you'd want to access it anytime u need it

#

if it only needs read when u run a certain function why not read it then

slender nymph
rocky canyon
#

instead of having it update every frame.

#

its just depending.

rocky canyon
#

"if it aint broke, dont fix it" or something like that

ionic zephyr
rocky canyon
#

yea, only update it when you need to use it..

#

if you need it every frame.. then do it

slender nymph
rocky canyon
#

its like a health bar for example.. you can update that every single frame.. but why? you only need to update it when it changes..

#

so isntead of doing in update.. u would do it instead inside an Attack() function...

#

it would be called only if you took damage or got a powerup or something

ionic zephyr
#

Okay, thanks a lot again

slender nymph
rocky canyon
#

ya, i was trying to think of alternatives but im not that great at properties. and getter setter type stuff

slender nymph
#

just

[SerializeFieldOrReadonlyHere] private int _myField;
public int MyField => _myField;

is enough for now unless you want other objects to assign to it, then just use a full property or even an autoproperty where you target the backing field with the desired attribute(s)

summer stump
slender nymph
#

and just do what spawncamp suggested and directly use _characterMovement.PlayerVelocity in place of _bulletVelocity in your Instantiate call. then you don't need to do anything crazy like constantly update your _bulletVelocity variable because you can just access the current value when you need to

little oak
#

how can i instantiate an gameobject with a certain vertical velocity?

#

like, instantiate it and give it a velocity

slender nymph
#

instantiate it, then assign its velocity

queen adder
#

what is the correct way to code it so my player wont be able to move their camera or player anymore

little oak
#

i tried that

summer stump
slender nymph
little oak
summer stump
little oak
#

wait

#

lemme show u the whole thing

#

lol

queen adder
#

i initally wanted to do an entiiire if statement on my movemenscript that checks if the player is unable to move or not but i feel like thats not very optimal

slender nymph
# little oak

you're not assigning the velocity of the instantiated object. remember that Instantiate returns the reference

little oak
#

ohhhhhhhhhhhh

slender nymph
#

also pass a Rigidbody2D as the first parameter of Instantiate, not a GameObject

little oak
#

i thought it expects a game object? how else would it creae it

summer stump
fluid remnant
#

How do I assign shape to Particle System in code?

little oak
#

alr

#

still doesnt work

slender nymph
#

you're still not modifying the instantiated object

#

again, Instantiate returns the new object

little oak
#

but im assigning the new velocity

little oak
slender nymph
#

no, it takes in the prefab as the first parameter and returns the instantiated object

little oak
#

yes

summer stump
#

instance = Instantiate
instance.velocity =

You do NOT set the velocity of match

fluid remnant
polar acorn
little oak
#

oh so it doesnt work bc it returns the prefab instead

#

i mean

#

the instantiated modified one

gritty notch
#

anyone know what i can call do see which button was pressed when using ipointerdownhandler, idraghandler and stuff?

summer stump
fluid remnant
slender nymph
#

correct.

Particle System modules do not need to be reassigned back to the system; they are interfaces and not independent objects.

little oak
slender nymph
little oak
#

mb

summer stump
slender nymph
#

modify the velocity of the instantiated object. because Instantiate returns a reference to that object

little oak
#

lemme test that

slender nymph
#

it will work

summer stump
#

*if done correctly

little oak
#

didnt work

#

ye

#

it looks good tho

#

i changed the velocity

#

after i instantiated it

slender nymph
#

and what is the value of meet.velocity

little oak
#

its the value of another gameobject

#

the velocity of another gameobject

summer stump
#

No. Specifically what is the value

little oak
#

it changes

slender nymph
#

you do know words have meaning right? i am asking what the current value of that property is

polar acorn
# little oak

This will set the velocity of your new object to whatever the current velocity of meet is

summer stump
#

Debug.Log if not sure

little oak
#

when the scene starts its 0

#

but itd change no?

#

if the game object that meet is set to is falling

summer stump
little oak
#

alr

#

it does

summer stump
# little oak

And where did you log this value? On the shoot method?

polar acorn
#

Okay now also log instance.velocity after setting it

little oak
#

returns meet.velocity

queen adder
#

im a fucking GENIUS

#

IM A FUCKING

#

GENIUS!!!!

little oak
#

fr

summer stump
queen adder
#

i basically took the input values for movement and camera movement and i multiplied them with the boolean of the player being alive

little oak
polar acorn
# little oak

After setting velocity add this line:

Debug.Log($"Velocity of instance: {instance.velocity}, velocity of meet: {meet.velocity}");

and then show it

little oak
#

wait c# has formatted strings???

summer stump
#

Of course

slender nymph
#

yes, have you not gone through any proper structured course for learning c#? pretty much all of the good ones teach how to use string interpolation

little oak
#

bruh i thought that was just a python thing

#

lol

summer stump
#

There is very little (if anything?) that python has that others don't

little oak
#

☠️

scarlet shuttle
#

im trying to makes boids, what would be a good way to group them so they only get boids in the same group as them?

little oak
polar acorn
little oak
slender nymph
# little oak

well would you look at that, id does set its velocity correctly. so if it isn't behaving as you expect, then you need to make sure that nothing else is affecting it (like colliding with something or its own code affecting its velocity)

little oak
#

when i set the velocity, will it stay at that velocity or will it accelerate

#

bc its a rigidbody

polar acorn
little oak
#

i see

polar acorn
#

be they gravity, collisions, or code

little oak
#

maybe i should approach what i want differently then

#

i dont think making the velocities the same will work

summer stump
slender nymph
#

or you could explain what it isn't doing that you are expecting it to do and we can look into reasons why it isn't doing that

little oak
#

dynamic

slender nymph
polar acorn
summer stump
slender nymph
#

yes

summer stump
#

Huh. Alright. Thanks!

summer stump
little oak
#

im trying to instantiate an arrow inside a bird which can jump, but when i instantiate it, the arrow moves away from the bird (they dont collide)

slender nymph
slender nymph
little oak
#

yes i made them excluded

#

wait let me explain it better

summer stump
little oak
#

i made the arrow and bird stay together by making it so that any key that moves the bird moves the arrow in the same exact way

but if i instantiate the arrow while the bird is jumping, the arrow will be off position

#

WAIT

#

i just tested it

#

it works

#

wait why it didnt work before

#

weird

slender nymph
#

why does the arrow have a dynamic rigidbody if you want it to move with the other object? why not just remove its rb and make it a child of that object?

desert elm
#

hm, is there some kind of major issue with this? it appears that the distance isn't measured

little oak
#

with the parent

slender nymph
#

yes, children objects move when their parent objects do. with the exception of dynamic objects like rigidbodies which move independently (though may be influenced a bit by a parent object's movement)

little oak
#

i tried it before, making the arrow the child, ig it didnt work bc it was a dynamic rigidbody

#

im not sure how the types of rigidbodies work

#

lol

#

ill try that then

polar acorn
lofty sequoia
#

wouldn't the distance between t.position and hit.point be 0?

#

hit2's raycast would be a ray of length 0 basically because hit.point is where t.position is

little oak
#

what else type of body would it be lol

#

wait

#

let me find out what the different types of rigidbodies are

#

and ill be bacl

desert elm
little oak
#

so a kinematic rigidbody isnt affecred by gravity

#

i just tried it and the arrow began to fly up once i instantiated it

lofty sequoia
desert elm
polar acorn
lofty sequoia
#

it might not reach the else statement if it tries to peel into the hit object only to find that it is null

desert elm
#

oh, huh

rocky canyon
#

if I wanna instantiate an object on the ground (raycast from cam to game)
1️⃣ OnGroundClick(ray.GetPoint(hit.distance));
2️⃣ OnGroundClick(hit.point);

#

:TIL: about GetPoint

polar acorn
desert elm
eternal needle
rocky canyon
#

lol same!

#

trying to think of a purpose

#

other than using it just like hit.point

polar acorn
rocky canyon
#
            else
            {
                // Raycast either hit nothing
                // Raycast hit something not in our layermask

                if(hit.collider == null)
                {
                    // Ray didn't hit anything
                    Debug.Log("Raycast Missed: Hit nothing");
                }
                else
                {
                    // Ray hit something, but it's not in the clickable layer
                    Debug.Log($"Raycast Hit something outside Clickable Layer: {hit.collider.gameObject.name}");
                    Debug.Log("Please add the object to the Clickable Layer");
                }
            }```
#

hehe, im also having a raycast fiasco

polar acorn
rocky canyon
#

well a position is not a direction

#

so probably yea

polar acorn
rocky canyon
#

hey, get out of my head

polar acorn
#

So that would probably mean your raycast is kind of fucking off into space

desert elm
polar acorn
rocky canyon
#

you can use a point in space and math it with another point to get a direction

#

but a singular position isn't worth anything to a raycast

eternal needle
desert elm
# polar acorn why

made sense to me to think that you would have a origin and direction point- right what am I supposed to do if I want to raycast towards a point

rocky canyon
#

better than having to introduce a pointless offset variable

polar acorn
#

Origin point and direction

#

straight from the documentation

#

"Hey buddy what's your address?"
"Left."

desert elm
#

yeah I read that
and assumed that "a vector representing the direction of the ray" meant that it would be a Vector2 or 3 that showed where to go
ah well, great

#

thats the bug

#

ill go and fix it tomorow

polar acorn
desert elm
#

I am aware

rocky canyon
#
Vector2 startPosition = new Vector2(0f, 0f);
Vector2 endPosition = new Vector2(1f, 2f);

Vector2 direction = endPosition - startPosition;
Vector2 normalizedDirection = direction.normalized;
#

two positions make a direction 👍

rocky canyon
desert elm
rocky canyon
#

yup that would give u a direction

#

may need to experiment with the order of subtraction..

#

may give u a direction opposite of the way u want.. but u can just negate that direction = -direction; to make it flip around the other way

#

pretty sure its where your going - where you are that gives u the right direction

desert elm
#

is there a way to visualise raycasts

#

for easier debugging

rocky canyon
#

yessir

desert elm
#

great

rocky canyon
#
   // Visualize the ray using Debug.DrawRay
   Debug.DrawRay(ray.origin, ray.direction * hit.distance, Color.red);
desert elm
#

thanks

desert elm
rocky canyon
#

or u can use OnDrawGizmo's or OnDrawGizmosSelected

    {
        // Create a ray from the object's position
        Ray ray = new Ray(transform.position, transform.forward);

        // Set the Gizmos color
        Gizmos.color = Color.blue;

        // Visualize the ray using OnDrawGizmos
        Gizmos.DrawRay(ray);
     }```
polar acorn
desert elm
#

okay

buoyant prawn
#

!ide

eternal falconBOT
bronze estuary
#

Can anyone tell me why this piece of code gives my 2D player no x velocity?

#
        {
            float tempx = moveInput * (walkSpeed+1);
            float tempy = jumpValue * 100f;
            rb.velocity = new Vector2(tempx, tempy);
            jumpValue = .033f;
            Debug.Log("jump " + tempx);
        }```
#

whereas this does have x velocity

        {
            float tempx = moveInput * (walkSpeed+1);
            float tempy = jumpValue * 100f;
            rb.velocity = new Vector2(tempx, tempy);
            jumpValue = .033f;
            Debug.Log("prejump " + tempx);
        }```
teal viper
rocky canyon
# desert elm okay

like here, if u have a (1,0) the length from the origin to that point is 1,
if you have a (0,1) the length of the vector is also just 1
but if u were to compound these you'd get the orange dot in the top right..
its (1,1) naturally.. but if u draw a line from the origin to That point you'll see its Longer than (1)

#

if u normalize it you get this instead.. the vector becomes 1

#

the same as it did on the other two.. this is used for example in a movement script.. that way when ur giving two inputs (forward and left) for example... you don't run faster

#

than u would if u were to just go one direction or the other

north kiln
bronze estuary
teal viper
bronze estuary
teal viper
#

Well, in that case you'd need to debug.

#

One of the multipliers is 0

#

Debug the values that go into tempx.

rocky canyon
#

you can click the kabob menu in the top right and set it to Debug... it will show all ur variables in the inspector.. including the private ones.. can keep an eye on ur values easily that way..

bronze estuary
rocky canyon
#

or u can use ur standard Debug.Log and log the values u need to watch

bronze estuary
teal viper
bronze estuary
#

Here's the updated code.

        {
            Debug.Log("jump " + moveInput);
            Debug.Log("jump " + walkSpeed);
            float tempx = moveInput * (walkSpeed+1);
            float tempy = jumpValue * 100f;
            rb.velocity = new Vector2(tempx, tempy);
            jumpValue = .033f;
        }```
#

it returns 1 and 5 when moving to the right

rocky canyon
#

and should be -1 and -5 when moving left

teal viper
#

You should probably provide better description in your logs too. As it's now you're gonna confuse the 2 logs.

bronze estuary
teal viper
bronze estuary
rocky canyon
#
Debug.Log($"WalkSpeed: {walkSpeed}");

you can use string interpolation as well that way u dont have to do the " + " bull crap

teal viper
#

Debug the tempx as well.
Ideally all 3 in the same log. You want to see what values they have when the issue occurs.

teal viper
bronze estuary
teal viper
#

That's why you should log all 3 at once.

bronze estuary
#

The issue is that Im unable to jump to the right and left when holding down a directional input

#

it only jumps directly upwards despite having a non zero x velocity

rocky canyon
#
   // Debug using string interpolation
   Debug.Log($"Jump: MoveInput = {moveInput}, WalkSpeed = {walkSpeed}, TempX = {tempx}, TempY = {tempy}");``` Freebie
teal viper
#

If a * b = c, and you see that c is wrong, it is probably because a or b is wrong, so you dig deeper to where they go wrong and so on.

bronze estuary
#

Im aware of debugging. Im asking for help because rb.velocity.x is a non-zero number (I've debugged it multiple times) but Im not getting any x velocity. However, here is the full debug log.
Jump: MoveInput = 1, WalkSpeed = 5, TempX = 6, TempY = 9.000152

teal viper
#

Well, tempx is not 0

#

So this is not the case you want to look at..?

#

Unless the issue occurs at this case as well

bronze estuary
#

Yes, tempX is 6, and im feeding tempx directly into rb.velocity, but rb.velocity is not giving my player character any x velocity

#

so the game is treating tempx as 0 despite it not being 0

teal viper
#

Okay, so the whole debugging was sort of pointless..?

#

You want to debug rb.velocity as well

#

*not entirely pointless. It provides a clue that the issue might be somewhere else.

#

Debug the velocity. Does it actually equal to tempx after setting it?

bronze estuary
#

Debug.Log(rb.velocity.x); returns 6

teal viper
#

Great. Should have started with this though.
Now there are a few possibly causes. One likely is that you're overriding the velocity somewhere else. Try commenting out every other place you access rb.velocity.

bronze estuary
#

I see the problem, thank you.

        {
            jumpValue += 0.1f * Time.deltaTime;
            rb.velocity = new Vector2(0f, rb.velocity.y);
        }

        if(jumpValue >= .09f && isGrounded)
        {
            float tempx = moveInput * (walkSpeed+1);
            float tempy = jumpValue * 100f;
            rb.velocity = new Vector2(tempx, tempy);
            jumpValue = .033f;
        }```
bronze estuary
#

If I want my 2D player character to bounce off a wall is this a suitable way of doing so

    {
        if(!isGrounded)
        {
            rb.velocity = new Vector2(-rb.velocity.x, rb.velocity.y);
        }
    }```
teal viper
bronze estuary
teal viper
#

I think Collision2D(or the contacts) has a collisionVelocity property. You can use that and dot product to determine how "horizontal" the direction is.

bronze estuary
teal viper
ionic zephyr
sturdy wren
#

why can't i make an array of objects containing a script?

north kiln
#

Component is not plural

#

Use the plural version of the method

sturdy wren
#

what's that?

north kiln
#

Components

sturdy wren
#

oh

queen adder
#

how should i code the camera lerping to zoom out while looking at the player?

#

this is how i do it
(in the update function, there is a if statement that when true, runs this function)

#

however sometimes it doesnt even look at the player

#

my full code is herehttps://gdl.space/solaniqofe.cpp

north kiln
#

A position is not a direction, it makes no sense to pass it to LookRotation

queen adder
#

oh

teal viper
north kiln
#

(also, obligatory: use Cinemachine)

ionic zephyr
#

not the prefab in th asset folder but yes the one in the scene

queen adder
#

WAIT A MINUTE

#

is a direction euler angle coordinates?

teal viper
timber tide
#

direction is a direction vector

ionic zephyr
#

the component existi in the prefab

teal viper
#

Okay, now the next question is why are you not setting the direction on the new instance of a bullet?

north kiln
queen adder
#

oh whoops

#

_<

queen adder
#

i changed my equation to this and now my death camera works!

#

thank you guys : )

teal viper
ionic zephyr
#

The thing is that in the prefab I introduce in the Serialized GameObject it works

#

but not in the Instanced bullets

teal viper
ionic zephyr
#

You mean in the Inspector?

teal viper
#

Yes. Whatever you have referenced in the inspector is not related to the newly instantiated bullets in any way, so there's no point in setting a direction for it. Instead you need to set the direction for the instantiated bullets

ionic zephyr
#

but it is

#

look

#

the present ball moves, which is the one in the inspector

#

the instanced ones dont move AT ALL

teal viper
#

Yes. That's exactly what I'm saying.

queen adder
#

(for context, controls are weird and buggy and the prompt keeps glitching)

little oak
#

when instantiating a prefab, how can i access a child object of it?

#

like you see this

#

the instantiate thing

#

how can i change the positions of child objects in a parent when instantiating

gusty hazel
#

how would i go about setting the direction that my enemies are facing so i can makew their attacks

#

in a top down game

smoky niche
#

What would be the best way to pause the game? I've heard Time.timescale = 0 is not the best solution, although I've never really had trouble with it. Outside of that, what would be the best way to pause a game?

teal viper
teal viper
teal viper
swift crag
#

The good news is that most things should already handle pausing correctly

swift crag
#

Anything that takes place over time will be using deltaTime already

#

save for a few things like mouse input

little oak
#

so its not possible to use instantiate alone? id have to modify the prefab prior?

swift crag
#

which you'll just want to ignore

swift crag
#

how would you access the child object before instantiating?

#

you can't refer to child objects from a prefab

#

you should put a component on the root of the prefab that references the child objects you need

#

and then just grab the references from the component after instantiation

teal viper
#

Read the docs Return section what does it say exactly?

smoky niche
#

I know that everything that uses deltatime gets paused, as well as coroutines which use the WaitForSeconds.

nimble apex
#

i lost my confidence now lol

#

u dont really need a coroutine if u dont have to wait and return anything right?

#

thats just what normal void function does

teal viper
#

Yes... A coroutine is for running something asynchronously.

nimble apex
#

ohhhh

#

i see

#

i think of a possibility

#

because these codes are 6 yrs accumulation of my team, im trying to figure it out

swift crag
#

A coroutine lets you run a method that can pause itself and get resumed later

#

That's the gist.

#

note that it doesn't run in parallel. It's the same single-threaded code as always.

little oak
#

so u cant

nimble apex
teal viper
swift crag
# little oak so u cant

of course you can change the position of the instantiate object's children!

public class MyComponent : MonoBehaviour {
  public Transform someChild;
}

...

void Foo() {
  MyComponent clone = Instantiate(original);
  clone.someChild.position = Vector3.zero;
}
#

You could also mess with the position of someChild in the prefab, I guess

little oak
#

oh

nimble apex
#

thats the only reason i can think of

little oak
#

i didnt know u could access the child lol

#

thank u

swift crag
teal viper
#

You can access them with transform.children at the very least.

teal viper
nimble apex
#

so my team lead gave me an answer, simply for heavy event based functions, or functions that contains huge tasks, like instantiate+setup a gameobject , we will use coroutines to simulate multithreading

teal viper
#

That's... Not really how it works... It still runs on the main thread...

#

Though, I guess if the setup is heavy you could break it down to several frames. Hard to say anything without seeing the implementation.

nimble apex
#

because they believe that ,

startcoroutine(funcA())
funcB()

yes, they think after funcA is called, funcB will also call while funcA is doing its job

teal viper
#

funcB would be called when funcA gets to it's first yield return.

nimble apex
#

ok

#

i will try to share one of the implementation

#

wait

swift crag
#

it's not while funcA is doing its job. it's after funcA gets to a yield return and decides it's done running for now

#

Unity will resume the enumerator returned by funcA sometime later

nimble apex
#

ikr, but when i saw the coroutines, they behave like normal void function

#

hold on

teal viper
#

And IEnumerator is just a function that returns an IEnumerator with some additional logic involved.

nimble apex
#

as u see, theres no yield return at all

swift crag
#

this accomplishes nothing

swift crag
#

yield break was added at the end because the compiler demands you have at least one yield statement somewhere

teal viper
#

This coroutine would complete entirely before UpdateDimMask is called.

nimble apex
#

this is just a "wannabe" multithread

teal viper
#

It's not gonna make it multithreaded or async just because you treat it as a coroutine. It actually needs to yield return for it to work async.

nimble apex
#

ikr, the coroutine will do all the stuff before doing other things

#

that yield break looks sus to me at first glance already

teal viper
#

Tell your team lead to go back over the basics😛

nimble apex
#

lol

swift crag
#

although its presence is certainly weird

#

so, true, it is sus at first glance!

swift crag
#

multithreaded, running-at-the-same-time, etc.

nimble apex
#

lemem tell u, all the functions that includes setup + instantitate are all using this kind of approach

swift crag
#

no, they're really really basic! they're just enumerators!

nimble apex
#

they are everywhere

swift crag
#

also this doesn't even look that expensive lol

nimble apex
#

20 +

swift crag
#

i guess it could be slow if it needs to fetch that thing from disk

nimble apex
#

just a single manager contains 20 + of these kinds of functions

nimble apex
#

the data is fetched from server at very first, this function is utilizing it only

teal viper
#

I don't know the whole context, but it's fine for the team lead to not know details of implementation sometimes(unless they wrote that code). It is their responsibility to not make assumption and confirm with the docs before giving explanations though. If that code was delegated to someone else to be written, it should be handed back to them for rewriting.

nimble apex
#

as i said, these codes are accumulation of 6 yrs, so most staffs that wrote these are left

teal viper
#

I see

nimble apex
#

theres no way to seek them out lol

#

95% of the code is finished i would say

teal viper
#

Send them an email with threats. Stalk them to their doorstep. Make calls and breath heavily.

nimble apex
#

this team is on final stage, like optimizing stuff before production

#

yes, optimizing lol

swift crag
#

i mean, it certainly won't hurt the game

#

it'll be marginally worse than just not doing a coroutine at all

teal viper
#

It probably just adds some overhead in this case.

nimble apex
boreal tangle
#

does someone know if i have two box colliders on a sprite, how do I specify the collider I want GetComponet to get?

summer stump
boreal tangle
#

ok ty

summer stump
# boreal tangle ok ty

You could get all of them and check the size or some property I guess. But that seems like a brittle way to do it

boreal tangle
#

yeah, il just add them as children

nimble apex
#
  private void GenerateSocketErrorDialog(DialogType type, string msg, Action OkAction, string[] args = null, bool isWaitChangeScene = false, string errorCode = null)
  {
    var prefab = Resources.Load(dialogPath + type.ToString());
    GameObject dialog = GameObjectInstantiate(prefab as GameObject);
    CommonDialog msgDialog = GetComponent<CommonDialog>();
    //Reset flag
    RoomManager.Instance.onclickingGameJoin = false;

    //login error and normal error
    msgDialog.SetDialog(msg, OkAction, null, DialogMessageType.Default, args, isWaitChangeScene, null, errorCode);
    msgDialog.Truncate();

    AddDialog(dialog);
  }
#

this is the one i modified

dense root
#
public Image oldImage;
public Sprite hiraganaChart;

void Update()
{
    // Detect if the ` key is pressed
    if (Input.GetKey(KeyCode.BackQuote))
    {
        Debug.Log("Backquote key pressed");

        changeImage();
    }
}

public void changeImage()
{
    oldImage.sprite = hiraganaChart;
}

How do I un change image on the "upstroke" of the keyboard? i.e. back quote is pressed, changes image, then unpressed and the image reverts

frozen stream
#

I have to make this cannon shooting at meteors game but i don’t know how to make a bullet come out the cannon

#

It’s a 2d project

runic prawn
timber tide
#
void FixedUpdate()
{
    Vector3 angles = GetAnglesFromCurve();
    Quaternion rotation = Quaternion.Euler(angles.x, angles.y, angles.z);
    Quaternion lookRotation = Quaternion.LookRotation(rotation * Vector3.forward, Vector3.up);
            
    transform.rotation = initialRotation * lookRotation;
    Vector3 posChange = currentSpeed * Time.fixedDeltaTime * transform.forward;
    transform.position += posChange;
}```
rotations make my brain melty, but can anyone tell me why LookRotation works here such that the angle of rotation stays consistent such that my initial rotation wouldn't affect how this object travels
#

like, why isn't initialRotation * rotation enough to satisfy the initial rotation relativity. Even something like rotation * initialForwardDirection

runic prawn
#

Or you could do something with checking if an input method is false/use an else statement.

dense root
#

How do I reorganize the image layers? I want the on in the back to be up front I tried setting the layers but no dice

frosty hound
#

Order in the hierarchy

north kiln
dense root
runic prawn
#

the component overrides the renderer settings, incase you were curious

dense root
runic prawn
#

That's a UI element, so you have to add the sorting group component.

dense root
#

Set the Inputfield and image to in sorting and 0 for the hiragana chart

runic prawn
#

hmm. I hade this issue with another project of mine. Let me open it up and see if I recall what I had to do

eternal falconBOT
weary summit
#

I just found out about navmeshes and what a miracle this is. Whoever wants to make an enemy AI for example, nav meshes makes it so much easier

#

I was actually suffering until I found out nav mesh

vernal minnow
#

Im currently working on a really basic game and plan to set up the powerups tomorrow, would it make sense to have the player pick them up by detecting a collision of a tagged object(the powerup) which could then set a variable that resets itself after a set time?

#

i havent tried to make powerups before and am hoping that they arent to complicated 😅

runic prawn
#

Does anyone know why I have to use the default constructor in this script? If i use

private void Awake()
{
  bitBoard = new ulong[12];
  prefab = new GameObject[12];
}
private void Start()
{
bitBoard[(int)PlayerPiece.wPawn]    = 0x000000000000FF00;
  ...

or:

private void Start()
  bitBoard = new ulong[12];
  prefab = new GameObject[12];

  bitBoard[(int)PlayerPiece.wPawn]    = 0x000000000000FF00;
  ...

It doesn't work. Only this works and I don't know why:

public class GameManager : MonoBehaviour
{
    public GameObject[] prefab;
    public ulong[] bitBoard;

    private GameManager() // has to be GameManager()?
    {
        bitBoard = new ulong[12];
        prefab = new GameObject[12];
    }

    private void Awake() // Start() also works here
    {
        bitBoard[(int)PlayerPiece.wPawn]    = 0x000000000000FF00;
        bitBoard[(int)PlayerPiece.wKnight]  = 0x0000000000000042;
        bitBoard[(int)PlayerPiece.wBishop]  = 0x0000000000000024;
        bitBoard[(int)PlayerPiece.wRook]    = 0x0000000000000081;
        bitBoard[(int)PlayerPiece.wQueen]   = 0x0000000000000008;
        bitBoard[(int)PlayerPiece.wKing]    = 0x0000000000000010;

        bitBoard[(int)PlayerPiece.bPawn]    = 0x00FF000000000000;
        bitBoard[(int)PlayerPiece.bKnight]  = 0x4200000000000000;
        bitBoard[(int)PlayerPiece.bBishop]  = 0x2400000000000000;
        bitBoard[(int)PlayerPiece.bRook]    = 0x8100000000000000;
        bitBoard[(int)PlayerPiece.bQueen]   = 0x0800000000000000;
        bitBoard[(int)PlayerPiece.bKing]    = 0x1000000000000000;

        for (int i = 0; i < 12; i++)
        {
            InstantiatePeices(bitBoard[i], i);
        }
    }

    private void InstantiatePeices(ulong value, int pieceIndex)
    {
        BitArray squares = new BitArray(BitConverter.GetBytes(value));

        for (int row = 0; row < 8; row++)
        {
            for (int col = 0; col < 8; col++) {

                if (squares[col + row * 8])
                {
                    Instantiate(
                        prefab[pieceIndex],
                        new Vector3(col, row, 0f),
                        Quaternion.identity );
                }
            }
        }
    }
}

I read online that Awake() and Start() are preferred over default constructors for MonoBehaviours, but there are apparently some exceptions. Is this one of them, or am I just doing something wrong?

teal viper
#

And yeah, you shouldn't be using constructors with MonoBehaviour.

slender nymph
#

keep in mind that public variables will be serialized so after the constructor runs unity applies the serialized arrays, which are probably empty if you haven't assigned anything in the inspector

teal viper
#

The problem is probably you overriding the prefabs array with nulls.

#

In awake or start. When you move it to the constructor, it's probably not executed, so it doesn't cause the problem.

frozen stream
#

I’ve been unable to make a character move around and jump about in my 3D game

#

It’s been frustrating, the character can move but just can’t jump

slender nymph
#

show !code

eternal falconBOT
sweet zenith
frozen stream
errant fern
#

Someone please?

slender nymph
#

this is a code channel

errant fern
#

I'm not too sure if it will be possible to do with just joints, so that's why I ask here, to find another way.

frozen stream
#

Hold on while i show you the script too

sweet zenith
#

what on earth

frozen stream
#

Can’t screenshot

sweet zenith
#

why not?

frozen stream
#

Laptops been bugging for a week

sweet zenith
#

that's a very strange bug

slender nymph
frozen stream
#

Everything’s been freezing

#

No i tried i literally can’t screenshot

#

i’m sending my laptop for repair soon

frozen stream
slender nymph
#

and you still haven't bothered even sharing the code despite having been asked to like 45 minutes ago

frozen stream
#

? my laptop has been freezing and refreshing, ive been trying

#

i already mentioned it being slow and freezy, ive been trying to open the unity code

frozen stream
#

just copy and paste?

slender nymph
#

with the link you just posted then deleted.

#

and don't multiply your velocity by deltaTime

frozen stream
#

okay

frozen stream
#

so spare me not understanding some stuff

slender nymph
#

and if the object is still not moving then you need to make sure your animations are not controlling the position of the object otherwise they will override the position

frozen stream
#

currently, the character moves just fine, left and right, front and back, sprints and walks but I just don't know how to do the jumping part

#

thats the main issue w my character

slender nymph
#

ah so you aren't having trouble with existing code. you just don't know how to implement a jump

#

plenty of resources online about how to check for ground and apply an upward force or velocity to a rigidbody

frozen stream
#

and the tuts ive watched on yt

slender nymph
#

let me guess, they haven't worked?

frozen stream
#

nope

slender nymph
#

and that's probably because you are overwriting velocity every FixedUpdate

frozen stream
#

they just show a capsule as the character and never shows how to do it with a real imported character w animations

slender nymph
frozen stream
frozen stream
slender nymph
#

so? jumping has nothing to do with animating. you can pass parameters to your animator however you'd like. that doesn't mean your animator has anything to do with how you are actually implementing the jump in physics

frozen stream
#

right right

#

ill handle that later as i have another submission that I gotta give by midnight which is 12 hours from now but its much simpler

#

its a 2d cannon game where the cannon is fixed at the bottom and can turn left and right to shoot bullets, there are meteors fallling down at a random range which will get destroyed if the bullets hit them

#

and theres like an interval to which the bullets are fired

#

thats all there is thats required

#

issues ive been facing are not knowing how to implement bullets being fired from this 2d sprite cube

nimble scaffold
#

I cannot find the tools window in unity urp

slender nymph
nimble scaffold
slender nymph
slender nymph
nimble scaffold
slender nymph
#

do you mean the Tools dropdown menu in the toolbar? that only appears if you have some asset or code that adds something to that menu

nimble scaffold
#

Like here

slender nymph
#

first of all, that screenshot is so small that the text is literally not legible.
and second, the Tools menu will only appear if something in your project is actually adding something to that menu

nimble scaffold
#

But I added a asset which uses tools window

slender nymph
#

are you sure about that?

nimble scaffold
#

Yes

slender nymph
#

then check your console for errors

nimble scaffold
#

Yeah I have one

slender nymph
#

well then you probably need to fix it

nimble scaffold
#

Wait

#

[Worker0] Failed to load 'C:/Users/SOHAM PAL DEBASHIS P/car/Assets/Car-Controller-master/ProjectSettings/XRSettings.asset'. File may be corrupted or was serialized with a newer version of Unity.

the error

slender nymph
#

this is not a code issue. you may need to restart the editor or something 🤷‍♂️

nimble scaffold
#

the file was deleted by me rn

runic prawn
slender nymph
#

that would work just fine if you assign those arrays in Awake

runic prawn
#

You'd think so

slender nymph
#

because it would

runic prawn
#

But it doesn't

teal viper
slender nymph
teal viper
#

Anyways, you've yet to answer what's going wrong.

#

Or how you detect/confirm it.

polar acorn
polar acorn
# runic prawn

That error does not look like it's in one of your scripts

slender nymph
# runic prawn

and that has nothing to do with when you create the array instances. the object you are passing to Instantiate is null which means your prefabs array contains null elements

slender nymph
polar acorn
slender nymph
#

yeah

polar acorn
runic prawn
#

what does that mean

teal viper
#

They initialize the array in awake and start with nulls, which causes the issue. I'd assume the constructor doesn't run at all, preventing the faulty code from running.

polar acorn
slender nymph
#

oh you know what, i know exactly why this is happening and it's exactly what i told them earlier

#

they have assigned values in the array in the inspector because these arrays are serialized. the serialized values are applied after the constructor runs

#

but if they create new instances of the array in Awake then of course those serialized values will be overwritten because Awake happens after that

runic prawn
#

Yeah this isn't needed

        bitBoard = new ulong[12];
        prefab = new GameObject[12];
polar acorn
slender nymph
#

nah, parameterless ctor should run when unity creates the instance

#

it's just that deserialization happens after the ctor has run

runic prawn
#

Okay, so it worked with the constructor because it was overwritten by the assignments in the instructor, but it didn't work with awake because it's overwriting the assignments in the instructor

#

makes sense

slender nymph
polar acorn
slender nymph
#

yeah, really only useful if you actually know what you are doing

runic prawn
#

Well I'm glad I asked despite it 'working'

nimble apex
#

just to make sure

    if (GameManager.Instance.isPaused)
    {
      msg = "ERROR_CONNECTION_FAIL_FROM_BG";
    }
#if DEV
    else
    {
      msg = detail;
    }
#else
    else
    {
      msg = "ERROR_CONNECTION_FAIL";
      GenerateSocketErrorLogs(detail);
    }
#endif
#

this will work right?

slender nymph
#

yes, but why bother including the else and the brackets in there? why not just wrap the statements themselves in the conditional compile directives?

north kiln
nimble apex
#
    if (GameManager.Instance.isPaused)
    {
      msg = "ERROR_CONNECTION_FAIL_FROM_BG";
    }
    else
    {
#if DEV
      msg = detail;
#else
      msg = "ERROR_CONNECTION_FAIL";
      GenerateSocketErrorLogs(detail);
#endif
    }
#

guess its just me braindead lol

slender nymph
#

either way works, i personally just perfer the latter so i know i'm not fucking up any braces in the non-compiled code

eternal needle
#

methods dont require you to write it, it will just default to private if you dont write any

#

im not entirely how unity does it, and i dont think its really known either (could be wrong on that). it doesnt really matter, they could be using their own messaging system or reflection.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.html
on the docs they do list all the methods as "Messages" for things they call like this

waxen adder
#

Don't know if this is the right place. I'm using a basic starter asset for a first person player to test some prototyping, and am trying to figure out how to handle the main camera. I don't suppose you would just add it to the prefab? Tried that and it didn't work out

slender nymph
#

don't make the camera a child of the player. and you should consider using cinemachine

waxen adder
#

Cinemachine, sounds fancy. Gonna have to look into that

meager gust
#

they use reflection

slender nymph
#

its fine if you don't really care about how it ends up looking, so for just learning sure it's alright. but if you want the camera to actually feel good then you won't do that

gaunt sandal
#

Hi all... I have a cylinder with a ridgedbody component and I'm trying to figure out how to make it lean over. This would be as if it was hinged at its bottom. I looked at AddRelativeTorque() but couldn't make it work right. Is that the proper method?

eternal needle
gaunt sandal
#

Well it's floating, and I want it to respond to wind or current

#

But its anchored

#

If I rotate it, it will turn at its center.

#

Even hinging at the base is not exactly right, ideally I'll do some trig and figure oiut the new position, accounting for the anchor line.

eternal needle
#

if this is a global variable, theres no difference. itll be initialized to null anyways
if its local, like inside a method, then the compiler will complain even if u try to do if(input == null)

#

yea

real thistle
#

this is scoped to the class, it becomes private to Foo, FYI.

rigid mesa
#

guys i have a question if you like uh learn 2d game coding and use the code that learn from making 2d games for 3d game will it still work?

slender nymph
#

there really isn't a whole lot different between 2d and 3d when it comes to code

twin bison
#

Hi, just wanted to know if this is a good or bad way or what can be improved.
I have a player that has 2 child gameObjects. These 2 child object just have 1 Collider each. One child is a "hitbox" and the other is a "magnet" (for picking up items).

The player itself has a controller script and a health script - that health script implements an Interface IDamageAble
When the hitbox script will detect a collision with enemy it will access the health script and decrease its life.
This is the little snippet :

void OnTriggerEnter2D(Collider2D other)
    {
        IDamageAble damageAble = other.GetComponent<IDamageAble>();
        damageAble.TakeDamage(10);
    }

How can this be improved?

eternal needle
twin bison
eternal needle
#

At the end of the day, itll have the same effect. I highly doubt you'll have a 2nd script implement IDamageAble

twin bison
slender nymph
#

the whole component vs interface debate for this is really just personal preference.
what isn't however, is null checking that object returned by GetComponent. you wouldn't want a bunch of errors if it hits something without an IDamageable or health component, so you should switch to using TryGetComponent instead of just GetComponent because it combines the null check and getcomponent call all into one line

twin bison
#

Next step is that the health script emits an event - so the GameManager will pick it up and then go in gameover state ? Or should the health script go into gameover state when it's 0 ?

eternal needle
#

Ah yea didnt even notice that get component thing

slender nymph
eternal needle
twin bison
#

In a bit more detailed, how would this event look like? Like PlayerDamaged(int remainingLife) and the gamemanager then checks if it < 0 ?

eternal needle
twin bison
#

Since health is on both enemy and player I kinda need a second argument to let the gamemanager to know if it is the player or enemy that hit 0 hp right?

eternal needle
#

Neither player or enemy would know about the game manager, the game manager subscribes to the event itself

slender nymph
twin bison
#
void CheckPlayerDead () {
        if(gameObject.tag == "player" && hp <= 0) {
            // dead.invoke()
        } else {
            return;
        }
    }
``` something like that?
slender nymph
#

what, why

#

just check health, don't worry about the tag

#

that way you can use the event for enemy things too, like tracking score, keeping count of how many are alive, etc

twin bison
#

yes but the health script is also attached to enemy, and when its an enemy that died, i want to emit another signal or something like that

slender nymph
#

why does it have to be a different one? just have one OnDeath event

eternal needle
twin bison
#

Ok, lets say a enemy dies and i emit OnDeath, the game manager picks it up and then he checks if it is the player and then goes into gameover state?

eternal needle
#

Nothing here should be checking if it's the player

slender nymph
#

why would the game manager subscribe to an enemy's OnDeath event? again, don't make it static

twin bison
#

ahhh ok im dumb

#

got it

#

the manager isnt subscribing to the script, but to the instance that has this script, and this is just the player instance, got it guys so helpful

eternal needle
#

Yea you got it

twin bison
#

it clicked, thx so much - now that i have a rough plan I will try to make something simple with it

upper crypt
#

Hello, I really need help with my script. I'm trying to move the ball by moving the mouse forward, etc. Like "Hyperbowl" game if anyone knows it. can anyone take a look at my code? if they have experience with this movement

slender nymph
#

why not just one object that contains all of the different stats as fields or properties

#

well creating a class for each individual skill is silly. You could instead create a Skill class with the level and modifier values

upper crypt
#

Okay, I thought it's best to include it in all 3 coding channels as I don't know where it should belong

slender nymph
#

yes

#

they still wouldn't need to be different classes for that unless they needed different behavior

#

you wouldn't go and make a "OrangeCat" class and a "BlackCat" class when you have two cats that share the same behavior but just have different values for things like color

#

right

twin bison
#

This the right way of creationg my died event on the Health script? What is the naming convention for delegate / event etc?

public delegate void Died();
public event Died died;

Invoking it:

public void TakeDamage(int damage)
    {
        StartCoroutine(FlashSprite());
        amount -= damage;
        particles.Play();
        if (amount <= 0)
            died?.Invoke();
    }
slender nymph
#

you don't even need to create a delegate for that, just use System.Action

twin bison
slender nymph
#

up to you whether you want to follow standard conventions or not. but C# naming conventions state that public members should be PascalCase

twin bison
#

Alright thx, now the last piece of the puzzle, am I doing it the right way?

public class GameManager : MonoBehaviour
{

    private Health _health;
    void Awake()
    {
        _health = FindAnyObjectByType<Health>();
        if (_health != null)
        {
            _health.Died += PlayerDied;
        }
    }
    void OnDestroy()
    {
        _health.Died -= PlayerDied;
    }
    void PlayerDied()
    {
        Debug.Log("Player died.");
    }
}
twin bison
slender nymph
#

i for sure would not use any of the Find methods to get a reference to the Health component. if the player is already in the scene at edit time, just drag the reference in. if it is spawned by something, then have whatever spawns it pass the reference

twin bison
#

Ok 100 % right

public class GameManager : MonoBehaviour
{

    [SerializeField]
    private Health _playerHealth;
    void Awake()
    {
        _playerHealth.Died += PlayerDied;
    }
    void OnDestroy()
    {
        _playerHealth.Died -= PlayerDied;
    }
    void PlayerDied()
    {
        Debug.Log("Player died.");
    }
}
#

That should do the trick

twin bison
#

When my weapon hits an enemy or obstacle, i will spawn particles at the location it hit. Where should that particle system reside? On the weapon? Or globally in the scene, spawning at location of hit? Interface with IParticleEmittable or something like that and then the thing i hit, that has this interface, will spawn the emitter at its position?

twin bison
craggy oxide
#

What is a MonoBehaviour

teal viper
#

A type.

teal viper
teal viper
twin bison
twin bison
#

One thing that feels a bit off to me is that health script emits the Died event and not the player script itself. But I think it's just the naming itself. In my head it reads "when health dies do x ..."

#

ReachedZero()? 😄

teal viper
#

I'm sure player would love to do some logic when it's dead too.

twin bison
#

so you mean the player could subscribe to this event and then invoke its own Died event?

teal viper
#

Yep

twin bison
#

ok got it thx

#

enemyHealth.Died += EnemyDied(enemy); what about this? How can i pass in a argument to the GameManagers "EnemyDied" method?

teal viper
#

Maybe you have some ability to install revive the player and it's defined on the player? You can then avoid invoking the player died event and instead restore health. Just an example.

twin bison
teal viper
#

In gameManager:
enemy.Died += onEnemyDied;
In player script:
health.OnZero += OnHealtReachedZero

teal viper
twin bison
languid spire
#

you pass the parameter value when you invoke the action not when you subscribe to it

twin bison
#

Have it like this now and it works 🙂

public event Action<GameObject> Died;
Died?.Invoke(gameObject);
royal ledge
#
    {
        bool isWall = other.gameObject.CompareTag("Tiles");
        
if (isWall){
            Vector2 normal = other.contacts[0].normal;
            rb.velocity = Vector2.Reflect(rb.velocity, normal);
             }
  }```

I have a bullet that i want to bounce clean on walls without loosing velocity, meaning it should bounce indefinitely, but i can't get it to work consistently, probably because the bullet physically hits the wall aswell. Any ideas? Should i Ignore the collision for 1 frame after each collisionenter2d?
fringe kindle
#

How do I go about applying velocity to a Third Person Controller when pressing a certain button?

#

From something like swinging on a rope

#

Because whenever I pressed the space bar to jump off, it just keeps plummeting to the ground

frosty hound
timber tide
#

well, if you're parenting/attaching the player to the rope and using the rope to guide the player then you need to also transfer the velocity over to the player when disconnecting from the rope

fringe kindle
#

This is what I have, codewise.

I'm sure it should be transferring the velocity over but it doesn't whenever I have the Third Person Controller Script enabled. Otherwise, it works as intended.

#

I have a rigidbody on my character and everything

frosty hound
#

Isn't the third person controller a kinematic controller? It doesn't use a rigidbody to move?

fringe kindle
#

Yeah, because I couldn't find anything about rigidbodies in the script

#

I added one onto the character as a component

frosty hound
#

They're going to conflict

fringe kindle
#

Oh

#

So is there a way to pull off the swing jump without a rigidbody?

frosty hound
#

Manually calculating the physics. Or you keep what you're doing and apply the velocity to the player controller you use for actual non-rope movement as the new velocity.

#

Or you commit to using a rigidbody movement controller for everything outside the rope as well and keep it all within the same system.

fringe kindle
#

So by disabling the third person controller when swinging on the vines and replacing it with a rigidbody one?

frosty hound
#

You implied you were disabling the controller when you were swinging and activating the rigidbody instead. Then swapping them back after you release.

fringe kindle
#

Yes

frosty hound
#

So when you swap them back the other way, when you turn off the rb and turn on the controller, you need to take the velocity of the rb and apply it to the controller.

#

Or as above, drop the controller and use a rb for everything

ionic zephyr
#

how can I make my platforms with a linear movement? because It starts to slow down when it reaches its destination with the Lerp vector

twin bison
#

Hi guys in my gamemanger I have this function that a enemy spawner will call. Is it better to write it either this way:

public void AddEnemy(EnemyController enemy)
    {
        _enemies.Add(enemy.gameObject);
        enemy.Died += OnEnemyDied;

    }

or that way:

public void AddEnemy(GameObject enemy)
    {
        _enemies.Add(enemy);
        enemy.GetComponent<EnemyController>().Died += OnEnemyDied;

    }

What would you prefer and which one makes more sense? Any other mistakes I've made maybe?

lost hamlet
#

or just add the same value to it each frame

#

both work

frosty hound
#

Or as above, lerp the start and end position

ionic zephyr
lost hamlet
#

between A and B

#

If you use the current position it will slow down the closer it is

ionic zephyr
#

Oh, of course, thanks a lot!

earnest basalt
#

so basically when i add using System LINQ my current code breaks because it thinks I want to use LINQ instead of some other package
Its working until I add System LINQ.

#

But I neeed LINQ for something else

hexed terrace
#

I'm pretty sure it won't like that massive gap you've got there

earnest basalt
#

i need to somehow force it to use a specific package

ionic zephyr
#

How should I check that my Platform has reached point A or point B?

languid spire
earnest basalt
#

its gonna use findobjectoftype every frame until it finds right ?

languid spire
#

yes

earnest basalt
#

so you suggest to search every 0.1f of a second instead?

languid spire
#

no, find another way of doing this

north kiln
#

Why can't this thing just register itself instead of constantly querying every object in existence

shell sorrel
#

Or find a better way, like have things register themselves with the system as needed

earnest basalt
#

i see will think about it

#

Yeah I need to stop using findobjectoftype constantly haha. its coz it works fast on my pc that i dont replace it with faster methods

#

but its better to get rid of it

hexed terrace
#

It's fine to use, properly, in appropriate places

ionic zephyr
#

my platform doesnt move

#

like at All

shell sorrel
#

like a find object of type during a 1 time awake here and there sure cache it once and use it

#

per frame on multiple objects and you are approaching a problem wrong

hexed terrace
twin bison
#

Can 2 colliders that are triggers trigger collision / trigger enter?

ionic zephyr
hexed terrace
#

Don't try and put it into your scenario straight away, follow it.. do the examples.. learn.. and then play with it and change for your needs

fringe kindle
#

When it comes to transferring the velocity from the rigidbody to the (kinematic) third person controller, which script does it need to be a part of? The vine swinging or the third person controller script?

queen adder
#

Is there anyone who knows about Photon Engine Multiplayer system in Unity?

twin bison
#

I have one HitboxComponent that has a collider that is also a trigger. Now i have a player and an enemy and both have this component as child. When I move with the player to the enemy, the OnTriggerEnter2D for the players fires 1 time and the OnTriggerEnter2D for the enemy fires 2 times - any idea why?

Code:

void OnTriggerEnter2D(Collider2D other)
    {
        Debug.Log(tag);
        Hit?.Invoke(5);

    }

Log:

Enemy
Enemy
Player

Hence the enemy always takes double damage. What am I doing wrong?

#

Nervermind! My player has a second component that is also a trigger called PickupRange, is there a way to check for collider name or something?

gaunt ice
#

yes, by if statement

ionic zephyr
gaunt ice
#

no built in way btw, write it yourself

ionic zephyr
#

but the change of points doesnt

gaunt ice
#
_OriginalPosition = _PlatformObjective;
_PlatformObjective = _OriginalPosition;
int x=10,y=5;
x=y;
y=x;
what is the value of x and y now?
ionic zephyr
#

oh god

#

thanks a lot, stupid doubt

twin bison
rare basin
#

by name

#

do it by getcomponent or even tags

twin bison
#

Yep I will add some tags thx

deep robin
#

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

keen dew
#

Read the error message

#

short * short = int, you do need to cast

minor cloud
#

Hey there. I made a script to aim these turrets on this ship... When this spaceship moves. The hole thing shits itself. Any help?

Also my braincells can't handle adding turnspeed... Optionally it would be great if someone could help me on that front too.

Code:```using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TurretAim : MonoBehaviour
{
public Camera camera;
//public float maxTurnSpeed = 90f;
public int minRotationAngle = -45;
public int maxRotationAngle = 45;
private bool camExistis = true;
[SerializeField]
private bool lockZRot = true;
private void Start()
{
if(camera == null)
{
camExistis = false;
}
}

void Update()
{
    AimAtMouse();
}

public void AimAtMouse()
{
    Vector2 mousePos;
    if (camExistis)
    {
        mousePos = camera.ScreenToWorldPoint(Input.mousePosition);
    }
    else
    {
        mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }
    float angle = -Vector2.SignedAngle(this.transform.position, mousePos);
    angle = Mathf.Clamp(angle, minRotationAngle, maxRotationAngle);

    this.transform.localEulerAngles = new Vector3(0, angle, 0);
}

}```

queen adder
#

        IEnumerator late(CustomYieldInstruction delay, Action act){
            yield return delay;
            act?.Invoke();
        }```how to use this? What kind of instruction can i feed in `delay`?
queen adder
#

me just did :3

bright zodiac
queen adder
#

no, im trying to make sure some methods are don in EndOfFrame, but realized I should use just YieldInstruction for those

bright zodiac
queen adder
#

ah yea? mj just enlightened me like earlier

bright zodiac
#

it's similar to this

    public IEnumerator Foo(Action func)
    {
        yield return new MyCustomYield();
        func.Invoke();
    }
#

just like regular coroutine

twin bison
#

Is this a good idea (hurtbox and hitbox)?

buoyant knot
twin bison
ionic zephyr
#

Why aren´ t my materials working even if I assigning them to the Colliders of Objects

buoyant knot
#

well, if you want to make an enemy that is like a goonba with a big spike on its head, and is vulnerable on the main body, then it makes sense

#

to make spike a hitbox and body a hurtbox

twin bison
buoyant knot
#

it depends on the type of game, really

#

i would expect for an FPS to only need 1 hitbox

#

since enemies don’t do dmg on touch. it’s the objects and projectiles they spawn or whatever that have hurtboxes

#

for mario, might be good to split up

#

for smash bros, characters don’t have a normal hitbox active on them at all times

#

for sonic, you definitely want to split

ionic zephyr
#

Do materials need a RigidBody?

buoyant knot
#

physics materials live on rigidbodies

ionic zephyr
#

but also in Colliders

buoyant knot
#

i don’t think so

#

maybe it is different for 3D

#

i don’t recal if colliders can have different materials

polar acorn
buoyant knot
#

in 2D, colliders without RB are assumed to have a static RB on them

ionic zephyr
buoyant knot
#

or rather, they behave as though they have a static RB with settings that don’t change anything you set on the collider

ionic zephyr
swift crag
#

that's how I did hit/hurt boxes in a soulslike

#

I created Hitbox and Hurtbox components

#
void OnTriggerEnter(Collider other) {
  if (!other.TryGetComponent(out Hurtbox hurtbox))
    return;
  // hurtbox is now guaranteed to contain a valid Hurtbox

  hurtbox.Damage(10);
}
polar acorn
ionic zephyr
swift crag
ionic zephyr
polar acorn
#

It only moves how you tell it

#

Forces don't act upon it without code telling it to do so.

ionic zephyr
#

But what about SimpleMove

fringe kindle
#

This is the code I'm trying to use to transfer the velocity of the rigidbody to my Third Person Controller.

The problem is that I'm getting mixed results with the game. Sometimes the character jumps and sometimes it doesn't, neither of which matching with the velocity values I set.

Am I doing it right? Or is there something missing?

polar acorn
hexed terrace
ionic zephyr
#

It applies gravity

buoyant knot
#

my game does not have separate hitboxes. I have a main collider, ObjCollision component, and EntityData SO. ObjCollision listens to all collisions, makes a small struct with condensed info about the collision, and invokes anything listenning to it with the collision info.

I then have GenericEnemyLogic : Monobehaviour that subscribes to ObjCollision’s events, and it checks the entity data vs the masticated collision info to cause different things to happen.

polar acorn
ionic zephyr
#

Ooh okay then

#

So basically CharcterController provides the control of your character only considering collisions and won´t move in any direction(including vertical) unless the code you write says so

buoyant knot
#

like, EntityData has an enum Cardinal for directions where an enemy can hurt/be hurt by the player, is flammable, can set things on fire, etc. And this gets parsed

#

eg goomba can hurt mario if touched by left/down/right, but is hurt by mario from above.

#

this allows different flags to be easily added to the game for vulnerability to different things

#

want to add radiation? just add a bool to EntityData

true yacht
#

hi, faced a strange issue, turning animation works on pc, but not on mobile (or simulator in editor), move tree works perfectly, why is that?

buoyant knot
#

this info is directed more at Fen

polar acorn
swift crag
true yacht
swift crag
#

the hurtboxes themselves just told the entity "hey you got hit"

swift crag
#

show us the transition's inspector

true yacht
#

yes

swift crag
#

Have you checked if isRot is being set to true?

#

If not, you have a scripting problem

#

You can look at the animator window while the game is running in the simulator

buoyant knot
swift crag
#

just make sure you have the animator's object selected

true yacht
swift crag
#

That does not answer my question.

#

I asked if isRot is being set to true when the problem occurs. You need to check that.

#

Perhaps your code isn't handling mobile input correctly.

true yacht
swift crag
#

Okay, so you have a code problem.

#

Look at the code that's responsible for setting that boolean

#

You can check if it's running at all with Debug.Log.

true yacht
#

Looks quiet strange, cause mobile input on pc works fine also

swift crag
#

it works fine except for making you turn :p

#

you aren't going to fix this by explaining to me how it couldn't possibly be broken!

#

get to debugging -- check if the code is running at all, and if it's producing the values you expect

buoyant knot
#

i might have a nasty refactor ahead of me. My main level editor (which I made at start of development) handles level editor input, undo/redo history, preview management, and actually editting my level.

The biggest challenge is separating level editting methods between: 1) private methods only level editor has, 2) methods that only other level build classes get access to, and 3) public methods all scripts get access to.
Any recommendations?

swift crag
#

are you trying to break this off into an assembly?

buoyant knot
#

i wanted to, but it’s too coupled

swift crag
#

I would start by finding every public member and seeing if it can be made less visible without any other changes

buoyant knot
#

right now, everything that is public should be public, and everything that is private is a mix of functions that should be private and others that should only be visible to other classes in my build system

#

part of why i have the too-many-responsibilities problem is that I really want to avoid exposing several methods to all my scripts, which is why I kept piling on the private methods into one class

#

but now, I want to add more features to the level editor, and if I add more private methods to that class, I will go insane

swift crag
#

One option is to use partial classes to break one very large definition up into multiple pieces. I'm not a huge fan of this, though.

#

I tried it once and wound up five files with no clear organization

buoyant knot
#

that doesn’t feel like a solution

swift crag
#

(i wound up just obliterating the entire class with a total rewrite)

swift crag
buoyant knot
#

that feels like a way to end up with one class over multiple files

swift crag
buoyant knot
# swift crag gimme an example of a feature you're adding

level editor right now has methods:
-DrawCommand (what to do when user issues a command to draw at current pos, including validation logic)
-DrawWithLog (try to draw a tile while logging everything to the undo history)
-public ForceDrawAt (during runtime, other scripts can request drawing at a specific spot)
-public SmartDrawRuntime (force draw, but also funnels logic through some singletons that may need to update internals)
-DrawAtRegion (actually erases anything that conflicts in different tilemaps, and draws)
-SetTileAt (draw the tile, but I have special info to also manage)

#

these aren’t the actual names, but the actual desired function of each

swift crag
#

If you can build up a good "core" of functions for manipulating the level, you can move implementation of the level editing tools into other classes

buoyant knot
#

now I want to add custom draw logic, where certain types of tiles will have custom draw functions, where when used, they will change the map while in editor mode

#

imagine placing the goal flag, and the goal flag needs to move a gameobject, AND erase some tiles that would conflict with the game object, AND log all of this to the undo log

true yacht
# true yacht

Lol it doesn't debugs at all, seems like there is no IK pass on mobile

#

Because i change this value probably in OnAnimatorIK

buoyant knot
#

but I want to keep anything that alters the build history (for undo) under extremely tight lock-and-key

true yacht
#

and its ok on pc but idk somehow on mobile it does not work

west sonnet
#

Can anyone please help me with what this error message means?

true yacht
fringe plover
#

!code

eternal falconBOT
swift crag
frosty hound
swift crag
#

I would not expect OnAnimatorIK to not run on mobile.

buoyant knot
#

and I have several sets of methods like this for rotate, erase, and I later want to add select + copy-paste. All of this needs access to change build log

swift crag
#

modifying it would do nothing at all

buoyant knot
#

but if I keep doing all this stuff as private in one class, it is just totally out of control, and i need to put my foot down

swift crag
#

hence the error, and hence the fix -- store it in a variable, modify that variable, and assign the variable back

gritty notch
#

what is the difference between using raycast and onmousedown in 2d? is one better than the other?

fringe plover
buoyant knot
fringe plover
swift crag
#

it works on both 2D and 3D colliders

#

Physics.Raycast only cares about 3D colliders. It's useful for figuring out what object is "under" a pixel on the screen

#

like for shooting a gun

#

It ignores 2D colliders.

#

It lets you ask if there's a collider at a specific point

swift crag
#

this is in the context of OnMouseDown, which tells you which game object you clicked on

hexed terrace
swift crag
#

so I'm thinking about ways to detect a collider under your mouse

fringe plover
#

Jump and Dash have different jumpSpeed

hexed terrace
#

Then share the most up to date code so you don't waste our time ¯_(ツ)_/¯

fringe plover
#

IT ACTUALLY FIXED

cosmic quail
swift crag
#

we're talking about 2D physics here

#

a Physics2D.Raycast would not really make sense

fringe plover
swift crag
#

you use a Raycast in 3D because you need to detect every collider along a line; if you're using 2D physics, you only need to sample a single point in space

buoyant knot
#

i never use raycast in 2D

#

ever

swift crag
#

it'd be plenty useful if you wanted to shoot a 2D gun :p

buoyant knot
#

that would be the only real use case, ig

swift crag
#

Now, if you actually made a first person 2D game, you would use Physics2D.Raycast

#

But your screen would also be an infinitely thin 1D line..

#

not exactly a great experience

#

Flatland: The Video Game

buoyant knot
#

Casting a whole 2D collider is just so cheap relative to the amount of information it gives, you want to actually very specifically want to shoot a thin beam for raycast to be the right one

cosmic quail
swift crag
#

Unless you were a four-dimensional being playing the game on a three-dimensional display. Then you'd just sample a single point in space again.

buoyant knot
#

raycasting to detect ground, walls, enemies, etc in 2D is just mostly inferior to Casting collider

swift crag
#

😁

buoyant knot
#

so many people just do like a fan of raycast beams, spaced at different points. it’s actually worse than just doing the whole collider

#

when you have a simple shape in 2D

swift crag
#

I do that when I actually need lots of individual samples

#

like if I need an enemy to be able to partially see you

buoyant knot
#

i feel like there is a smarter way to do that with LineCast and Cast

#

anyway, point being, Collider2D.Cast is good. use it

#

feels expensive. is not super expensive

fringe plover
cosmic quail
fringe plover
#

I hope he's not using Raycast3D in 2d💀

sleek notch
#

I'm doing player movement and I applied rigidbody to this but when I move the whole character fall down logickly

#

How can I fix it?

swift crag
#

you'll want to freeze rotation in the X and Z axes

#

you can do that from the "Constraints" section of the rigidbody's inspector

sleek notch
#

Ok thanks

fringe plover
sleek notch
#

Why is it not working?

swift crag
#

Read the error message.

fringe plover
sleek notch
#

Man I'm beggining with 3d

swift crag
#

Read the error message.

fringe plover
#

yeah

swift crag
#

You can't possibly fix this unless you read the error message.