#๐Ÿ’ปโ”ƒcode-beginner

1 messages ยท Page 840 of 1

wintry quarry
#

Or the firing point is not a child of the gun

#

Showing screenshots of the setup of the gun and the firing point in the scene would help

#

Including the inspector for this script

ebon ice
#

I have the exact same setup on the player, the only difference is that I use Rotate() on the player to move with arrow keys and LookAt() on the enemy which is why I initially though that was the problem

verbal dome
# ebon ice

Why are you using FindGameObjectWithTag for the parent instead of a direct reference (like you did for firing_point)? Doesn't each tank have its own shell container? Or is it shared between tanks..?

ebon ice
#

It's in the level, I'm used to Godot so maybe not necessary here, but in Godot if you didn't reparent to an empty in the level, turning the tank would turn the airborne shell too if it's still in the scene.

#

I could do a direct reference

grand snow
#

even in godot you can "serialize" references right?

#

using tags/names are the less ideal solutions

rich adder
#

its a prefab, I'm guessing they need to find it runtime on spawn? but should use awake/start or pass it directly on spawn instead of every Shoot()

verbal dome
rich adder
#

godot parents a spawned object by default ? oof

verbal dome
#

Also I gotta ask, does the tank have an animator?

ebon ice
#

It does not

ebon ice
grand snow
#

wild but yea if the thing is external to the prefab just perform some setup post spawn

verbal dome
#

Does the shell use a rigidbody, maybe it is colliding with the turret that's shooting it?

ebon ice
#

It only has a trigger collider

#

and damage is called OnTriggerEntered()

swift crag
#

right, but does it have a Rigidbody?

ebon ice
#

It does not

swift crag
#

how does the shell move, then?

#

ah, Translate

ebon ice
#

Yeah I posted it above

rich adder
#

Unless you use Raycast or something, thats bad way to do detection if you want accuracy

#

Translate is essentially teleporting it (OnTriggerEnter works with physics) you're in a draw of the luck if it ever does detect it w/ translate, assuming the tank has RB

swift crag
#

indeed, that'll need to be fixed later

verbal dome
#

So this is the current issue

ebon ice
#

Yeah

verbal dome
#

Why's the enemy health UI rotated like that btw

#

Looks wrong

#

Might be a clue

ebon ice
#

The healthbar for now (until I fix it) is just a child of the main tank body

grand snow
#

tis beginner channel probably not something that was solved yet ๐Ÿ˜†

swift crag
#

in play mode, pause the game and select the enemy's FirePoint object

#

ensure that your scene view is set to show local handles, not global handles (check the top-left corner of the scene view)

#

the arrows should align with the barrel of the gun, and as the turret rotates, they should rotate with it

rich adder
#

might need to flip the healthbar parent

verbal dome
ebon ice
#

I haven't locked it to the y axis yet so it does dip but even then it should still spawn from the firing point even if it fires down

swift crag
#

that looks valid (for a bullet that travels in the -X direction!)

#

the red arrow points right

#

next: pause the game after the enemy shoots and select the bullet that it fired

verbal dome
#

It could be an issue like:
Update -> Something resets the turret rotation
Update -> Shoot (in the wrong direction)
LateUpdate -> Set the actual turret rotation (which is what ends up rendering)
But i'm just speculating

swift crag
#

it would be helpful to see the entire script

solar hill
#

!code

radiant voidBOT
solar hill
#

please use the pasting sites when sharing entire scripts

swift crag
#

a paste site will make it easier to browse, ye

solar hill
#

also it does not embed on mobile

#

use the pasting site

#

please....

polar acorn
#

!code

radiant voidBOT
solar hill
#

you didnt do anything different now

#

look at the bot message

#

5 unmissable links right at the top

#

pick one, preferably the third one, copy and paste your script there

#

and share the link here

swift crag
# ebon ice

hm, it looks like the bullet's world rotation doesn't quite match the shooting point's rotation

ebon ice
#

That's what I just pasted...

solar hill
#

you pasted a .txt

swift crag
#

you wound up pasting the entire script directly into the chat

solar hill
#

not a link

swift crag
#

the site might have misbehaved

naive pawn
#

wait did the list change again

ebon ice
#

Yeah looks like that isn't actually copying

naive pawn
#

it was 6 like last week wasn't it

ebon ice
#

This was pastes.dev

naive pawn
#

i think pastes.dev is so far the best but it's certainly not perfect unfortunately

swift crag
# ebon ice

Assuming that the "Shell Container" object is un-rotated, this rotation is weird. The enemy tank is rotated towards the player by more than 4 degrees

verbal dome
ebon ice
swift crag
#

i'm suspicious of this line

turret.rotation = Quaternion.RotateTowards(transform.rotation, target.rotation, rotation_step);

This is starting with the tank's rotation and trying to align it with the target's rotation, then using that to set the turret's rotation. That doesn't smoothly rotate the turret at all (it's just going to make the turret align with the tank, with a slight bias based on the target's own rotation)

#

However, the tank can't fire without first calling turret.LookAt(target);

ebon ice
#

Ah yeah that was trying to figure out why LookAt wasn't working and look for other possible solutions online

#

Oh I see I was looking at the commented out code

#

That one is supposed to be the tank I must've used the wrong rotation when setting up the navmesh

#

Yeah that was it...

swift crag
#

The NavMeshAgent is going to be setting the rotation of its own Transform constantly

ebon ice
#

I must've replaced the wrong variable at some point as originally the turret wasn't being used

swift crag
# ebon ice Yeah that was it...

but that's impossible! the turret gets pointed directly at the player afterwards, and you the instantiate a bullet in the same function; there is no time for anything else to interfere

verbal dome
#

Attack being called in two different places seems off to me

swift crag
#

Oh, duh

#

I didn't see Attack there

#

yep, that's the issue

#

turret gets rotated weirdly, Attack is called

ebon ice
#

Yeah because it can't attack for a short while again

swift crag
#

and then the turret gets rotated correectly immediately

swift crag
#

yep, almost that!

#

just within a single function

ebon ice
#

Thanks a lot!

swift crag
#

I've had similar issues (on a larger scale) while dealing with interactions between IK, ragdolls, physics, ...

ebon ice
#

So it was updating rotation with navmesh, attacking, then because I set it up to have a delay before it can attack again, the actual turret turning attack didn't get called

swift crag
#

Yeah, the Attack() call after the turret rotation could only succeed if the enemy could not see the player

#

but, if the player isn't visible, that can't be reached anyway

prisma shard
#

Black dots are units, red lines are the path, green is the formation they are commanded to enter into. I am not smart enough to rely on my own knowledge. Does anyone know what i could tell an AI or at least what math formulas would fix this multi agent path finding for me.

naive pawn
#

could probably weigh for the closest position that isn't taken?

echo tulip
#

Hello, Looking for a Level Designer / Environment Artist
Hi everyone! Iโ€™m currently developing my own game and Iโ€™m looking for a talented level designer to create a custom map for me. I have a reference map layout and a specific vision in mind (similar to Ranch Simulator style).
If youโ€™re interested or can recommend a platform/artist, please let me know or DM me. Iโ€™d love to see your portfolio and discuss the details!

naive pawn
#

would be a naive approach thay would probably be ok-ish

radiant voidBOT
# naive pawn !collab

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
โ€ข ** Collaboration & Jobs**

prisma shard
prisma shard
naive pawn
#

is movement on a grid?

prisma shard
#

Just a gigantic one

naive pawn
#

oh that changes things

#

(fyi please be upfront about this kind of context)

prisma shard
#

my mistake i already described it in here before idk why i assumed people knew that

wicked stratus
#

If I'm planning to use raycastall for mouse position (Sort of like onmouseover but for everything the mouse is over), is it best to have it be a singleton and just grab that array from other methods when needed? I'm assuming yes?

naive pawn
#

do they have some kind of central manager or do they have to figure this out themselves as emergent behavior?

naive pawn
#

figure out the system design you want to have, how it'll interface with other systems. draw on paper or in diagram tools if it helps

naive pawn
wicked stratus
#

no worries! I'm worried specifically about performance here

#

It's kind of a silly/simple question but I was just checking since I am newish to raycast stuff and want to make sure there's not like common knowledge I'm missing here

ivory bobcat
prisma shard
wicked stratus
# ivory bobcat Sounds like you're asking if you ought to use a Singleton to share data. The phy...

I basically want a replacement for OnMouseOver, since it's kind of picky about overlapping colliders and such, I want an OnMouseOver for anything the mouse is over, and I'm trying to find the most efficient and easy way to achieve that.

A few Ideas I have for that is having like an interface for anything that may have behavior when the mouse is hovering over, and calls the functions in that if it has that property. Another would be having a raycastall on all of the scripts that may need it but that seems pretty bad/inefficient, and I feel there is probably a more elegant solution

ivory bobcat
#

I'd worry about efficiency later. This looks like micro optimization in the grand scheme of things. Just use whatever works for you.

wicked stratus
#

Ah okay, thank you!

naive pawn
#

what about figuring out which positions are closest to which units, starting with the position that's farthest from all units?

#

oh, this might be quite inefficient

ivory bobcat
prisma shard
#

i guess i could try something like that ive just been trying to limit those kinds of things as much as possible because of lag

naive pawn
#

ideally it'd be O(n^2), what i'm suggesting would be O(n^3)
it'd something like this

while remaining positions:
  for each position:
    find nearest unit
  "targetPosition" = find position with farthest "nearest unit"
  "targetUnit" = targetPosition's nearest unit
  targetUnit goto targetPosition
  remove targetPosition & targetUnit from pool of consideration
#

you could cache the "find nearest unit" part if the previous nearest unit was not removed from the pool

while remaining positions:
  for each position:
    if position's nearest unit == null or isn't in pool
      find nearest unit
  "targetPosition" = find position with farthest "nearest unit"
  "targetUnit" = targetPosition's nearest unit
  targetUnit goto targetPosition
  remove targetPosition & targetUnit from pool of consideration
```(null check for the first loop)
wicked stratus
naive pawn
#

(read the docs/signatures)

prisma shard
wicked stratus
#

thank you both, I'll do some more reading and play around with it a bit

rich adder
#

anything that returns results more than 1, always opt in for NonAlloc versions

wicked stratus
rich adder
#

eg
myarray[i].collider
i comes from the hits

wicked stratus
#

Why wouldn't you use myarray.length?

rich adder
wicked stratus
#

oh pft

#

right

rich adder
#

You may iterate over missing items

#

so in a nutshel

RaycastHit[] storageArray = new RaycastHit[maxResults]; // i think some want a Collider[] depends on which cast
int hits = RaycastThingNonAlloc(etc.
for (int i = 0; i < hits; i++){
var itemToCheck = storageArray[i].collider // etc.```
ivory bobcat
# wicked stratus Why wouldn't you use myarray.length?

I believe they're referring to how you're to use the returned integer. For example:cs int count = Physics... for (int i = 0; i < count; i++) ...where i may be some value less than the length of the array by design so you shouldn't simply iterate every element of the array as they may not have been used.

grand snow
#

raycast hit 2 things but array 8 long, bad times if you check all 8

#

good times checking just 2

prime cobalt
#

I keep getting null ref exceptions in the second loop when I'm near a wall... notlikethis When the first loop should take care of those.

//Get all nearby colliders in the wall layer
int numCollidersHit = Physics.OverlapSphereNonAlloc(transform.position, wallCheckDist, nearbyColliders, whatIsWall);

//Exclude walls that are below the player
List<Collider> nearbyWalls = nearbyWalls = new List<Collider>();
if (numCollidersHit > 0)
{
    //Turn the array into a list for easier resizing
    nearbyWalls = nearbyColliders.ToList();

    //Check each collider in nearby wall colliders
    for (int i = 0; i < numCollidersHit; i++)
    {
        //Get closest point
        Vector3 closestPoint = nearbyWalls[i].ClosestPoint(transform.position);

        //If the closest point on the collider is below the character controller then remove from list
        if (closestPoint.y < transform.position.y - (controller.characterController.height / 2) || nearbyWalls[i] == null)
        {
            nearbyWalls.Remove(nearbyWalls[i]);
        }

        
    }
    //Set num colliders hit. This keeps using num colliders hit so that if the player isn't near a wall they don't waste processing power on changing the array into a list.
    numCollidersHit = nearbyWalls.Count;
}

//Check if there's still active walls after the cull of ones below the player
if (numCollidersHit > 0)
{
    //The wall which is closest to the player 
    Vector3 closestWall = Vector3.zero; 

    //Find which wall is closest to the player
    for (int i = 0; i < nearbyWalls.Count; i++)
    {
        Vector3 closestPoint = nearbyWalls[i].ClosestPoint(transform.position);
        if(Vector3.Distance(transform.position, closestPoint) < Vector3.Distance(transform.position, closestWall)) 
            closestWall = closestPoint;
    }

    //Get the normal of the closest wall
    nearWallNormal = Vector3.Cross(closestWall - transform.position, transform.position - closestWall).normalized;

    //Yes there is a wall near
    wallNear = true;
} else
{
    //No, there is not a wall near
    wallNear = false;
}
prime cobalt
grand snow
#

The fuck is this
List<Collider> nearbyWalls = nearbyWalls = new List<Collider>();

naive pawn
#

so nearbyWalls, nearbyWalls[i] or transform
transform definitely isn't it

#

do you have both a local field and a member named nearbyWalls

prime cobalt
naive pawn
#

nearbyWalls = nearbyColliders.ToList();
this is suspicious as well

#

nearbyColliders is from a NonAlloc query, it doesn't necessarily have all valid members

grand snow
#

I have to point out there are better ways to check some array/list and pick the closest thing

swift crag
#

it does check out, though

grand snow
swift crag
#

you never use the variable before it's initialized

naive pawn
#

sometimes handy for readability...

swift crag
#

oh, I was specifically thinking about how you were using the declared variable in the expression that assigns into it

#

(that's not even a syntax matter)

#

that's just a semantics matter

naive pawn
#

oh yeah i didn't think so either

ivory bobcat
wicked stratus
# ivory bobcat I believe they're referring to how you're to use the returned integer. For examp...

Okay I think I see where I'm getting confused a little more.

    private void Update()
    {
        HitsArray = Physics2D.RaycastAll(InputManager.instance.WorldPoint2d, transform.forward, 100.0f); // WorldPoint2d is the mouse position, and the object this is attached to would have no rotation.
    }

In this circumstance, would RayCastAll return an array with the length of how many hits there are? It wouldn't return blank entries in that array, right?
Is this code chunk bad practice? Does it not overwrite the prior array essentially, or does it still keep that data handy/read only and cause issues?
Thank you also for your patience with me

swift crag
#

You are re-assigning the HitsArray variable.

grand snow
# prime cobalt There is? How?

made up example

float closestThingDistance = 0f;
Collider closestThing = null;

foreach(var thing in things)
{
    float distance = Vector3.Distance(us.position, thing.transform.position);
    if(closestThing == null || distance < closestThingDistance)
    {
        closestThing = thing;
        closestThingDistance = distance;
    }
}
naive pawn
#

In this circumstance, would RayCastAll return an array with the length of how many hits there are? It wouldn't return blank entries in that array, right?
yes
Is this code chunk bad practice?
not necessarily. using the nonalloc form can be better for perf but it does require an assumption about how many entries you will receive.
Does it not overwrite the prior array essentially, or does it still keep that data handy/read only and cause issues?
yes, that's what assignment is
the data will be kept if there are other references to it, and if not, it will eventually be freed (garbage collection (GC))

prime cobalt
rich adder
#

@wicked stratus layer filtering might help a little but still if you call this everyframe its unecessary amount of GC for new array each time

grand snow
wicked stratus
#

oh okay.

So to make sure I understand, say my HitsArray = [hit1, hit2, hit3]
but then on the update, the HitsArray = Physics2d.RaycastAll(...) which equals [hit4, hit5, hit6]
it doesn't get rid of the original hitsarray and that memory builds up, then? Is there a way to tell it to throw the original hitsarray away?

naive pawn
#

it won't get rid of it immediately, but it will eventually if nothing else uses it (GC)

swift crag
#

The problem is not that the old memory is never disposed of (it is)

#

the issue is that you keep allocating more and more memory, which creates more work for the garbage collector

naive pawn
#

you may just want to look up a GC explainer so you have a little more context

wicked stratus
#

Ohhh okay. I will do that

#

Thank you

swift crag
#

a non-allocating method is like a whiteboard

#

you have to get a large enough whiteboard to hold all of the data

#

but you aren't creating any garbage when you put new stuff on it

#

allocating methods are like a printer; every time you get data, you're making garbage

rich adder
#

on this point giving yourself a decent amount even doing 100+ items array will be less to worry about than a new one of 20 each frame

naive pawn
#

i thought this was gonna be like the alloc method taking out a permanent marker and giving you a new whiteboard every time

swift crag
#

Note that none of this matters whatsoever unless you're doing it many times per frame

#

like, at all

#

it does not matterโ„ข

#

I say this as someone who spends a ridiculous amount of time and effort minimizing allocations

#

fortunately, this is a situation where performance and readability aren't at odds

swift crag
#

so I do like to use non-allocating methods by default when it's practical

#

it's not like you're making your code dramatically harder to understand for a minute gain

naive pawn
swift crag
#

the usual trick of "make a static array and re-use it" works fantastically as long as it's impossible for two things to want to use the array at once

wicked stratus
#

โœ๐Ÿผ โœ๐Ÿผโœ๐Ÿผ ok thank you

naive pawn
#

(or just make it a member instead of a local, doesn't need to be static)

swift crag
#

(e.g. imagine you call a method when you detect an object, and that method also wants to do raycasts)

naive pawn
#

oh wait i may have misinterpreted "static"

wicked stratus
naive pawn
#

(it was in fen's message)

wicked stratus
#

Oh gotcha, I think it was in my original one too so if that caused confusion at some point I do apologize.

prime cobalt
#

Nice I altered some stuff and it works, thanks for the advice!

swift crag
#

(assuming single-threaded code, of course)

stable yarrow
#

Is there anything like f3x (a plugin from roblox studio) in unity? Or any good youtube tutorial on how to properly use these horrendous default tools?
I learned about ctrl+shift on move tool for collision moving and holding v for vector aligning.
But I cannot find anything information on how to turn on collision when using the scale tool.

polar acorn
#

...what?

#

What does the scale tool have to do with collision?

stable yarrow
polar acorn
#

Objects don't have collision when the game isn't running. There's no physics so no colliders

teal viper
#

Assuming you're scaling the parent object of both physics and visuals, colliders should scale as well.

stable yarrow
#

Sure that is fine, the objects I have do have box collider components.
I asking about if theres a way for the scale tool to stop when the object hits another

#

Or maybe a better way would be if theres a way to scale an object to an exact point like holding v? if thats possible

teal viper
stable yarrow
teal viper
#

Physics queries should work in the editor too, so you should be able to implement it.

verbal dome
#

So yeah it could technically be implemented

#

(I only vaguely know about this roblox tool since other people have brought it up before)

ivory schooner
#

Does anyone know how to help to make this border match the width of this health bar slider? I can show any code that you need to see. Right now, the slider is at full health, but it doesn't get to the border. :/

copper pasture
#

I'm trying to test out a camera but I cant find the play button

#

I have to use crtl p and when I do it breaks it anyways

slender nymph
#

!input

radiant voidBOT
# slender nymph !input
How to Set Input

To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling

โ€ข Input Manager (Old): Use the original Input settings.
โ€ข Input System Package (New): Uses the new input system package.
โ€ข Both: Use both systems.

slender nymph
#

as for the play mode button being gone, you can try resetting the layout to default

copper pasture
keen dew
#

Right click where they should be and select Play Mode Controls

copper pasture
#

okay now still the texture doesn't work and the camera is cutting of the model in the center

teal viper
naive pawn
digital oar
#

hello people

#

I'm a kinda experienced programmer tryna learn unity 3d

#

can someone tell me how do I go by learning

naive pawn
#

!learn

radiant voidBOT
naive pawn
swift crag
naive pawn
#

which kinda makes assumptions doesn't it? i feel like it'd be easy to forget about if you add something where the results are, for example, used in different messages

#

just making it an instance member doesn't cost that much extra does it? ๐Ÿค”

#

in exchange for having better separation of concerns - each instance has its own storage

devout otter
# digital oar can someone tell me how do I go by learning

that would depend on a game that youre planning to make, but anyway, its good idea to get some general knowledge at least to basic level especially if you dont know what you want to make. Eventually just start focusing more on the stuff that you need specifically as nobody knows everything and knowing everything doesnt make sense

i personally suggest learning UI because imo its relatively easy and i can hardly imagine a game without UI, probably 99.9% games need it ๐Ÿคทโ€โ™‚๏ธ

errant breach
#

!code

radiant voidBOT
digital oar
#

Basically those crazy hack n slash character action kinda games

vernal vortex
#

Anyone run into the issue of being unable to drag anything from the Project tab to the world scene? Or actually, being unable to drag anything in the Project tab to anywhere else. Unity 2022.3.62f3

warped sierra
vernal vortex
swift crag
#

using a static array makes the method non-reentrant: you can't safely enter it again while it's already running

#

(and making the array an instance member doesn't actually help much there; it just prevents simultaneous invocations of the method on other instances from causing problems)

naive pawn
swift crag
#

if you're writing this code in a message like Update or OnTriggerEnter, then it's actually pretty likely for a static array to be fine

naive pawn
#

i phrased that poorly

#

you need this assumption to have it be static, you don't if it's an instance member

swift crag
naive pawn
#

so what i'm trying to say is, having it be an instance member removes that assumption, at relatively extra little cost

#

i'm not saying the static array doesn't work, but i feel like it being an instance member just makes it harder to accidentally shoot yourself in the foot 2 months from now

swift crag
#

perhaps, but you're also potentially wasting a lot of memory (and, ironically, creating lots of GC churn if these are short-lived instances)

#

I do see the benefit of defualting to something that's safer

#

i guess that, in most of the places where i'd use a non-allocating method, it's extremely obvious that the data is only relevant until the function quits

#

e.g. i have no use for a RaycastHit down the road

#

the hit is only meaningful in the instant that it was produced

swift crag
#

It wouldn't be that hard to abstract all of this

naive pawn
#

mark it transient ๐ŸšŽ

#

ah wait wrong server for that emote

swift crag
#

you'd have a static array that gets used first, and if it's already used, you fall back to allocating

naive pawn
#

uhh read that ๐ŸšŽ as "/s"

swift crag
#

the keyword that does โœจ something โœจ

#

i've read the C# specification and I still can't clearly articulate what it does

naive pawn
#

damnit i guessed wrong ๐Ÿ˜†

#

there's a few modifiers like this in java and i just guessed which one c# probably had lol

swift crag
#

the using keyword is close to what you're thinking of

#

it lets you automatically dispose of something when its scope ends

naive pawn
naive pawn
swift crag
#

oh, that's a serialization thing, interesting

#

i'm surprised that gets to be a keyword

naive pawn
#

yeah

swift crag
#

the main thing volatile does is prevent read/write reordering

naive pawn
#

i hate that i know what that means now.

swift crag
#

(people incorrectly assume that this also provides some kind of "locking" for the field)

frigid marsh
#

everyone can help me my trees are pink

naive pawn
frigid marsh
#

sry where i can ask?

naive pawn
polar acorn
#

If you are gonna ask questions you should probably read replies

frigid marsh
#

I could have known that you can press on it

naive pawn
#

tip: text highlighted in blue is often a link

real thunder
#

If I make a loot you can pick up and it get destroyed, but it also have an expiration timer in which it gets destroyed, will I get an error if those two Destroy calls happen at the same time? Is that a problem?

high marsh
#

Anyone have recommend method to reconnect SerializedField or public reference to object after go to another scene and comeback? Sorry for bad ENG.

naive pawn
naive pawn
real thunder
high marsh
rocky aurora
#

is there a way for USS to apply to mulitple selectors like in CSS?

for example:
.class1 .class2, .class3 .class4

right now I have to create .class1 .class2 and .class3 .class4 selectors separately

swift crag
rocky aurora
#

I guess I have to edit USS in text editor then?

#

ah I tried using list selector but when I opened it in UI builder it just splits into 2 selectors automatically

swift crag
#

makes sense (yet still annoying!)

rocky aurora
#

I guess I won't question it and work around it ๐Ÿ˜‚

#

thank you

swift crag
#

I wonder if you can write the USS separately (so that it's never interacted with in the UI)

rocky aurora
#

probably, but once I include it in UXML and open it in UI builder then it's going to blow it up again ๐Ÿฅฒ

#

I guess this is to support the dragging and dropping of class into UI ๐Ÿ˜ญ but I'll trade that for list selector lol

rocky aurora
#

a workaround: just delete and dupe rule each time I make change to something in the list. not perfect but..

#

unity pls

night cedar
#

How do i run a script?

solar hill
#

depends on the kind of script, but typically its assigned as a component on a game object

shut grotto
#

broo im actually overthinking so hard

rocky aurora
#

๐Ÿ˜ญ why is it so painful to bind non scriptable object to ListView in UI ToolKit/Builder. I've been trying to do it for the past hour

#

I added item source and bind the class that contains the list to it and it's still not working for some reason

sour fulcrum
rocky aurora
#

Ah thank you

#

Yeah my type is list already but the list is a property in a class

prime cobalt
#

Does anyone have advice for how to use less if statements? I know this many nested if statements are bad but I'm not really sure how to do it better and with less.

teal viper
#

!code

radiant voidBOT
teal viper
# prime cobalt Does anyone have advice for how to use less if statements? I know this many nest...

First, you can use && in the if statements to group several conditions together.
Second, you can move the condition checks outside the if statements and only have one if statement for the whole thing.
Third, finite state machine or similar patterns can help organize code flow.
Lastly, your code is not particularly bad in terms of if statements. It's still pretty much readable. And that's the thing that matters.

wintry quarry
prime cobalt
#

UnityChanwow Thanks for the advice!

dark hatch
#

is HLSL obsolete anyhow? or can i still use it for my projects

teal viper
naive pawn
naive pawn
prime cobalt
prime cobalt
verbal dome
#

Also compute shaders and some other features are hlsl

dark hatch
#

it seems its fine now that im reading current documentation

teal viper
midnight summit
#

Good day, I have a small issue with coyote time, it still does a doble jump even after putting the the counter to 0

#

the code goes as follows:


//coyote time vars
public float _coyoteTime = 0.2f;
private float _coyoteTimeCounter;

//ground check inside update
private void Update() {
  GrounCheck();
}

//ground check
void GrounCheck()
{
    Collider2D[] _collider2Ds = Physics2D.OverlapCircleAll(PlayerController.Instance._checkCollider.position, _checkRadius, _GroudLy);
    if (_collider2Ds.Length > 0) //while grounded
    {
        _state.Add(ActorStateFlags.Grounded);
        _state.Remove(ActorStateFlags.Airborne);
        _coyoteTimeCounter = _coyoteTime;
    }
    else //while falling
    {
        _state.Add(ActorStateFlags.Airborne);
        _state.Remove(ActorStateFlags.Grounded);
        _coyoteTimeCounter -= Time.deltaTime;
    }
}

//DoJump func
public void DoJump()
{
    if (_coyoteTimeCounter > 0f)
    {
        Jump();
        _coyoteTimeCounter = 0f;
    }
}

//Jump func
private void Jump()
{             
    _playerCtrl.AnimationStateUpdate(EntityState.Jump);
    _playerCtrl.Rigidbody2D.AddForce(new Vector2(0, _playerCtrl.State.HasAny(ActorStateFlags.AntiGravity) ? -_jumpForce : _jumpForce), ForceMode2D.Impulse);
}
rocky gulch
#

theres a case where you are jumping and the groundcheck still does the check to reset the coyote time

midnight summit
#

where exactly?

#

should I remove the _coyoteTimeCounter = _coyoteTime; when it is true?

swift crag
#

i'm guessing that your "is grounded" check is too generous

#

so that, even though you appear to have walked off the edge (and thus started your coyote-time counter), you're actually still grounded

#

you then perform a normal jump

#

and then your ground check starts failing

#

so coyote time starts

midnight summit
#

hmm well, let me check that out then

timber stump
#

are these channels also related to .shader code or just c# scripts?

swift crag
#

this is intended for scripting

timber stump
#

k thank you

topaz gorge
swift crag
#

the DoJump method does that

swift crag
topaz gorge
#

Or just use a canJump bool, cause as i said there's nothing to stop the continous jumping, and that should only be reset to true when the player is grounded

#
public void DoJump()
{
    if (_coyoteTimeCounter > 0f)
    {
        Jump();
        _coyoteTimeCounter = 0f;
    }
}

This right here only stops jumping after the coyoteTimeCounter is less than or equal to 0, while its bigger than 0 they can jump as many times as they want.

swift crag
topaz gorge
#

Right but the input can happen multiple times before its actually gets set

swift crag
#

How?

#

There is no "gap" between Jump being called and the counter being set to zero

topaz gorge
#

Im not sure, but i typically set something like that above a action, cause fast spam input causes issues within the engine

swift crag
#

It is impossible.

topaz gorge
#

One sec i shall demenstrate

swift crag
#

Even if you immediately call DoJump again after the method returns, the counter will have already been reset.

#

The only possible way for this to happen would be if the Jump method called DoJump

#

which it obviously doesn't

topaz gorge
swift crag
#

right, and that is, indeed, the issue

crystal agate
#

Question, if I made Script A, and in Script A, I had 2 GameObjects: playerPrefab and enemyPrefab, and then in Script B, I wanted to have a GameObject variable, but instead of assigning it manually, I want it to take the one assigned as playerPrefab in Script A, how can I do that?

swift crag
#

Depending on the relationship between these two components, the exact solution will vary

wintry quarry
topaz gorge
wintry quarry
#

example:

public Player playerPrefab;
public Enemy enemyPrefab;

void SpawnPlayerAndEnemy() {
  Player player = Instantiate(playerPrefab);
  Enemy enemy = Instantiate(enemyPrefab);

  // Give the player reference to the enemy so it knows who to chase:
  enemy.Target = player;
}```
@crystal agate
crystal agate
wintry quarry
crystal agate
# wintry quarry That's a separate issue than the one you asked though

my current issue is that I'm trying to have a separate script for handling what each button does, but the IEnumerator commands in BattleSystem are working off references to the player unit, enemy unit, and their stats, while if I move them to a different script they don't have those references

wintry quarry
#

Or making them available in some other way such as via a singleton

topaz gorge
wintry quarry
#

The prefabs are probably not the references that are needed

crystal agate
wintry quarry
radiant voidBOT
crystal agate
#

essentially instead of having IEnumerator PlayerAttack(), I'm trying to make it run the IEnumerator of an Ability script

wintry quarry
#

or you could pass them as params when you create the Ability object

#

Or you could have the ability access the references from the BattleSystem, which could be either passed to the Ability when it's created or accessed as a singleton

#

There are many ways to do this

crystal agate
#

I could try one, unless there's one specifically tidier way than the others

swift crag
#

Abilities are always a fun can of worms

#

especially once you start thinking about how they "target" things

topaz gorge
#

if your not using scriptableobjects already i would highly advise it

crystal agate
#

Question, I mistakenly set dialogueText as Text earlier when it should've been string, but after I corrected it and saved the script, editor still thinks it's Text, how do I fix this?

swift crag
#

That means Unity hasn't recompiled yet.

#

I'm guessing you have a compile error caused by changing the type of that variable

#

look at the Unity Console (or see if your IDE is displaying errors)

crystal agate
#

oh yeah there we go there were some compiler errors, thank you

#

let's just say I want the string to be "You attack " + [enemy name] + " for " + [damage] + " damage!", how do I write it in editor?

#

assuming the quotations change

#

or do I actually have to hard change it in the script

grand snow
crystal agate
#

how's those work?

grand snow
grand snow
thorn hull
#

I have a game where the player talks to npcs and they can enter a sorta rpg battle sequence after in a seperate scene. I need to count how many npcs have been defeated. I also want to mark the npc with a โ€œdefeatedโ€ status so that the next time the player talks to the npc, the dialogue wonโ€™t allow for them to do the battle again if they already defeated the npc. What would be the best way to keep track of that across scenes? Iโ€™m thinking i make some sorta progression manager?

crisp rampart
thorn hull
#

im working on a class project

crisp rampart
#

Which part of the backend(C#) and the frontend(Javascript) do you wanna implement that function in your project?

thorn hull
#

im using C#. Just a windows download. If thatโ€™s what yr asking

crisp rampart
#

Elseif, do you have your own private or public repository for the current project?

solar hill
#

feels like very odd very forward questions

crisp rampart
#

I mean github

solar hill
#

especially since you arent saying why

#

oh nvm i see

#

but i dont think we need to see your repo to give you the answer here lol

solar hill
#

your idea for the progression manager is there

obtuse hollow
solar hill
#

make it ddol

#

is that the quickest and dirtiest solution or is it just not "the solution" lol

#

as for the npcs, have each npc have a unique ID of some kind which you can keep track off inside of the singleton

obtuse hollow
solar hill
#

saving it externally vs tracking stuff like that at runtime are 2 seperate parts here

thorn hull
#

And all the stuff i want to keep track, like adding to the number of npcs defeated and setting the status, will just stay constant betweenthe scenes. Like none of the data will be lost

solar hill
#

if your singleton is a ddol then yes

#

it should

grand snow
#

You can also just keep some data in a static variable, not everything needs to be a monobehaviour

#

But I get it's easier to just work with components as a beginner

obtuse hollow
#

So if you have like a main menu -> go to the game -> do sth -> back to main menu -> back to the game, it will keep everything you put there, but if you reset the play mode or restart the game, it will be lost

#

and ensure that you do proper static management if you are doing it on statics, this can get hectic quickly

eager thunder
#

is it just me or the unity asset third person controller is super jank. i have issues jumping where its delayed, or not jumped at all log gave more then 4 times per input and sometimes just Ignores ground checks

thick halo
#
    void Update()
    {
        if (InputSystem.actions.FindAction("Click").IsPressed())
        {
            Vector3 mousePos = Mouse.current.position.ReadValue();
            Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos);

            Rigidbody2D rb = GetComponentInParent<Rigidbody2D>();
            rb.AddForce(new Vector3(worldPos.x - transform.position.x, worldPos.y - transform.position.y) / 2);

            float distance = Vector3.Distance(transform.position, worldPos);
            Debug.Log(distance.ToString()); //Prints an object
        }
    }
}

Hi. The first few lines are working as it should. Im trying to use the Distance method and then print out the distance but it prints "(object)", not the float. And ofc I want the number. Please help if possible!

rich adder
#

eg Debug.Log($"Distance : {distance}");
also if you add a second parameter with the gameObject or this component it highlights in hierarchy which object called the log

thick halo
#

its the only thing going into my console if thats what you mean

grand snow
rich adder
thick halo
#

๐Ÿคทโ€โ™‚๏ธ I saw there was one better for physics but I didnt care to change it yet

rich adder
#

no they mean you should at very least cache your action

thick halo
#

oh well alright I could do that

thick halo
rich adder
thick halo
#

alright, heard about that, thanks...

half lantern
#

in unity netcode does the lobby system automatically pick a new host when the host disconnects? i have heard conflicting things

topaz gorge
half lantern
#

whats distributed authority mode

topaz gorge
half lantern
#

ohhh

topaz gorge
half lantern
#

so thats not when a player is ahost?

#

im trying to set up host migration with relay by making all clients check if there is a host id change on the lobby periodically. is this a good idea? would this work if player is a host?

topaz gorge
# half lantern so thats not when a player is ahost?

No technically that something you would have to build yourself, so when the host disconnects, on the callback from that you need a select someone to be host load the server up on there game and migrate the other people that were in the original host's game

half lantern
#

in peer-hosted multiplayer, is it a bad idea to have host migration? is it better to just end the match?

topaz gorge
topaz gorge
#

Of course that depends on the complexity of the game

half lantern
half lantern
topaz gorge
half lantern
#

so ig theres no way of making it safe then#

#

would it just be better to end the game if the host leaves

topaz gorge
half lantern
#

ok thank you

topaz gorge
# half lantern ok thank you
Host Migration System:

So all data is stored on each client's game. Object positions, player positions and so on. This is very typical of a game this is why ESP is technically impossible to stop and games use anti cheat 3rd party softwares.

Now when the host disconnects
|
v
OnClientDisconnectedCallback <- This will be triggered, same for if someone else leave's | Now this will only be triggered by either server only execution or host only execution.

Now because it will also be called when other client's disconnect you will need to make sure if it's the host or not.

example:

if (IsHost)
{
  // Do something here
  return;
}

// Do something here for clients

Now if it is the host obviously your gonna have to pick a new one. Now keep in mind because the host is gone doesn't mean the data is gone. Using this before completely exiting the session you can pick the new host | After picking the host you will need to start client migration, by changing there address and port route, and have them try to connect every few seconds -> force the host to load the server / world, When the host successfully loads the server the clients well then naturally connect again. then when server/world load is done all the data you wanted to keep like players positions and rotations ect can then be loaded from there. 
topaz gorge
topaz gorge
stuck palm
teal viper
stuck palm
#

i dont know why

teal viper
#

Did they not exist before you entered play mode? Because it's not clear from the gif.

teal viper
#

How are you instantiating them?

stuck palm
# teal viper How are you instantiating them?
public void AddElement(string buttonText, Action onClick)
    {
        var element = Instantiate(buttonToAdd.gameObject, content).GetComponent<PopulatableDropdownContent>();
        element.SetAction(onClick);
        element.SetText(buttonText);
        ArrangeSelectables();
    }
#

really dont have any idea whats happening here

teal viper
stuck palm
#

content is the second parameter

teal viper
#

Ah, I see now. And content is a reference to the gameobject in the scene? Could it possibly be a prefab reference?

stuck palm
#

this might be it?

#

on the bottom right

teal viper
#

I think it's fine. ๐Ÿค”

#

I know there's an editor preference setting for disabling scene reload on play, but I don't think there's something like that for exiting play mode...๐Ÿค”

#

So, I'd assume it's either a bug or something weird in your project/env.

stuck palm
#

zamn

teal viper
#

Maybe try recreating the issue in a new empty project. If it doesn't happen there, you can at least be sure it's something in your project. Then start investigating it.

#

Checking the console(or even logs) for any warnings/errors around exiting play mode might be useful too.

teal viper
stuck palm
teal viper
#

I see. Even if it's not enabled, there's a slight chance it's messing something up. I'd start with testing in an empty project to see if the issue is reproducible there. If it's not, this asset is the first thing I'd doubt.

stuck palm
#

will do that

stuck palm
#

but the destroy part is still bugged

stuck palm
#

@teal viper not sure whats causing it, but it appears Start is also being called when I exit playmode. I just added this if statement to stop the unwanted behaviour, but its very strange

protected override void Start()
    {
        if (!Application.isPlaying) return;
        print("DROPDOWN CONTAINER STARTED");
        foreach (Resolution resolution in Screen.resolutions)
        {
            dropdown.AddElement($"{resolution.width}x{resolution.height} ", () => {});
        }
    }
teal viper
#

Otherwise it could be called from somewhere else. I'd add a debug log and check it's callstack to make sure.

wicked stratus
#

running into a slight tricky problem with the input system, wondering if it's common and if so, what good solutions for it are: if the player is using a controller, they can aim using the second joystick. if they aren't using a controller at all, I feel it's a safe assumption that calling vector2 aim = playerInput.actions["Aim"]; will return (0,0) if no controller is being used (but also, if no movement on the second joystick occurs, problematic for me sort of). Alternatively, if they are using a mouse, the aim is just wherever the cursor is, and not mapped to my input system aim action. I do not know how to tell if a player is using a controller and just not aiming, vs when a player is using a mouse. is there a way to determine whether a controller is being used, or if a mouse is being used?

deep sphinx
#

About a year ago i made a game called frictionless, i stopped working on it due to school and stress but recently picked it back up agin. or so i hoped. all i had left of it was the built game, not the project, i tried version control but it was a blank scene. i used asset ripper to try and turn it into a project. it somewhat worked, but, the scene is completely flat gray and the game veiw is black. i also dont think the file structure is the same or correct at all. Please help. i need to get this game back.

sour fulcrum
#

Your project is probably gone

naive pawn
#

please do not crosspost.

swift surge
#

hey guys

#

how do i make it so that my character in a top down project rotates where the mouse goes and not the movement?

untold mulch
#

When do they start

limpid sparrow
#

I have a Question, related to the Overlapping Sphere Function. ``` void SearchForTelegrapfen()
{
Collider[] colliders = Physics.OverlapSphere(transform.position, SearchRadius);
foreach (var colliderfound in colliders)
{
if (colliderfound.gameObject.tag == "Telegrapf")
{
TelegrapfenScript teleScr = colliderfound.gameObject.GetComponent<TelegrapfenScript>();
if (teleScr ==null) { Debug.LogError("TeleScript Null"); return;}
if (teleScr == this) { Debug.LogError("Telescript This");return;}

            if (teleScr.TelegrapfPlaced)
            {
                Debug.Log("Telegrapfen found");
                ConnectionManager.Instance.SetUpConnection(this, teleScr);
                ReachableTelegrapfen.Add(teleScr);
                teleScr.NewTelegrapfPlacedInReach(this);
            }
            
        }
    }
} ```This funtion gets called when a new Object is placed, however Sometimes the function does not find all objects. I made a short video so it's more understandable what i mean. I checked in the Inspector, whenever a line is not appearing, the object is not detected by the function properly
sour fulcrum
keen dew
#

Although now that I look at it, the code stops as soon as it hits itself (if (teleScr == this) { return; }). If it's not the last in the array then it won't process the rest of the objects. Those returns should be continues instead

swift surge
keen dew
#

I don't know what you mean by "not the movement" but if you google for "unity 2d rotate towards mouse" there's plenty of guides

swift surge
#

they use the older input system though

#

and i have no idea

#

how to convert it to the newer one

#

in the code

keen dew
#

Then look up how to get the mouse cursor position in the new input system

swift surge
#

doesnt show anything

keen dew
#

What doesn't show anything?

swift surge
#

youtube

keen dew
#

I have no idea what you're talking about

swift surge
#

....what..

#

oh my god

#

cant be fr with this ๐Ÿ˜ญ

sour fulcrum
swift surge
#

i did

sour fulcrum
#

is your problem resolved

swift surge
#

no

stuck palm
swift surge
narrow idol
teal viper
swift surge
narrow idol
swift surge
#

pretty much

narrow idol
#

lol, me2. i recently finished the Unity Essentials pathway from Unity Learn Pathways, now i'm going to be doing programmer pathway

narrow idol
swift surge
#

okay

narrow idol
#

then select pathways

swift surge
#

is it paid or?

narrow idol
#

free

swift surge
#

cause im broke for now

#

oh

#

good

stuck palm
#

but either way it shouldn't be a problem with this guard rail, and it won't be a problem in the game build either I imagine

teal viper
#

Is the log actually being printed on exiting play mode?

stuck palm
rocky gulch
#

As a temporary fix sure, but you are avoiding the issue which is start being called when exiting playmode

grand snow
#

Unity should not be doing this but adding a breakpoint will let you detect this happening with ease

#

Unless something is creating this component on play mode exit? OR this is the scene being re created and its ExecuteAlways

#

who knows

rocky gulch
#

adding a breakpoint will let you detect this happening with ease
i thought the editor console already shows you where its being called from, thats new

grand snow
#

Id rather use a debugger than add a log to meerly check when something is called

cursive saddle
#

Hey everyone,
Iโ€™m working on a pirate game project, but Iโ€™m having a lot of trouble fixing player jitter while standing or walking on the ship in the ocean.
Right now, the character feels like itโ€™s constantly shaking a little, and walking around on the ship feels pretty unstable. It gets even harder because the game is multiplayer, and Iโ€™m using FishNet for networking.
How would you approach this kind of system? What would be a good way to make walking on a moving ship feel smoother and more stable for all players?
Iโ€™m mainly looking for ideas or implementation approaches to reduce jitter and make the movement feel cleaner.

grand snow
#

Perhaps when on a ship player positions should be relative to that? I remember seeing something about some other game with how it handled this but i forget where

warped sierra
#

I tried to create a template (and upload it to GitHub) but it got stuck in the second stage

#

I think it was due to lack of space, it's over now

sharp bloom
#

If it requires a reference to the target anyway, way not just call the function directly instead of going through this message middleman?

keen dew
#

The point is that the target may have zero, one, or more components that can receive the message, and the message sender doesn't need to know about them. It can just broadcast the message and not care if there's something there that wants to do something with it

swift crag
#

The SendMessage system requires reflection to find the target method by name

polar acorn
#

(You should probably just call the method directly still, though)

keen dew
#

If you have a situation where you want to call a specific method

cosmic dagger
#

I don't understand the if statement. The if and else block have the same code . . .

nocturne kayak
#

oh yeah dont worry about it , that's for later , but is allocating variables inside this IEnumerator something wrong ?

nocturne kayak
#

sry i need to find a website to past this

cosmic dagger
radiant voidBOT
nocturne kayak
cosmic dagger
#

No problem. It's definitely much easier to look at . . .

nocturne kayak
#

uh i have some problem it dont copy the link ๐Ÿ˜ญ

rich adder
nocturne kayak
#

i dont really know how i'am gonna be moving the balls has it is in a function

rich adder
#

if you want accurate physics don't use Translate

nocturne kayak
nocturne kayak
cosmic dagger
rich adder
#

you're essentially teleporting it bypassing physics, occasionally it might catchup to do something but mostly inaccurate

nocturne kayak
cosmic dagger
#

And they are right. It doesn't make sense to have access to or use a Rigidbody variable if you're moving the object with Translate. That method will override any physics applied to the game object . . .

nocturne kayak
#

okay thank you guys i will be changing that !

rich adder
#

fun fact . if you declare InitialBallPrefab as Rigidbody you can spawn it directly as rigidbody instead of doing GetComponent

#

InitialBallRigid = Instantaite(InitialBallPrefab, etc..

#

use AddForce or Velocity in most cases

#

i'd also be careful calling StartCoroutine in Update without more safeguards..

nocturne kayak
#

for loop i guess

crystal agate
#

So, currently I have this script that decides through random numbers which attack an enemy will use. However, it seems that it only rolls a number the first time around, and will keep using that move forever. How do I make it roll for a new number every time?

keen dew
#

Random.Range(0, 1) will always return 0. If you want either 0 or 1 it has to be Random.Range(0, 2)

#

Also whenever you have numbered variables, it would probably be better to use an array

swift crag
#

(and then you can simply do Random.Range(0, abilityArray.Length))

wintry quarry
#

absolutely! With Fen's suggestion you can cut your code in half here

crystal agate
wintry quarry
#

With a list or an array and what Fen said

crystal agate
#

currently if I have 4 ability slots and only fill 2 it just gives me a null reference exception

wintry quarry
#

use a list

#

Does your character have a fixed number of slots or something?

#

and do they have to be contiguous or is it possible to have:
[ability] [empty] [ability] [empty]

crystal agate
#

I'd say it would be possible yeah

swift crag
#

arrays let you store a flexible number of objects

#

if you have four distinct variables, then you have to write code for each of those variables

#

importantly, this suggests that each of those four variables is "distinct" in some way (after all, you're writing unique code for each one)

wintry quarry
#

here's the simple example with a List, not allowing empty slots:

List<Ability> myAbilities = new();

// make sure you populate the list

void DoRandomAbility() {
  int randIndex = Random.Range(0, myAbilities.Count);
  Ability ability = myAbilities[randIndex];
  dialogueTeext.text = ability.buttonName;
  if (ability.target == SingleEnemy) {
    ability.useAbility(playerUnit);
  }
  // etc.
}```
swift crag
crystal agate
swift crag
#

if not, then you can at least do something like this

wintry quarry
# crystal agate I'd say it would be possible yeah

If you can have empty slots it's a little more complicated, but if the number is only up like 4 you can do something like this and it will be just fine

int GetAbilityCount() {
  int count = 0;
  for(int i = 0; i < myAbilities.Length; i++) {
    if (myAbilities[i] != null) count++;
  }

  return count;
}

int GetAbilityAtIndex(int index) {
  int count = 0;
  for(int i = 0; i < myAbilities.Length; i++) {
    if (myAbilities[i] != null) {
      if (count == index) return myAbilities[index];
      count++;
    }
  }

  throw new IndexOutOfRangeException();
}```
Then you can proceed as in my above example but use these two instead of .Count and the indexer
swift crag
#

you only write unique code for the unique parts

crystal agate
wintry quarry
#

highly recommend this

#

arrayify or listify all of ti

#

so you only need to write code once

crystal agate
#

Thank you!

jovial heron
#

even when i added [SerializeField] to the public movement it doesn't show in inspector\ (pieceMovement is a plain C#)

slender nymph
#

does it have any fields that can be serialized? the screenshot only shows a method, which obviously wouldn't appear in the inspector

jovial heron
slender nymph
#

it's not a component so what exactly are you expecting to drag in?

jovial heron
slender nymph
#

what would you drag in that case?

#

an instance of a plain c# class doesn't exist as a draggable object anywhere in the editor

#

that only works for things that inherit from UnityEngine.Object because those typically exist as objects you can interact with in the editor

jovial heron
#

oh ok so i should just make it a monobeahviour?

slender nymph
#

if it needs to be a component in the scene, yes make it a monobehaviour. otherwise you might want to consider a scriptableobject

jovial heron
slender nymph
#

is it just the one method? because it doesn't appear to have any instance data so the method could just be static

#

but also from what i see of the method in the screenshot above, this seems like a poor way of handling the movement in the first place

rocky gulch
#

If its for like a strategy pattern then have some factory or just do new PieceMovement() for now ๐Ÿคทโ€โ™‚๏ธ

jovial heron
#

i'm a beginner so it shouldn't be too complicated of course

slender nymph
#

not shoving all of the different movement types into a single method, but rather use a base abstract class (that inherits ScriptableObject if you want to drag things in the inspector), then inherit from that for each individual type of movement

#

i might even allow multiple movement types to be set on a single object too so that you aren't duplicating code for things that share movement types (like the queen shares movement with rook and bishop, so it would have the two movement types that are associated with those on it instead of one single queen movement type)

jovial heron
jovial heron
slender nymph
#

really you just need 3 movement types, diagonal, horizontal/vertical, and knight where the first two specify the distance along each axis is permitted. plus any special moves (castle, en passant, etc)

limpid sparrow
#

Can i modify this function, so that the object is spawn on the surface of the collider. public void MoveCurrentPlaceableObejectToMouse()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    RaycastHit hitInfo;
    if (Physics.Raycast(ray, out hitInfo, Mathf.Infinity, layerMask)) //Mouse hit Collider
    {
        currentPlaceableObject.transform.position = hitInfo.point;
        currentPlaceableObject.transform.rotation = Quaternion.FromToRotation(Vector3.up,hitInfo.normal);
    }
}

currently it's the middle point on mouse point

rich adder
#

Vector3 offset = hitInfo.normal * groundOffset;
you're better off using bounds though, so its more flexible and not a fixed value

rancid wadi
#

From where should I actually start learning?

slender nymph
#

!learn

radiant voidBOT
prime cobalt
#

I'd like some advice on how to structure something if possible UnityChanThink

I've got a few core movement mechanics, (slide, jump, and wall run) and they all have variations for if you combine them, (for example if you slide and wall run you wall slide, and if you jump while wall sliding then you get a special directionally boosted jump).

I want to have things like sliding and wall running be more modular and exist in different scripts, however I'm not really sure how i should structure the way the main script chooses which movement mode to use. I could do like a massive amount of if/else statements for like

if(wallRunning.wallRunCheck() && inputManager.slideInput.action.IsPressed() && inputManager.jumpInput.action.WasPressedThisFrame())
else if (wallRunning.wallRunCheck() && inputManager.slideInput.action.IsPressed())
Else Etc, etc...

But that seems like it would create a pretty massive and unwieldy series of checks. Anyone have advice for how to do that better?

solar hill
#

i dont think these kind of things should live on different scripts in my opinion

#

a single centralized "playercontroller" is enough

rich adder
#

how can we possibly tell that if you show nothing of the code / setup ?

solar hill
#

it also looks like its consistently jittery

#

and seeing the edge of the wall just makes it clear how jittery it actually is

prime cobalt
solar hill
#

theres some things you want to keep in seperate scripts... but for movement its overkill

rich adder
#

!code

radiant voidBOT
rich adder
#

also first thing obvious is that you're multiplying mouse input with DeltaTime which should not be done at all

#

mouseInput is already the delta (change) between frames

swift crag
#

specifically: mouse input tells you how far the mouse moved; it's not how fast the mouse is moving

#

those sorts of inputs need to be multiplied by deltaTime

halcyon lake
#

In case I get 2 collider requests at the exact same time, how can I do to accept only one?

frosty hound
#

Nothing happens at the exact same time, one will always happen before the other.

#

So if you don't care which it is, it's already handled. Otherwise, have the collider pass itself up to a controller to notify it's been hit.

halcyon lake
wintry quarry
#

You'll just get one after the other

#

If you really want to disambiguate you can store data about the hit in OCE and then process it in the next FixedUpdate

#

e.g. make a list or set of Hit datas, and process them later

halcyon lake
#

nvm I think i found the issue

#

also

#

i think im the dumbest person to ever touch unity

swift crag
#

importantly, they won't actually happen simultaneously

#

one message will be sent before the other

halcyon lake
cunning bramble
#

Hey guys, i am currently working on my Character customizer and i have an problem with the Eyelids of the character. I wanted to make an slider to lower and higher it but the Rotation changes not only X axis and now i have no clue how to make an slider that controlls that notlikethis
(Pls ping me)

Would be very nice if anyone would help me UnityChanThumbsUp

halcyon lake
#

again, I tried using bool, thinking its a casual race condition, but it didn't work

fickle plume
swift crag
#

notably, I don't see any boolean variables in that code

cunning bramble
halcyon lake
#

also I want to point out that Blue: 1 means that the episode ended instantly (a new episode to be specific)

halcyon lake
swift crag
#

well, i can't tell you what was wrong if you deleted it!

halcyon lake
#

ok, Ill readd it

swift crag
#

it looks like you instantly call GameOver, which, in turns, resets the ball

#

however, unity isn't going to stop processing the collision messages just because the ball got moved

#

so the second message gets sent, and RaceCondition is once again false

halcyon lake
#

right..

#

but how do I stop the second message then?

swift crag
#

one option would be to reset RaceCondition inside of the FixedUpdate method

halcyon lake
#

ok, that solves it

halcyon lake
#

also is it better to use [SerializeField] than getting the objects using GetComponentsInChildren/GetComponentInParent?

#

like, is it faster?

slender nymph
#

SerializeField since it won't need to search for the component it will just have the reference to the correct one(s)

swift crag
#

it's faster, but more importantly, it's more reliable

ivory bobcat
# halcyon lake like, is it faster?

Performance is to be considered but more importantly, explicitness. With reference via serialization, you're certain that the field would have been set from the inspector. Component checking is fine but it's more automated and has some runtime uncertainty.

marsh stump
#

guys im having a issue in the unity engine where my chracter is constantly moving to the right i thibk its from a ghost controller? can some one help me

fierce shuttle
tall brook
#

guys how do i make game

rocky gulch
#

!learn

radiant voidBOT
keen bridge
#

Hello,

I am currently making a drag and select system in my game, I am making my UnitSelectionManager a singleton as I only want to allow one of these per game instance. However, because of this code I am getting an error saying it is null, because the Awake function in SelectableUnit is running before UnitSelectionManager has chance the set the current Instance. What can I do about this?

NullReferenceException: Object reference not set to an instance of an object
SelectableUnit.Awake () (at Assets/Code/SelectableUnit.cs:10)

UnitSelectionManager.cs

public class UnitSelectionManager : MonoBehaviour
{
    public HashSet<SelectableUnit> AllUnits = new();
    public static UnitSelectionManager Instance;

    private void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
            return;
        }

        Instance = this;
    }

SelectableUnit.cs

public class SelectableUnit : MonoBehaviour
{
    [SerializeField]
    private GameObject SelectedUnitIndicator;

    private void Awake()
    {
        UnitSelectionManager.Instance.AllUnits.Add(this);
    }
rocky gulch
sour fulcrum
#

Assign the singleton in a getter

marsh stump
sour fulcrum
#

phone pseudo but eg.

public static UnitSelectionManager Instance
{
get
{
if (instance == null)
instance = UnityEngine.Object.GetAnyObjectByType<UnitSelectionManager>();
return (instance)
}
}

keen bridge
#

thanks guys, will take a look into those solutions ๐Ÿ™‚

#

Why is my unit not moving? I have baked the navmesh and applied a navmesh surface to the ground plane, and added an agent to my unit. ๐Ÿค”

    private void HandleMovementInput()
    {
        if (!Mouse.current.rightButton.IsPressed()) return;
        Vector2 mousePosition = Mouse.current.position.ReadValue();

        foreach (SelectableUnit unit in SelectedUnits)
        {
            if (unit == null) continue;

            unit.MoveTo(mousePosition);
        }
    }
#

the function that runs moveto is running, the code is being reached.

thorn holly
#

i making a 2d map that basically wraps around to the opposite side when the player gets to the edge. i did this by splitting the map into chunks and then teleporting each chunk to the other side once its too far away from the player. i did this teleportation by just setting the transform.position of everything within that chunk, including the map, enemies with rigidbodies and colliders, etc. would this create any problems or desyncs physics wise? since im setting transform.position it should essentially just be a teleport and the physics wont break on me right?

#

oh and also should i put the teleport code in update or fixed update?

#

i also cant really try it and see since if theres any desync it would resolve itself really fast, the desync would only be problematic (and noticable) in edge cases

#

basically what im asking is is it ok to set the transform.position or do i need to set rb.position as well? or something else entirely?

cursive saddle
#

Hey everyone, howโ€™s it going?
Iโ€™m trying to figure out the best way to handle player movement on a moving ship, so I decided to ask for some advice here.
Iโ€™m making a third-person pirate game, and I need the player to smoothly follow the shipโ€™s movement while still being able to walk around on it normally.
You can think of how player movement works on ships in Sea of Thieves, for example. Thatโ€™s the kind of feeling Iโ€™m trying to achieve: stable, smooth movement on a moving boat without jitter or weird sliding.
How would you approach this system? Would you use parenting, velocity compensation, custom character movement, or something else?
Thanks in advance for any help!

blazing horizon
#

Quickie: how do I debug what is the mouse currently hovering over? I'm trying to find what is stealing my clicks.

frosty hound
#

Select the event system object in your scene, it'll have some debug information included what's bring clicked.

grand snow
#

(unless you are using new input system cus its been broken there for ages)

light ledge
#

Is "null" = 0 ?

naive pawn
light ledge
#

i mean like its the same with 0 ?

keen dew
#

no

naive pawn
#

it is not, no

light ledge
#

ok

#

im new at programation

midnight tree
#

null = nothing
I mean 0 is actually nothing but in programming it means parameter has no value.

half jetty
grand snow
#

The real explanation is in c/c++ we say a pointer with a value of 0 is a "null pointer"

#

This applies to reference types, if they "point" to nothing they are null

#

best not to go into it more it will just confuse beginners

agile ibex
#

hi
im learning input system
what does this error mean

#

object reference not set to an instance of an object

#

like i left a field empty somewhere?

#

or maybe how i tried to create a function

polar acorn
half jetty
# agile ibex hi im learning input system what does this error mean

thats a classic NullReferenceException error, youre probably trying to use input system variables that werent initiated correctly. heres whats happening:
in the Start() method, you tried to search the actions:

moveFwd = InputSystem.actions.FindAction("MoveFwd");
moveBack = InputSystem.actions.FindAction("MoveBack");

the issue is in line 28 (in VerticalInput), because one of these variables (moveFwd or moveBack) is null. im not sure how to fix it but hope it helps!

agile ibex
polar acorn
#

Try logging them to find out which is null

agile ibex
#

oh

#

it reset whatever i had yesterday

solar hill
#

you might have saved a new one

agile ibex
#

i have no idea how to save them

#

i copied it and saved it as a text file in case it happens again

#

im really not sure of anything right now tho

#

my controller does this silly thing where when i release it, it doesnt go back to 0

#

it's like 0.35

edgy tangle
#

You should confirm that it is indeed happening at the level of input and not something caused by your code. If you confirm that then you can introduce a dead zone for the sticks

#

E.g. if input axis is <= 0.4 it just counts as 0

agile ibex
#

this is how im checking it right now

#

read value for button

#

i have lots of things going wrong im figuring out lol

scarlet skiff
limpid wren
#

I might have a ghost-in-my-machine type issue here, but just for clarity, Unity doesn't do some kind of magic with Monobehaviors where it automatically instantiates member variable lists and such, right?

I have a declaration: List<Vector2> currentPath;
And in "Awake" that currentPath is already listed as a list with count=0

#

currentPath is private so nothing else can touch it

naive pawn
#

it may be that it was previously serialized so the serialized version still has a list that gets injected

limpid wren
#

It isn't serialized... Or shouldn't be, anyway

naive pawn
limpid wren
#

How do I check the raw yaml?

naive pawn
#

locate the file in question and open it in your ide rather than in unity

#

you may need to configure what files are hidden/shown

#

i'd need more context to give more specific instructions

scarlet skiff
limpid wren
naive pawn
limpid wren
#

So open the scene file in Visual studio and look around for the object that may have serialized the data

naive pawn
#

it'll have a lot of stuff, so you wouldn't really "look around" lol

#

could try searching for other members of that monobehavior that you know are serialized, or the component id from the script's meta file, or via the GO's name and then going through its transform then components

swift crag
#

unity serializes private members for the sake of the debug inspector

#

i don't believe it will actually write anything into the file on disk

naive pawn
swift crag
#

(also, it wouldn't matter if there was data for the currentPath property in the file โ€“ unity will ignore anything that it's not explicitly told to serialize)

swift crag
limpid wren
#

Because it automatically serializes them?

swift crag
#

private int x; doesn't get populated even if the serialized data includes a value for x

limpid wren
#

There is no visual "currentPath" in the inspector, yet at that "awake" call "currentPath" is not null

naive pawn
#

that's nice to know

#

real quick, how did you check that

limpid wren
#

So something is definitely instantiating between those two points

naive pawn
#

just as a sanity check

swift crag
swift crag
swift crag
naive pawn
swift crag
#

ah

#

Unity is still serializing the field (strictly for the sake of showing it in the debug inspector, afaik)

#

I reproduced the behavior on my own

naive pawn
swift crag
#
public class Foo : MonoBehaviour
{
    private List<int> items;

    void Awake()
    {
        Debug.Log(items);
    }
}
scarlet skiff
swift crag
#

This caused me a huge headache at one point. I was getting garbage InputActionReference data

swift crag
#

I don't fully understand this "half-serialized" behavior โ€“ e.g. i don't know what happens in a built game

#

it scares me

limpid wren
#

Uh, ignore the Rem I guess

naive pawn
#

you should probably put in a layermask there to filter for what to hit

#

arguably obstacles could be a layer rather than a component as well

limpid wren
swift crag
#

oh, i see; they're on the top of the square

naive pawn
#

btw you don't need to put a ternary on direction, you could also just do Vector2.right * direction

swift crag
#

A 2D raycast will ignore any collider that it starts inside of by default. I wonder if you're skipping over the wall completely

scarlet skiff
#

u just realized its hitting its wn collider

scarlet skiff
#

added bunch of debugs

#

result

limpid wren
#

What happens if you breakpoint in here when it should collide?

scarlet skiff
#

"TestEnemyV2(Clone)" is name of the enemy

fickle spire
#

Huh

#

Wait this is unity

naive pawn
scarlet skiff
#

thing is i cant make obstacles their own layer becuase some obstacles are "ground" also

limpid wren
scarlet skiff
#

i suppose i could still change them to that, and then change ground dependant logic to also account for obstacles that should count as ground

limpid wren
#

I suspect you're hitting something else that's blocking your ray

#

And that object isn't an obstacle or ground.

scarlet skiff
#

yes i figured it out its the enemies own collider

slender nymph
#

use a layermask that doesn't include whatever layer its own collider is on

naive pawn
scarlet skiff
# naive pawn but the enemy isn't an obstacle nor the ground, is it

yes, i do have an enemy layer but i had a whole thing with it i had planned to use it in some way specific i think so i also was looking for other solutions, i settled with moving the start point by 0.01 forward so we dont start by grazing the enemies own collider, and it works

limpid wren
#

So you could layermask so you only collide with "obstacles" or "ground"

agile ibex
#

how do i access this value in another script

swift crag
agile ibex
#

thank you !

agile ibex
#

im stuck on this bit

#

i dont think i can just treat that as a uhh

#

child of the vehicle

#

or

#

if vehicle is the target

#

i guess i put it under the main camera somewhere

#

like the tutorial had me do earlier

#

but i dont know if i can access the vehicle script's variables from the camera script

swift crag
#

you've boxed a single property of the Player Controller component

#

you aren't referencing that

#

you are referencing the entire Player Controller

slender nymph
#

you need to store a reference to the vehicle's script, you can't reference a float

swift crag
#

given access to the player controller, you can read its "speed" field

fierce coyote
#

Where is the make game button that makes the game for mw

agile ibex
#

i think i already have it then

#

player

slender nymph
#

player is a GameObject variable, you can call GetComponent on it to get the PlayerController component, or you should just reference the PlayerController component directly rather than using a GameObject variable

#

in fact, making that variable a PlayerController won't even change the existing code at all

agile ibex
#

if i select it from the project panel

slender nymph
#

this isn't the place to shitpost

#

<@&502884371011731486>

agile ibex
slender nymph
#

yes

agile ibex
#

oh okay

slender nymph
#

the transform property is just a reference to the Transform component on the gameobject. all GameObjects and components will have a reference to the Transform component that they are attached to. so all components on that same object will all point to that same Transform component

swift crag
#

it's equivalent to writing whatever.GetComponent<Transform>()

#

Unity used to have a bunch of these properties, like light and rigidbody, but those were removed

#

the only other component guaranteed to be on an object is the Transform

agile ibex
#

got it

#

im trying to make the camera that follows my truck get closer or farther depending on the absolute value of the speed

#

partial success

slender nymph
#

what is the very first error in the console

agile ibex
#

the referenced script (unknown) on this behavior is missing

#

that's the warning

#

everything else is this lol

#

i just made the formula wacky

naive pawn
#

NaN, Inf, and -Inf, the trifecta of nonfinite values lmao

agile ibex
#

had no idea it would be that wacky

#

i forgot absolute value

#

and i swapped a couple terms

naive pawn
#

it couldve been (0, <some positive value>, <some negative value>) / 0

agile ibex
#

got it

#

oh

#

there's a whole channel dedicated to the input system

wild fox
#

can someone help me? How to I flip a 2d character using the new input manager? everywhere I look online it just shows ways with the old one

naive pawn
#

changing input systems just changes the part of receiving input, the flipping part will be the same

naive pawn
#

from the mathematics library?

#

i guess so

#

typically you'd use Mathf from unity

agile ibex
#

oh okay

#

yea i just guess how things work

#

looks like it auto imported the math library

#

that's nice

naive pawn
# agile ibex got it

๐Ÿค” is this supposed to be applying extra offset or lag when the player goes a certain speed?

i'm confused what's going on there. speed shouldn't be negative to begin with, and for this calculation i feel like using the signed vector velocity would make more sense

agile ibex
#

lol i know

#

scalar doesnt work like that

#

negative speed is when it reverses

naive pawn
#

that's not speed then

#

speed is nondirectional, that'd be velocity

agile ibex
#

vector1

naive pawn
#

no, that's not what i'm talking about

#

typically, "speed" should not be negative

#

if it can be negative to indicate direction, that's velocity

swift crag
#

eh, "forward speed" is often implied by "speed"

#

in which case it's fine to say the speed is negative when you're going backwards

swift crag
naive pawn
swift crag
agile ibex
#

where

swift crag
#

in the screenshot that i replied to

#

every value was zero, actually

agile ibex
#

oh

#

i set it in the code

naive pawn
#

when dealing with physics, using non-typical definitions can very easily get very confusing ime

agile ibex
#

when i declare the variable

swift crag
#

that does not matter!

naive pawn
swift crag
#

the field initializer is only used when creating a new component or when resetting it

#

Unity will overwrite whatever the defaults are

#

(based on the values shown in the inspector)

agile ibex
naive pawn
#

those values aren't used

#

they're only defaults when you create the component

#

the value in the inspector is what matters - hence, you should use the inspector to set this stuff

swift crag
#

it doesn't matter that the default value of maxSpeed is 70; Unity is setting it to zero because that's what you put in the inspector

#

(or, more accurately, it's what showed up by default in the inspector, since you must have added that component before putting the field initializers in)

agile ibex
#

it works how it should though

#

well let me make sure

swift crag
#

without seeing the rest of the script i can't say much

agile ibex
#

yeah it stays at 70

#

ill set it in the inspector though

#

that way it doesnt need to re-compile every time i change something

swift crag
#

ah, you had them set to zero on a specific instance of the prefab

#

notice the blue lines on the left side

wild fox
swift crag
#

the original prefab had the values you wanted

swift crag
#

but, again, as Chris said: flipping the character has nothing to do with how you get input

wild fox
#

well that's how I've seen people do to check which direction the character is moving

naive pawn
#

this doesn't have anything to do with flipping the character though. from that you'd get a float, and then you'd use that float to decide to flip the character or whatever

changing input systems only changes how you get the float

swift crag
#

think about what that actually means

#

you don't flip the character because Input.GetAxisRaw("Horizontal") is a negative number

#

you flip the character because the player is trying to move left

naive pawn
wild fox
#

how do I check which side the character is facing? I know you flip it with the flipX

naive pawn
#

you can store it yourself, or you can read back what flipX currently is

#

(this part doesn't change when you switch input systems)

wild fox
#

oh geez, how do I make the check of which way the character is moving? Like, how do I check if the character is moving left or if it's moving right? That's what I mean

#

that's the part that I found to be input method dependent

swift crag
#

Are you able to move the character at all right now?

wild fox
#

yes