#💻┃code-beginner

1 messages · Page 547 of 1

verbal dome
#

Yeah

rare basin
#

i'll definitely watch some guides about that pattern

#

ty

verbal dome
#

I worked on Medieval II: Total War, The Bureau and Bioshock: Infinite.

swift crag
#

in my game, everyone is an Entity

#

Entities experience perceptions that can be attributed to other Entities

#

Entities make decisions based on these perceptions and their memories (e.g. they can be friendly or unfriendly to one another based on prior events)

rare basin
swift crag
#

So there's no special "Player" class at all

swift crag
#

One thing I don't really get about the whole "blackboard" idea is how it's not just a Dictionary<string, object>

rich adder
swift crag
#

Keeping your keys and values in order sounds very annoying

verbal dome
#

Then methods Get/SetInt/Float/Vector3

#

And a dictionary for object for when it is absolutely needed

#

Idk how I'm going to serialize that yet tho..

swift crag
#

what are some things you store in these dictionaries?

verbal dome
verbal dome
#

I think I just futureproofed

#

But it could be any data that doesnt fit into the other types

swift crag
#

I may have just constructed a "blackboard" in a slightly roundabout way, with things like:

  • Perceptions (I experienced a strong visual stimulus that I associated with Bob)
  • Relationships (I am afraid of Bob)
  • Motives (I am fearful right now)
  • Traits (I really hate being fearful)
naive pawn
#

what did Bob do 😭

swift crag
#

well that's down to the Inclinations!

#

those provide default relationship values based on qualities of the other entity

#

I'm running out of nouns, help

verbal dome
#

I don't actually store everything in the blackboard, I do have data types like TargetInfo which stores the detection state, aggression, observed actions etc. per each NPC's target

swift crag
#

I've just struggled to imagine how I'd enjoy using a "blackboard", since it's this giant bag of completely random values with no structure

verbal dome
#

Yeah exactly

#

Thats why I didnt shove everything in it

swift crag
#

It makes sense for the entity to have a pool of knowledge

verbal dome
#

I mostly use the blackboard for evaluating Utility AI

swift crag
rare basin
#

okay so i've break my code into more modular pieces, i've created ITarget IDamageable etc. So for example if i have Player: Character, ITarget, IDamageable, and then if i store ITarget currentTarget in my Enemy, can i do if currentTarget.GetComponent<IDamageable> (...)?

#

would that work?

rich adder
#

its not a Component

rare basin
verbal dome
#

You can!

rich adder
#

oh rly?

verbal dome
#

Sure

swift crag
#

(well, if you cast it)

rich adder
#

nice. I usually just make a Prop for it

#

GameObject Object => gameObject

swift crag
#

Ooh, I just realized that you could add members to the interface that match what MonoBehaviour already has

rare basin
#
using UnityEngine;

public interface ITarget 
{
    GameObject gameObject { get ; } 
}
swift crag
#

IComponentLike

rare basin
#

can I just do it like that?

verbal dome
swift crag
#

for things that are shaped like a Component

slender nymph
#

yep, exactly what i was about to suggest. can just throw the getcomponent declaration on the interface

rare basin
#

and then if (gameObject.GetComponent<IDamageable>)

swift crag
verbal dome
#

Why'd you need to, though

#

Just use the interface

swift crag
#

after adding the relevant members to the interface, yeah

#

my first thought did not involve changing the interface

#

(bad)

slender nymph
# verbal dome Just use the interface

because you can't call GetComponent on the interface without it either being declared as part of the interface or being cast to an object that has the method on it. you can call GetComponent to get an interface which might be what you were thinking of

verbal dome
#

Ohh, on the interface yeah i misread

rich adder
#

yeah I think there was confusion, you can GetCompeont <interface> you cannot interface.GetComponent

verbal dome
#

Nevermind me 🤦‍♂️

rare basin
#
using UnityEngine;

public interface ITarget 
{
    GameObject gameObject { get ; } 
}

if (gameObject.GetComponent<IDamageable>)

#

that works?

polar acorn
#

yes

rare basin
#

perfect

#

ty

rich adder
#

use proper capitlization for props

polar acorn
#

it will get any component that implements that interface

rare basin
#

i think it has to be lower case @rich adder

polar acorn
#

I would not recommend using the name .gameObject though, since all components already have a property of that name

verbal dome
#

When added to a monobehaviour

swift crag
#

Indeed.

swift crag
#

I somehow never thought of that

rich adder
#

oh had no idea it autoimplemented

rare basin
#

got it from stackoverflow, is this like outdated?

swift crag
#

I've really wanted to be able to make an interface that demands an object be...Component-shaped

rich adder
#

I wasted my time doing GameObject Object => gameObject 🥲

verbal dome
#

I used to make interfaces with GetGameObject() methods before I realized I can just add a gameObject property, which is already implemented in a MB

swift crag
#

Oh my god how did I never think of this

rare basin
#

lol glad i could help you think of something 😄

polar acorn
rich adder
#

hehe look at us learning new things every day

swift crag
#

I must have thought "but I couldn't implement the member myself..."

polar acorn
#

I've never thought of doing that either...

rare basin
#

exactly

swift crag
#

But you don't have to! Your type just has to have the member

#

Hence why you don't use override when implementing an interface

rich adder
#

game changer 😎

polar acorn
#

I have always just passed it in as a parameter, or made a new member

swift crag
#

you aren't overriding an abstract member. you're just meeting the criteria of the interface.

#

Now, this does still leave you with the bugbear of not being able to serialize interface types

#

But there are some workarounds..

steep rose
rare basin
#

so that way i can store ITarget and just check if that ITarget also implements IDamageable interface etc, just by doing if(currentTarget.gameObject.GetComponent<IDamageable>), or TryGetComponent right? no need to initialize that gameObject anywhere?

swift crag
#

Bingo

rare basin
swift crag
#

target.gameObject is accessing the gameObject member of whatever MonoBehaviour-derived type of yours implements the ITarget interface

rare basin
#

that's sexy lol

swift crag
#

And, if you decide you need some kind of "abstract target" that isn't actually a component, you just need to implement the gameObject property yourself

#

That might get icky if you decide you have to just return null

#

But I dunno if that would even happen in practice

#

Something I've learned over time: You have to draw lines in the sand about abstraction

#

"Yes, every target IS associated with a game object"

rare basin
#

right

swift crag
#

When you get more abstract, you're giving up on some capabiliities in exchange for being able to work with more kinds of things

#

if you go too far it decomposes into doing nothing to everything

#

very cool

#
public void PlayGame() {
  return;
}
ancient hamlet
swift crag
#

"Them"?

#

interfaces, you mean?

ancient hamlet
#

interfaces yeah

swift crag
#

Yeah, that's the idea.

rare basin
#

that's also confusing atleast for me at the stary of my journey

#

when to use abstract classes instead of interfaces

swift crag
#

You assert that you only need a few capabilities.

#

Now you can operate on anything with those capabilities.

rare basin
#

is it just preference most likely

swift crag
#

But you can't do anything else!

rich adder
swift crag
rare basin
#

so like Animal, Dog : Animal

#

get it, but i could also do like IAnimal?

swift crag
#

right, although the classic animal hierarchy falls apart really quickly

verbal dome
#

Do you people use default interface implementations?
Just realized I have still not used those

swift crag
#

They're mostly useful for inserting new members into an interface without breaking anything

rare basin
#

there is so much to learn about proper approch/patterns and this is terrying me 😄

#

when to use factory pattern, when to use this when that etc

#

i am spending more time designing my systems instead of coding them and learning

#

thinking im doing it "the wrong way"

swift crag
#

at some point you have to Make The Damn Game

rich adder
ancient hamlet
verbal dome
#

Most of my larger systems I have rewritten from scratch about 2-3 times before I got enough experience to do it right from the get go

rich adder
#

its a trail and error thing, see what works best for your projects eventually

#

you learn by making your mistakes and correcting them on the next iteration

ancient hamlet
#

hopefully not on production

swift crag
#

going from game to game, gradually refining the idea

#

My settings system is the result of like...four different projects

#

I like it now

#

I do not like what I had originally

#

Enum hell

alpine fjord
#

You learn more from failure than you do from success.

swift crag
#

and you learn more from doing something than from doing nothing :p

verbal dome
rare basin
#

for intermediate level?

#

if any

swift crag
verbal dome
#

Oh yeah, that thing

rare basin
#

i've been watching git-ammend on youtube but i barely understand his videos and the level of compelxity he's doing

swift crag
#

The doohickey

lyric rapids
#

I have script like this:

public class GameManager : MonoBehaviour
{
    public GameObject fallingObject;
    public float maxX;
    public Transform spawnPoint;
    public float spawnRate;
    bool gameStarted = false;
    void SpawnObject(){
        Vector3 spawnPosition = spawnPoint.position;
        spawnPosition.x = Random.Range(-maxX,maxX);
        Instantiate(fallingObject, spawnPosition, Quaternion.identity);
    }
    void StartSpawning(){
        InvokeRepeating("SpawnObject", 0.5f, spawnRate);
    }
    void Update()
    {
        if(Input.GetMouseButtonDown(0) && !gameStarted){
            gameStarted = true;
            StartSpawning();
        }
    }
}

And I try to put a prefab as a fallingObject but nothing falls when prefab is disabled, but when I enable it it falls and prefab gets destroyed so nothing can referance it anymore, why is that?

swift crag
#

"the prefab is disabled"?

#

is fallingObject in your scene? it shouldn't be

#

that should be a reference to a prefab asset

rich adder
#

you're probably touching the fallingObject prefab instead of the spawned instance

lyric rapids
verbal dome
# swift crag The doohickey

Do you have a way of loading a setting from script? By GUID or something? Or do you need a direct reference to the asset

swift crag
swift crag
#

But I never load them by name

cosmic quail
rich adder
swift crag
#

Which is no different from any other object at runtime

ancient hamlet
#

@lyric rapids you need to save the return of instantiate to a variable

lyric rapids
swift crag
#

The problem is that they're referencing a scene object instead of the actual prefab asset.

#

yeag

rich adder
#

just reminder, if you plan on destroying the spwned item do so on the Instance not the prefab

swift crag
#

It is a bit of a nuisance to not be able to just write Settings.quality or something like that

#

I do have a few singleton assets that store commonly-used settings assets so I can refer to them without assigning a reference every time

loud vault
#

Will " yield return new WaitForSeconds(0f) " still wait one frame or will it execute the rest of the code on the same frame?

swift crag
#

I would expect it to wait for at least one frame (probably not more than one frame)

wintry quarry
swift crag
wintry quarry
valid vector
#

anyone know how to use raycasts to tell where the player is looking

cosmic quail
valid vector
#

ok yeah but im in the code-beginner for a reason

cosmic quail
wintry quarry
#

do you mean find out what the player is looking at?

#

You answered that in your question - use a raycast.

valid vector
#

and i asked becuase i dont know how to use raycasts

wintry quarry
tiny vault
#

Has anyone ever tried, where the console says null reference error, but you have referenced field assigned, with the correct type ? In this case it's a gameObject with an image component

swift crag
#

Click once on the log message during play mode and Unity will select the offending object

cosmic quail
tiny vault
#

but i have all the fields assigned

cosmic quail
swift crag
naive pawn
swift crag
#

It's also possible that you have a valid reference, but then you access a null reference from it

#

foo.bar.baz

#

if foo is null OR if foo.bar is null, you'll get an error

naive pawn
#

maybe show the line that's given in the stacktrace

swift crag
#

Debug.Log("Hi!", gameObject);

cosmic quail
swift crag
#

Ah, no, it just selects a unity object

#

It's not telling you where in an expression the exception came from

tiny vault
#

I tried putting some Debug logs in to spot where null error arose from. Now i get this error, even though they literally are on the same prefab. Anyone got any ideas ?

languid spire
#

great that you dont show the line numbers of the code

wintry quarry
swift crag
#

You still haven't proven that you're looking at the correct object

swift crag
wintry quarry
#

or that

swift crag
#

but yes, I'd like to confirm that the actual prefab has these components

languid spire
polar acorn
dark brook
languid spire
dark brook
#

true just pointing out the possibilities

tiny vault
languid spire
swift crag
#

...how is Start even running?

polar acorn
swift crag
#

Instantiated objects get a negative instanceID (although persistent objects can have a negative ID, too)

#

But Start shouldn't be running on the actual prefab object

tiny vault
#

Im so fking stupid. Very new to Unity. There was just an old gameObject that i had forgotten to remove the DoorController script from. Adding the GetInstanceID helped. Was a good trick, thank you!

swift crag
#

That'll do it (:

swift crag
verbal dome
#

Pretty common mistake

zealous olive
#

someone can help me correct my code, I can't find the error, it's a 2d game
the error appears to be that the “groudCheckLeft” and “groudCheckRight” functions are not defined in the “PlayerMovement” function.
:

swift crag
#

Where is the actual error?

#

I don't see any errors indicated in the screenshot

#

if your code editor isn't showing errors and providing completions, see !ide

eternal falconBOT
zealous olive
slender nymph
#

make sure you read the entire error message

languid spire
zealous olive
slender nymph
#

did you read the entire error message? because it tells you what you forgot to do

naive pawn
slender nymph
#

it will literally say "You probably need to assign the groudCheckLeft variable of the PlayerMovement script in the inspector" which is what you've forgotten to do

zealous olive
slender nymph
#

ignore the code and drag the desired object into the slot on the object's inspector

#

surely whatever tutorial or course you are following would have shown you how to do that

slender nymph
#

then it's a shit course/tutorial or it is beyond your skill level. start by learning the basics. there are beginner c# courses pinned in this channel and the unity essentials then junior programmer pathways on the unity !learn site will teach you how to actually use unity

eternal falconBOT
#

:teacher: Unity Learn ↗

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

wintry quarry
#

also they are not functions

valid vector
wintry quarry
valid vector
#

hold on

wintry quarry
#

anyway this is called inverse kinematics

#

look that up

valid vector
#

yes i know

#

but hold on

verbal dome
#

The rotation of the palm doesnt seem to change

#

Yeah

wintry quarry
#

You need to do a raycast and project the cast direction on the surface to get the tangent along which you want your hand to align

valid vector
#

is there any other way to do that

wintry quarry
#

wdym

#

what's wrong with that way

valid vector
#

idk how

wintry quarry
#

learn

#

you certainly don't know some other unknown way either

#

Physics.Raycast
Vector3.ProjectOnPlane

valid vector
#

ok so

#

how do i put that in

#

and where

real grail
verbal dome
#

You'd probably have a script that has LateUpdate, which runs after animations have completed.
In LateUpdate you raycast (red) along the arm towards the hand, and if it hits something then you get the normal of the hit(yellow) and use that to create a rotation for the hand

#

create a rotation for the hand
This part is more complex

swift crag
#

Indeed.

#

This is a very common situation

#

It's often easy to find one direction

#

But you need second direction to figure out a rotation

verbal dome
#

Cross products likely come in handy here

swift crag
#

Hence the "tangent"

valid vector
#

im just using an IK script on the hand and set the target to where the player is looking

verbal dome
#

This way you get the "forward" direction of the hand resting on the surface

#

You can use the normal as the "up" direction

#

And from the forward&up you can construct a rotation

swift crag
#

Vector3.Project tells you how much of a vector lines up with a second vector

#

Vector3.ProjectOnPlane tells you how much doesn't line up

valid vector
#

that doesnt really help me understand what im suppoused to do

#

my idea was just point the front of the palm away from the camera but obviously that wouldnt work

verbal dome
#

Need to be fairly familiar with vector maths to do this kinda thing

valid vector
#

i just thought it would be funny for the player to touch things

#

well i give up

#

i will fix this when i have more time

#

bye

verbal dome
swift crag
#

actually, yeah

#

that's all you need

#

the vectors don't have to be orthogonal

verbal dome
#

Yep

#

Might be some weird edge cases that need to be handled

#

But that should get one started

wind hinge
#

If I have a really low framerate, and have say something that moves all the ways to the right, and then back to the left based on Time.time

#

Is it possible that the frame hithces or pauses could be perfectly so that you never see it move?

#

;-;

#

How to avoid that, or should I even care?

#

bc Time.time is not capped

swift crag
#

Sure -- if the object's position is entirely a function of the time, it could stay in the same spot forever given the appropriate framerate

#

(although, I'm pretty sure Time.time can't increment by more than the maximum delta time of 1/3 of a second)

wind hinge
#

i have an animation that is a function of the time

wind hinge
#

i didnt know it actually was capped

swift crag
#

Hopefully your game isn't running at under 3 FPS

wind hinge
#

oterhwise?

slender nymph
#

well if your game runs at less than 3 fps then you have some serious problems

#

and at that point, it's more a slideshow than a game

wind hinge
#

it does not

swift crag
#

Why are you concerned about this? Does the object need to collide with things, perhaps?

verbal dome
#

I really wish these docs would show the default value

frosty field
#

https://hatebin.com/acjnhwjbti
so i have this basic movement script for my game, but when i walk into objects my character just keeps moving forward and its getting like teleported back, its looking very bad and when i walk into an object mid air, it also keeps me in air for few more seconds, what can i do to avoid it?

cosmic quail
rocky canyon
frosty field
rocky canyon
#

if u swap over to rigidbodies u could use playerRB.velocity = or playerRB.linearVelocity considering which version of unity ur using..

and for the platforms u could use playerRB.MovePosition

frosty field
#

should i use rigidbody?

rocky canyon
#

if not then i'd def use a CharacterController and its Move() function

rocky canyon
#

Rigidbody-based movement ensures the player collides properly with objects and doesn’t "teleport" or clip through them.

frosty field
rocky canyon
#

rb will almost certainly improve the feeling and collisions

frosty field
verbal dome
#

I've seen the car tutorial that moves a rigidbody with Translate. It's a bit embarassing

frosty field
#

okayyy

#

thanks for help

rocky canyon
#

actually i prefer Kinematic Rigidbody solutions.. (kinda best of both worlds) but thats a bit more complex

cosmic quail
frosty field
#

okie dokie

cosmic charm
#

Hi, I'm currently working on 2d fighting game for 2 players, I finished coding of the character that fights, but now i'm struggling with doing the 2 players system, how can I make it so I have 2 characters, each work dependently of each others?

I would appreciate any help, my project deadline is so close 🙂

verbal dome
#

You mean independently of each other?

#

Ideally both characters would use the same scripts

#

Just different instances of those script components of course

languid spire
cosmic charm
frosty field
cosmic charm
#

i'm cooked, I guess?

rocky canyon
#
        playerRb.linearVelocity = new Vector3(0, 0, vertical);
        playerRb.linearVelocity = new Vector3(horizotal, 0, 0);```
setting velocity wont keep the velocity it already has
#

ur effectively re-writing it on ur very next line

#

for example if u wanted to keep the X and Y on the first and just adjust the Z
it'd be more like
playerRb.linearVelocity = new Vector3(playerRb.linearVelocity.x, playerRb.linearVelocity.y, vertical);

#

you'd pass in its own velocity it already has to the X and Y if u dont want to mess w/ those

#

otherwise ur setting them to 0 killin off any velocity

frosty field
#

oh okay

#

i wanted to do it like that

rocky canyon
#
 if (Input.GetKey(KeyCode.Space) && isGrounded)
        {
            playerRb.velocity = new Vector3(playerRb.velocity.x, jumpHeight, playerRb.velocity.z);
            isGrounded = false;
        }``` for example this would be a jump
frosty field
#

but i used Vector3(transform.position.x, transform.position.y [...]
and it did not work

willow breach
#

ok so after a long time i understood why my socket messages are being sent from unity editor but not from iOS
Failed to send event my-event: Operation is not supported on this platform. The unsupported member type is located on type 'System.Object[]'. Path: $.
how do i go around it?
this is the lib im using
https://github.com/itisnajim/SocketIOUnity.git
and here is my event emitting:
public void EmitEvent<T>(string eventName, T data) { string jsonData = JsonConvert.SerializeObject(data); Socket.EmitAsync(eventName, jsonData); }

rocky canyon
#

i usually construct my vector like FinalVector during the update after i get my inputs.. and then after everything is added together i'll pass the final vector

frosty field
cosmic charm
verbal dome
#

Wouldn't make sense to plug a position into a velocity

#

That would just yeet you outwards from (0, 0, 0)

real grail
rocky canyon
# frosty field yeah i used it cuz i didnt knew i have to put rigidbody instead of transform
  public float speed = 5f;
    private Rigidbody rb;
    private Vector3 moveInput;

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

    void Update()
    {
        // Read inputs in Update
        float horiz = Input.GetAxis("Horizontal");
        float vert = Input.GetAxis("Vertical");

        moveInput = new Vector3(horiz, 0f, vert).normalized; // Normalize for consistent speed
    }

    void FixedUpdate()
    {
        // Apply movement in FixedUpdate
        rb.velocity = new Vector3((moveInput.x * speed), rb.velocity.y, (moveInput.z * speed));
    }```
#

heres just the most basic of RB controllers..

cosmic charm
verbal dome
#

How much time do you have?

cosmic charm
cosmic charm
verbal dome
#

That's manageable, as long as you put in enough effort

#

And depending on how complex the game already is and how it is designed

cosmic charm
#

the thing is I'm so lost, I don't know where to start from

verbal dome
#

Search for local multiplayer tutorials for unity?

cosmic charm
#

I did, some of them are so complex to the point I don't understand how to implement the idea to my project, and some of them are stupidly simple, couldn't find anything in the middle, I even tried Udemy

frosty field
#

damnn

#

i didnt know making player move is so hardd

verbal dome
#

You can use GetAxisRaw to ignore that smoothing

steep rose
#

might be because of the getaxis

#

yup

verbal dome
#

You can also change the smoothing in the input manager

steep rose
#

you would generally use getaxisraw for instant movement

#

but it depends on preference

frosty field
#

okiee that does work now

rocky canyon
#

whoopwhoop

frosty field
#

but still its kinda weird for me

rocky canyon
#

even w/ that little change u should have much better colllisions w/ walls now

frosty field
# frosty field but still its kinda weird for me

why do i have to put movement in fixedupdate and make it complicated instead of just using
playerRb.linearVelocity = new Vector3(horizotal * speed, playerRb.linearVelocity.y, vertical * speed);
in update?

polar acorn
steep rose
#

Because it needs to reside on the physics step, unless of course you want framerate dependent movement

verbal dome
#

I think assigning velocity in Update is safe

#

Adding continuous forces is not

frosty field
#

okie i will just stick to fixedupdate then

#

still a little issue

verbal dome
cosmic dagger
#

you can assign velocity in Update. it won't run until FixedUpdate . . .

steep rose
#

then just keep it in FixedUpdate

verbal dome
#

I'd keep it in FixedUpdate for clarity's sake

steep rose
#

yup

verbal dome
#

Also fixedupdate runs just before update...

frosty field
verbal dome
#

So update would introduce one frame of delay, right?

steep rose
#

probably not, as if it does run only until the next FixedUpdate call it shouldn't provide any delay and even if it did it probably would be minuscule and unrecognizable

rocky canyon
#

using torque and stuff was a bit complicated

frosty field
#

weird

#

i use rotate and it feels like its not rotating at all

#

but it is rotating

rocky canyon
#

now if my character had to turn and rotate real-world objects. then yea i probably woulda figured out how to do it with Torque

#

but my player rotation has nothing to do w/ collisions

frosty field
verbal dome
frosty field
#

ohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

rocky canyon
#

if the object the rigidbody is attached to rotates.. the rb rotates w/ it

frosty field
#

waitttttt

#

i think i set my rigidbody to have fixed rotation so it wont spin in air in radom directions

rocky canyon
#

unless u have code rotating the rigidbody too.. then there would be conflicts

#

fun fact.. my rigidbody controller doesn't actually rotate.. i rotate a gameobject and the rigidbody just moves (in that objects forward direction)

steep rose
verbal dome
#

I can't believe that people don't care about a whole frame of delay in the input

#

When it can be easily mitigated

rocky canyon
#

i shot him first I swear!

spare mountain
#

hey I've played games with full seconds of input delay

#

this is a breeze

rocky canyon
#

dollarstore wifi Ftw!

spare mountain
rocky canyon
steep rose
#

I'm not saying to ever put it in update, I would keep it in fixedupdate either way

spare mountain
rocky canyon
verbal dome
rocky canyon
#

the only thing i dislike is when input is done in fixedupdate

#

feels soo janky and disconnected

verbal dome
#

But I just explained why it's sometimes better to do it in FixedUpdate

#

Do you want to start moving this frame or the next frame?

rocky canyon
#

true true.. im moving to the new input system either way.. soo my input code is irrelevant as of now

verbal dome
#

When you press a button

steep rose
rocky canyon
#

im guessing a full refactor is in order

swift crag
#

are we bikeshedding? i like bikeshedding

rocky canyon
#

my game runs at 400 fps at the moment..
my body doesn't and couldn't ever discern 1 frame of input lag

verbal dome
#

What if your game is performance intensive and runs at ~60FPS
I'd rather not have an extra 16ms delay on the input

rocky canyon
#

oh wait.. i use a CC.. soo doesn't matter to me either way heheh

steep rose
rocky canyon
swift crag
#

nevermind i totally would lmao

verbal dome
swift crag
#

I'm not sure exactly when the input state gets updated, though

#

If it's updated when the input events happen, then we are doomed

rocky canyon
#

i have that pinned up on my wall ^

swift crag
#

It'd be worth testing that

rocky canyon
#

i still need it for OnMouse stuff

verbal dome
#

I mean this is what i see

steep rose
verbal dome
#

FixedUpdate does have the most recent input

#

According to my tests

swift crag
#

excellent

rocky canyon
steep rose
swift crag
steep rose
verbal dome
rocky canyon
swift crag
verbal dome
#

Old system

#

Input manager

steep rose
#

well if I cap my framerate to 60 sure I'll notice something (or even lower)

rocky canyon
#

ya, you'll feelit more than see it i imagine...

rocky canyon
swift crag
#

it's worth testing your game at like

#

5 FPS

#

this can make execution order problems very obvious

verbal dome
steep rose
rocky canyon
#

thats very high expectations lmao

swift crag
#

I spent a while getting the order exactly right (through a mixture of script execution order and by adding explicit ordering to my code)

#

I had issues like the eyes of entities looking at a position from one frame behind

#

which was really obvious during fast movement

verbal dome
#

I gave up on relying on excecution order too much

rocky canyon
#

ive only did that for my game-manager to initalize things.. im more than certain i'd break something if i played with the execution order too much

swift crag
#

and my cameras were off by one frame, causing clipping through tight spaces

verbal dome
#

I like manually calling things from a centralized script

steep rose
swift crag
rocky canyon
#

as far as i know yea

swift crag
#

My own code just gets run in an explicit order

verbal dome
#

I admit it was Fen who got me to use those

#

Less deep profiling

swift crag
#

I'm slowly filling my game with profiler markers

#

they're really nice for getting a quick overview of hot spots

desert current
#

Is there any part of this script that would need to be adjusted to have frame rate independence? The game works perfectly in Unity but as soon as I try and build the character doesn't move the way I want it to, which I think is an error with the frame rate difference. Thanks!

https://paste.ofcode.org/d88BCDecHswsNESymRP8Mf

swift crag
#

what does "doesn't move the way I want it to" mean?

desert current
#

It slightly overshoots the target position

wintry quarry
#

There's some really weird stuff happening with "slimetype". It seems like that should be an enum or an int. Why is it a float?

#

And yes using a coroutine like that with WaitForSeconds with MoveTime is sensitive to framerate differences

#

This script overall seems overcomplicated for what I think it's doing

green flame
#

Hello! Someone can explain why I get this error "NullReferenceException: Object reference not set to an instance of an object"

I don't understand here is my entire script ^^

polar acorn
real grail
green flame
#

Thx guys! This works now :3

keen cargo
#

hey hey quick question, does anyone have a good tutorial/resource about loading, main menu, start game?

Before i try to go and find myself, maybe someone has a good resource on hand

rocky canyon
wispy coral
#

anyone know if the OnTriggerEnter Function work?

keen cargo
rocky canyon
# keen cargo hey hey quick question, does anyone have a good tutorial/resource about loading,...

Learn how to design and implement a loading screen in Unity!

Making Progress Bars: https://www.youtube.com/watch?v=J1ng1zA3-Pk
Custom Playables In Unity: https://www.youtube.com/watch?v=12bfRIvqLW4
Strategy Game Camera Controller: https://www.youtube.com/watch?v=rnqF6S7PfFA

----------------------------------------------------------------------...

▶ Play video
wispy coral
#

it basically tells me it doesnt exist

rocky canyon
#

may have to combine the two.. b/c this one doesnt go into the Menu and buttons and stuff

undone depot
#

know how would i add that delay?

rocky canyon
#

just moer about the loading screen and progress bars

rocky canyon
wintry quarry
rocky canyon
keen cargo
#

are you making a 2D game by chance?

wispy coral
keen cargo
#

within 2D pipeline?

undone depot
wispy coral
#

no im making a 3d game

rocky canyon
slender nymph
keen cargo
wispy coral
keen cargo
#

you need to finish writing it

wispy coral
#

doesnt auto complete, and doesnt work when finished

wispy coral
rocky canyon
#

is it within the monobehaviour ?

wispy coral
rocky canyon
#

public Class : Monobehaviour
{
// inside these brackets
}

wispy coral
#

oh yes it is inside it but it doesnt seem to be working

keen cargo
#

send the full snippet

#

of the code file

rocky canyon
#

!code

eternal falconBOT
wispy coral
#

gimmie a sec

rocky canyon
#

also make sure ur IDE is configured correctly

#

!ide ?

eternal falconBOT
wispy coral
#

it might just be my ide

#

ill try first to fix it

rocky canyon
#

easy to check.. at the top it should say AssemblyCSharp

#

in the left top corner above the text area

keen cargo
#

it's possible but it's showing the DetectCollision.OnTriggerEnter when you were hovering over it

rocky canyon
#

when its not configured w/ unity it'll still do stuff within the class and stuff..

#

it just wont know any Unity specific stuff

wispy coral
#

it seems its already set up properly

rocky canyon
#

hover Monobehaviour <-- at the top of ur class

#

if it refers to Unity it should be good

keen cargo
#

like this

wispy coral
#

yep it refers to unity

#

do all my game objects have to have rigid body for it to work?

rocky canyon
#

remove the private and just type OnTriggerEnter

rocky canyon
wispy coral
keen cargo
#

onTriggerEnter

rocky canyon
#

OnTrigger

#

not OnEnter

wispy coral
#

Ohhh ok my bad

#

Yes it does appear

rocky canyon
#

yea, just dont type private or public before it

#

it get confused

#

it thinks ur wanting to create ur own function

wispy coral
#

i see

#

so where do i need to put it if i need to detect collisions?

keen cargo
#

private/public is ok, my ontrigger works fine with it

cosmic dagger
#

You can put the accessor before it, that shouldn't affect anything . . .

rocky canyon
#

or.. u can put it on the object.. and check if hte player crosses into it

#

its just whichever

keen cargo
#

public class Bullet : MonoBehaviour
{
    private float topBound = 5f;
    // Update is called once per frame
    void Update()
    {
        if (transform.position.y > topBound)
        {
            gameObject.SetActive(false);
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Enemy"))
        {
            collision.gameObject.GetComponent<EnemyHealth>().TakeDamage(1);
            gameObject.SetActive(false);
        }
    }
}

I have my bullet projectile set up like this for an example

rocky canyon
wispy coral
#

I meant if i put it on void Update() or void Start()

keen cargo
#

don't put it under either

#

it's a separate function

#

look at my script

rocky canyon
keen cargo
#

oh what's those?

wispy coral
polar acorn
wispy coral
#

like a full script screenshot?

rocky canyon
# keen cargo oh what's those?
        if (collision.gameObject.CompareTag("Enemy"))
        {
            EnemyHealth enemyHealth;
            if (collision.gameObject.TryGetComponent<EnemyHealth>(out enemyHealth))
            {
                enemyHealth.TakeDamage(1);
            }
            gameObject.SetActive(false);
        }```
polar acorn
#

Type it up, let it be underlined, then send a screenshot of your IDE window with that script open

polar acorn
wispy coral
rocky canyon
#

if it doesnt have an EnemyHealth.. theres no need using GetComponent<EnemyHealth> when its gonnna be null anyway

polar acorn
keen cargo
#

ohh i see

#

what's the (out enemyHealth) part though?

rocky canyon
# wispy coral

if ur using VSCode u may want to install the UnitySnippets plugin

rocky canyon
wispy coral
rocky canyon
wispy coral
rocky canyon
#

right above it

polar acorn
rocky canyon
polar acorn
#

It is a separate function

wispy coral
wintry quarry
wispy coral
#

yeah its weird

polar acorn
#

No, I mean what are you talking about

#

You want to make a function named OnTriggerEnter

rocky canyon
#

when he types private before OnTrigger...

keen cargo
rocky canyon
#

it doesnt autocomplete

wispy coral
wintry quarry
rocky canyon
#

soo OnTrigg wont autocomlpete it?

polar acorn
#

VSCode doesn't really do autocomplete very well

rocky canyon
#

yea, install that UnitySnippet plugin for better results 👍

wispy coral
#

i will install that

rocky canyon
#

wait.. is that one for code?

#

yea it is

wispy coral
#

im genuinely so sorry yall

rocky canyon
#

dont be.. its how u learn

#

plus there may be 4 or 5 lurkers that didn't know that either

#

just helped them too lol ¯_(ツ)_/¯

wispy coral
#

the extension actually did it

rocky canyon
#

heck ya.. its almost required if u wanna use VSCode for unity

wispy coral
#

thanks so much

#

haha didnt even know about it

#

hadnt had any problems until now

rocky canyon
#

fun fact.. u can create ur own snippets in vscode

#

probably other ide's too but i know for sure in vscode

wispy coral
#

huh that interesting

rocky canyon
#

ya, u may get to a point where u want to..

#

just sayin

wispy coral
#

i gotta investigate more stuff about vscode

#

either way thanks

#

saved my life

rocky canyon
#

np 🍀

#

i think u'd live w/o it

#

but ur welcome 😉

keen cargo
#

lol i was basically forced off of vscode by my teacher

rocky canyon
#

for what? vs studio?

keen cargo
#

yep

#

had our first unity class so I was using vscode, was thinking "hmm why doesn't anything autocomplete and where are the funny colours"

rocky canyon
#

the ole vscode vs visualstudio fued..

keen cargo
#

he comes over "oh you're using vs code, i don't know how to use that lol"

rocky canyon
#

will continue til the end of days

rocky canyon
wispy coral
#

my only reason for being on vscode is that my pc cant handle rider or vs2022

rocky canyon
#

😄 solid reason

#

vs2019 crying in the corner

rocky canyon
#

before a code review.. just open ur solution in vscommunity and delete the .vscode folder

#

ezpz ;D

steep rose
rocky canyon
#

out of 18k+ users there has to be atleast 1

steep rose
#

us and the others where they are waiting to help someone, just like a velociraptor

frosty field
#

does anybody knows how to fix sticking to walls while mid air and holding direction key towards that wall? like on screenshot

rocky canyon
undone depot
#

remove the sticky goop on the cubes

undone depot
rocky canyon
#

np! you're now more powerful than ever 💪

#

just a tip i wish i woulda known at first.. sometimes you'll need to Stop a coroutine..

#

just cache it when u start it.. and then u can use that variable to stop it

ashen gulch
#

is there a way to find an inactive GameObject?

teal viper
#

If it being inactive is the only criteria, it might be difficult

mint lion
ashen gulch
#

Was trying to set some objects active when starting the game game with them inactive.

mint lion
#

if you know the transform to look under, then you can check the child gameobjects - gameObject.activeSelf indicates if it's active or not

wispy coral
#

is vs2022 too different from vscode?

#

i stopped liking vscode

#

its way too basic

#

(without extentions) for my taste

mint lion
undone depot
wispy coral
teal viper
undone depot
#

would it be fine to post the attacking script?

steep rose
wispy coral
#

alright, do i need the c++ workloads for vs2022? or just the unity one

steep rose
#

to configure it?

#

just follow this guide, !ide

eternal falconBOT
mint lion
frosty field
#

does anybody knows how to remove glitch that allows someone to double jump when they stick to a wall?

wispy coral
mint lion
#

.net desktop (workload)

steep rose
mint lion
frosty field
#

that's basically my player movement script

frosty field
#

i use colliders set like this

steep rose
#

you are allowing your jump if you have collided with anything

frosty field
#

well...

steep rose
#

you would probably want a ground check for that

frosty field
#

and.. how to do that? is there a premade function that i can use?

quasi dawn
#

Nope

#

But you can use Ground Layers and Physics Overlaps

steep rose
#

Raycast/spherecast would be good, overlapsphere would also suffice

#

Raycasts do return a boolean, so you could just assign an isgrounded boolean to it

valid vector
#

ok real quick does anyone know how to make an object not inherit its parent's scale

#

because my movement scales the player and that messes with other things and causes shearing

#

this just feels yucky to look at

mint lion
valid vector
#

well im not rewriting the entire fucking player code

frosty hound
#

There is no magic setting to toggle.

valid vector
#

this engine can make some of the best indie games in human history and cant individually scale child objects

mint lion
#

a gameobject's scale is based on its parent (if it has one)

valid vector
#

it does

#

and i dont know how to make it face the way it does without parenting it to the player

#

like how do i make it have the same rotation and position as the camera without parneting it to it

cosmic dagger
valid vector
#

yes

cosmic dagger
#

I think there's a parent constraint as well. Type "constraint" when adding a component to see what pops up (away from the computer, ATM), or check Google. They have a bunch of constraint components . . .

mint lion
#

what does "my movement scales the player" mean?

valid vector
valid vector
steep rose
#

literally just set object A to object B using .position and the equivalent code after, the same applies to rotation

ashen gulch
#

I dont understand what it wants from me, the variable is already set in the inspector prior to PlayMode, after setting it Active.False it just forgets about it I guess.

mint lion
#

ah. you should be changing the collider height, not the gameobject scale

cosmic dagger
valid vector
#

it was a tutorial

ashen gulch
slender nymph
#

how have you confirmed that?

ashen gulch
cosmic dagger
ashen gulch
#

In the scene

slender nymph
# ashen gulch

first, you need to search by type, not by name. use t:UIManager and second, you also need to ensure you do this search during play mode when the error appears

mint lion
ashen gulch
#

Nope, nothing new

#

what the ...

#

It started working

#

how t*

#

Aint changed nothing... and it starts working.. (unity just wants to emberass me)

quasi dawn
#
        {
            Flip(currentVelocity);
            if (Mathf.Abs(_rb.velocity.x) < maxSpeed)
            {
                _rb.AddForce(Vector2.right * currentVelocity * walkForce);
            }
            else if (Mathf.Abs(_rb.velocity.x) > maxSpeed)
            {
                _rb.velocity = new Vector2(Mathf.Sign(_rb.velocity.x) * maxSpeed, _rb.velocity.y);
            }
        }
        else
        {
            _rb.velocity = Vector2.Lerp(_rb.velocity, Vector2.zero, 0.5f);
        };```
Is this a good way to make 2D movement?
#

I tried making the deceleration process by adding counter forces but it was giving some weird results

#

Most likely me being bad at coding, but yeah
I decided to "cheat" by Lerping the velocity for deceleration

rocky canyon
#

i use MoveTowards tho.. when lerping, passing it the variable ur actively lerping as one of the parameters isn't a good way to lerp.. (you'll never reach the target that way)

quasi dawn
rocky canyon
#

im very skeptical of that.. but its possible.. its a super common mistake.. and theres entire web-dev logs devoted to it

rocky canyon
#

just note.. it probably isnt gonna be "game breaking" or anything

quasi dawn
rocky canyon
#

yea.. all the other example you'll notice the variable they're setting

#

is not included in the lerp

quasi dawn
#

I see

#

They added a local variable for taking the current position

#

Maybe doing the same with the currently velocity will avoid that

rocky canyon
#
public float targetValue;

void Start()
{
  StartCoroutine(LerpFunction(targetValue, 5));
}

IEnumerator LerpFunction(float endValue, float duration)
{
  float time = 0;
  float startValue = valueToChange;

  while (time < duration)
  {
    valueToChange = Mathf.Lerp(startValue, endValue, time / duration);
    time += Time.deltaTime;
    yield return null;
  }
  valueToChange = endValue;
}```
wispy coral
#

is there a way to make vs2022 not so laggy or is it just like that

rocky canyon
#

yup, but theres also alternatives..

#

like MoveTowards()
SmoothDamp etc

wispy coral
rocky canyon
#

movetowards doesnt take any of that extra stuff

#

thats y i prefer it

quasi dawn
#

The only way i'm using Lerp is for decelerating a rigidbody, so it doesn't feel as unnatural as just outright setting the velocity back to zero

rocky canyon
#

ya, i know what u mean.. my momentum stuff does the same thing

            airVector = Vector3.Lerp(airVector, airVector + airControlVector, characterSettings.airControlStrength * Time.deltaTime);
            groundVector = Vector3.Lerp(groundVector, Vector3.zero, characterSettings.airDamp * Time.deltaTime);``` this is at the end of my update loop
#

just two vectors i constantly feed to my CC's Move() function.. when its not being actively updated by the input it slowly fades to zero

quasi dawn
#

AAH WAIT

#

I GET IT NOW

rocky canyon
#

ohh lookie, lookie.. those are worng

#

😄

#

those should be MoveTowards()

#

they are in my updated version

quasi dawn
#

It will keep going forever since it'll never actually reach zero

#

I see it

rocky canyon
#

yea, it keeps cutting the result in half

#

and it keeps getting incremently smaller and smaller and smaller

quasi dawn
#

Nice to know :D

rocky canyon
#

yea, just a weird thing most ppl learn after they use lerp a few times

quasi dawn
#

It's probably best to just add a condition in case the value reaches a certain threshold

rocky canyon
#

thats a solution as well 👍

quasi dawn
#

Maybe a While loop?

#

Idk I've been avoiding while loops since every time I tried them, the editor would freeze

rocky canyon
#

i think its simpler than a while loop hold on

#
   valueWeChange = Mathf.Lerp(valueWeChange, 0, Time.deltaTime * 5f);
   if (valueWeChange < 0.1f) valueWeChange = 0;```
quasi dawn
#

That's cool

rocky canyon
alpine fjord
quasi dawn
quasi dawn
quasi dawn
rocky canyon
#

ya, basically that'd be the only legitimate reason

#

that and scaleability.. if u had to add more than 1 line.. u'd have to add the brackets back..

#

lord forbid

alpine fjord
quasi dawn
#

Now I wonder, with my current movement code
Would I be able to add movement hazards?

#

Like strong wind or moving platforms, stuff like that

rocky canyon
#
            if (Mathf.Abs(rbCurrentVelocity.x) < 0.01f)
                rbCurrentVelocity.x = 0f;

            _rb.velocity = rbCurrentVelocity;```
is pretty readible to me..
but, i get it
quasi dawn
#

Since I am using forces

rocky canyon
#

u can always break up ur vectors and add them together before u send them to rb.velocity

#

normalMovementVector + outsideForcesVector; and then just lerp the normalMovementVector part

#

instaed of the entire rb.vel

#
        finalVector =
            (groundVector * finalSpeed) +
            (airVector * characterSettings.airSpeed) +
            (Vector3.up * gravitySim);

        characterController.Move(finalVector * Time.deltaTime);```
#

i'll only lerp my ground and air vectors

#

no reason to lerp the gravitySim

quasi dawn
#

Yeah just I've heard that setting the rigidbody's velocity outright make adding stuff like moving platforms and strong winds significantly harder than by just using forces

rocky canyon
#

u just gotta keep up w/ what ur doing 🤪

#

but yea.. it does make it a bit more involved.. when ur adjusting ur velocity directly

#

a player controller is the most important part of ur game (most times)
u wanna make sure u have a solid understanding of it anyway

#

but by breaking up ur forces and stuff into different variables instead of just bunching them all into one.. u can help mitigate that a bit..

#

say something goes wrong w/ my groundVector i'll have alot easier of a time debugging it.. b/c all the other things wouldn't be involved at all

undone depot
#

can someone check out why the AttackDouble coroutine doesnt work?
all the things which affect it are kind of all over the script so i just pasted the whole thing

eternal falconBOT
undone depot
ashen gulch
#

How can I get the name of a button i pressed? I want this for something like 50 buttons, so i need something efficient.

wintry quarry
#

what do you mean?

ashen gulch
#

Yes UI button

wintry quarry
#

WHy do you want the name

#

dealing with object names is usually not efficient

#

What do you actually want to do?

#

Is it for a hotbar system for example?

ashen gulch
#

It is for a quick project, i need it to make a pair between a button and a 3d object. (when i press the button the 3d part changes)

wintry quarry
ashen gulch
#

wouldnt that mean i have to go through each of my 50-ish buttons individually?

wintry quarry
#

Wouldn't the thing you're asking about mean you would need to individually write code for 50ish different button names?

ashen gulch
#

I mean, I already had a list of stuff I wanted to model, so when I made the buttons/3d models i made sure for the names to match.

#

So if I could do the match name-wise I could do it with a single function, my guess

wintry quarry
#

ideally the buttons would all have been prefab instances calling a listener on themselves that just grabs their own .name

#

barring that - you can write a loop that adds a runtime listener to each one that takes the button object's name and passes it into some function

ashen gulch
#

I also found this EventSystem.current.currentSelectedGameObject.name. It returns the name of the button (CURRENTLY PRESSED*) as it is written in the hierarchy, so I think I can use this.

wintry quarry
#

The other thing to do would be to implement IPointerClickHandler on your button

#

or add an event trigger to it with the PointerClick event

ashen gulch
#

Ill take a look, thanks for the guidance

ashen gulch
#

(oh boy)

nocturne kayak
#

Hey, i have a... Jittery raycast point??

#

No clue why, but this is what's happening:

#

The small cube has it's position set to spawnCast_Hit

#

The big one's using the same code i'm using for drawing those rays

#

Still, i have no clue why it's so. damn. jittery

teal viper
nocturne kayak
#

The smaller wirecube should be at the same point at the bigger one

#

but it's just jumping around

teal viper
#

What is it even? How is it related to the raycast?

#

Ah, ok. So it's repositioned to the hit point?

wispy coral
#

how do i make it so that after an action i have to wait a certain amount of time to do that action again?

teal viper
wispy coral
# steep rose like a cooldown?

yeah just like that, i was thinking making the action itself a method and then using invoke with a key press with a delay

#

is that correct?

steep rose
#

you could use a coroutine, time.time timer or invoking a function

#

if you already have a function you made, invoking it may suffice

#

else you could use a coroutine or time.time timer

wispy coral
#

i havent learned what coroutines are at the moment so ill try the other two and see how it goes

#

thanks again

tender wren
#

If I move a game component's position outside of the update function without lerp it is jarring, but I cannot get Lerp to work outside the update function. Is there a work around function.

Example:

teal viper
#

And where is "outside of the update"??

nocturne kayak
#

canSpawnObjectHereRay is the bool "If this ray hit something"

#

spawnCast_Hit is the out from that ray

#

i'm only ever drawing the cube if it's hitting something

teal viper
nocturne kayak
#

oh, yeah, it's acter the other one, hold on

tender wren
nocturne kayak
tender wren
# teal viper Continue

Example of the Lerp in terms of the camera:

void Update()
    {
        transform.position = Vector3.Lerp(transform.position, new Vector3(player.transform.position.x, transform.position.y, transform.position.z), speed * Time.deltaTime);
    }

This creates a smooth movement from a to b, but it takes place in the update().

If I do
:

void Update()
    {
        CameraFunction(camera.transform);
    }

....

public void CameraFunction(Transform t)
{
  transform.position = Vector3.Lerp(transform.position, new Vector3(player.transform.position.x, transform.position.y, transform.position.z), speed * Time.deltaTime);
}

It does not update smoothly, instead it only moves one frame worth of the distance, before attempting again from where it was.

teal viper
tender wren
#

This is not actual code, but an example

teal viper
tender wren
# teal viper 1. This is not a correct way to lerp(the third param). Check the docs. 2. Extrac...

I deleted the lerp attempt, but I can show you the code i'm using to move all the game objects.

Warning its bad:

    public void AdjustTerrainVerticalityDown(int tSpeed, GameObject cliff)
    {
        cliff.transform.position = new Vector3(
            cliff.transform.position.x,
            cliff.transform.position.y - .4f,
            cliff.transform.position.z
        );

        foreach(GroundPiece gP in currentTerrain){
            gP.groundPiece.transform.position = new Vector3(
            gP.groundPiece.transform.position.x,
            gP.groundPiece.transform.position.y - .4f,
            gP.groundPiece.transform.position.z);
        }
    }

So in place the current pos = pos. I was doing pos = new vec3.lerp(current,new,rate);

#

Let me rewrite it and attempt again

teal viper
tender wren
#

This adjusts all the elements in the current terrain down, another function moves them up.

teal viper
tender wren
#

Let me attempt now.

tender wren
teal viper
tender wren
#

A simple example would be I have one game object. I press button it smoothly goes down and stops untilk I let go and press again.

teal viper
#

And while we're at that, I'd suggest you go over the beginner pathways on unity !learn before working on your own project.

eternal falconBOT
#

:teacher: Unity Learn ↗

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

nocturne kayak
#

i found the problem, i was being a dumdum and using a boxcast isntead of a simple raycast

stuck shard
#

Okay, I've started working with Unity Built-In UI Builder and UI ToolKit got all my ui set up for my intended issue but if I re-scale the game to anything but 1920 x 1080 the UI just stays exactly to what I've set it as. is there a way to make it automatically rescale?

#

Tried to look it up on youtube. didn't find anything on this rescaling issues. although a lot point to Position being Relative and Match the Game view that literally did nothing. should I apply a script to my UI Document that allows it to use a Canvas Scaler. I don't really have a viesable approach or anything to go off.

#

It's a pain cause I think it's my last piece to my puzzle on UI Builder

shy anchor
#

Hey everyone!

I am trying to make a simple collision script where I update the speed variable when the boxcollider is triggered. Here, PlayerController is a script of my player gameobject. I understand this is wrong, would someone know how I should thinkin
g of this?

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

public class PowerUps : MonoBehaviour
{


    public GameObject powerUp_Prefab;
    public GameObject player;

    
    void Update()
    {

        BoxCollider2D boxCollider2D = powerUp_Prefab.GetComponent<BoxCollider2D>();

        playerController = player.GetComponent<PlayerController>();
        if (boxCollider2D.isTrigger)
        {
            playerController.speed =  playerController.speed + 0.5f;
        }

    }
}
#

Also please excuse my syntax errors!

eternal falconBOT
undone depot
#

how would i differentiate between materials for adaptive hit noises or footsteps

shy anchor
#

thank you! I saw to use that as a solution, I am curious as to why it would not work the way I have it. My thinking is if the script is a component of my game object why can't I use get component and update the variable that way

wintry quarry
#

it is doing absolutely nothing to detect collisions between the box and the player

#

As for the use of GetComponent, that part looks correct assuming you have actually referenced the correct objects in the inspector

#

However - it's completely unnecessary

#

You could have just referenced the components directly in the inspector

#

saving yourself the GetComponent call

#

e.g.

    public Collider powerUpCollider;
    public PlayerController player;```
#

You might also be a little confused about what a prefab is.

#

A prefab is a thing in your project folder. Prefabs do not exist in scenes.

#

The things in the scene that are made from the prefab are instances of the prefab, not the prefab itself.

shy anchor
#

@wintry quarry That makes sense! Thank you for the explanation 🙂

undone depot
wintry quarry
rocky wyvern
#

I think the most elegant way would be to ontriggerenter with a collider that collides with ground layer and cache the ground material you want

#

But if you have overlapping colliders and whatnot it might be better to just raycast down from ur feet

undone depot
#

what about for hit sounds? is there a stand in thing i could put for that comment

#

im not above just repeating the if statement for 6 materials

undone depot
rocky wyvern
astral falcon
tough cosmos
#

Hello community 🙂 I have an issue with my animation on my 2D character.... it doesnt stop... even with no input from the keyboard... can anyone help me? I'm trying to solve this since 3 days....

burnt vapor
eternal falconBOT
tough cosmos
#

This is my PlayerController Script:

test
#

this is my script and i did a clean up because i had in every line a Debug.Log

#

i dont know why my animation is still ongoing even if i dont move

#

or is it better to post in the networking channel because it's multiplayer?

astral falcon
tough cosmos
#

when i move it works and when i dont move in the console it says:

No movement detected, deltaPosition is zero.
UnityEngine.Debug:Log (object)
PlayerController:Update () (at Assets/Scripts/Player/PlayerController.cs:62)

#

so the scripts detects that there is no movement, but why does my player still has the animation going?^^

astral falcon
#

please post your script on a script page, so we actually got line numbers and stuff

tough cosmos
#

how? i posted my script as a message, because it's too big

astral falcon
#

!code as already mentioned 🙂

eternal falconBOT
tough cosmos
astral falcon
#

As far as I can see, you never reset to false

            animator.SetBool("isRunning", true);
tough cosmos
#

ok? so i expand the if statement with an else and set the boolean to false?

astral falcon
#

Thats something for you to test and figure out. But the reason your animation is going is, that this is set to true and never reset

tough cosmos
#

nice now it works on the host and on the client! but one more issue^^ when i watch on the host screen the client animation dont stop but on the client screen it stops

#

any idea?^^

burnt vapor
#

The host never calls code that stops the running then

#

Same idea there

tough cosmos
#

hmm... yeah but i dont know where to but the code... 😦 sorry

#

in the update i put:

private void Update()
    {
        if (!IsOwner) return;

        // Eingaben des Spielers abfragen
        float moveHorizontal = Input.GetAxisRaw("Horizontal");
        float moveVertical = Input.GetAxisRaw("Vertical");

        // Bewegung basierend auf Input berechnen
        Vector2 deltaPosition = new Vector2(moveHorizontal, moveVertical) * moveSpeed;

        if (deltaPosition != Vector2.zero)
        {
            // Sende Bewegungsanfrage an den Server
            SendMoveRequest(deltaPosition);

            // Optional: Direkte Anwendung beim Eigentümer zur Reduzierung wahrgenommener Latenz
            if (isOwnerPrioritized)
            {
                RespondToMoveRequest(deltaPosition);
            }
        }
        else
        {
            Debug.Log("No movement detected, deltaPosition is zero.");
            animator.SetBool("isRunning", false);
        }
    }

now it works on the host

#

but i think i have to set the bool in the ServerRpc

#

right?

burnt vapor
#

No clue, sorry

tough cosmos
#

ok, no problem thank you 🙂

fickle wagon
tough cosmos
#

i got it! created a ServerRpc and a ClientRpc that sets the boolean to false gg wp

astral falcon
lilac turtle
#

can you detect the exact point where raycast hit a certain object?

eager spindle
#

so it would use hit.point

lilac turtle
#

ty

eager spindle
#

docs are very fun

lilac turtle
#

very amazing indeed