#💻┃code-beginner

1 messages · Page 546 of 1

wooden wharf
#

can some one help me im doing the junior programmer crate with code 2 lesson 4.3 and i have no idea why the powerup knockback isnt working

frail hawk
#

we could if you posted some code 😉

rich adder
#

📃 Large Code Blocks

eternal falconBOT
wooden wharf
#

sorry

modern trout
#

hi guys, im trying to make a quick time event to make my character crawl, i got the animation but i dont really know how to make it stop and wait for a qte, or even making a qte, any tips?

frail hawk
wooden wharf
wooden wharf
frail hawk
#

is the OnCollisionEnter being called, you could find that out with a simple Debug.Log on the first line.

rocky canyon
#

Debug.Log("Collided with " + collision.gameObject.name + " with power up set to " + hasPowerup);

#

does that ever run? ^ if not its b/c if (collision.gameObject.CompareTag("Enemy") && hasPowerup) one of these aren't true

wooden wharf
rocky canyon
#

add the debug right after the oncollisionenter

#

u should always do this to test anyway..

//log

if(extraCondition){
//log
  }

}```
wooden wharf
rocky canyon
#

u want to know if OnCollisionEnter is being called at all

#

then u move on to the next step

swift crag
#

The golden rule: Hang On, Is Anything Happening At All?

#

well, more of a golden question

#

aka Dude, Where's My Call?

rocky canyon
#

plugs in Mouse, aight guys fixed

rich adder
#

microsoft support: Have you tried restart computer?

wooden wharf
#

i just got "Collided with island with power up set to false" ... fuck

swift crag
frail hawk
rocky canyon
# wooden wharf i just got "Collided with island with power up set to false" ... fuck

waiit where?

    private void OnCollisionEnter(Collision collision)
    {
        Debug.Log("This will be logged regardless if its an Enemy OR if hasPowerup is true");
        
        if (collision.gameObject.CompareTag("Enemy") && hasPowerup)
        {
            Rigidbody enemyRigidBody = collision.gameObject.GetComponent<Rigidbody>();
            Vector3 awayFromPlayer = (collision.gameObject.transform.position - transform.position);

            Debug.Log("Collided with " + collision.gameObject.name + " with power up set to " + hasPowerup);
            // this one should not run if powerup is false ^^^
            enemyRigidBody.AddForce(awayFromPlayer * powerupStrength, ForceMode.Impulse);
        }
    }```
wooden wharf
rocky canyon
#

but if u moved the debug up below the oncollision and it worked. that means yea ur condition isnt being met to run the rest

wooden wharf
#

its still in the oncollision i just moved it up

lyric rapids
#

Hi, I don't really get why AtRest is becoming true when Vector3.Distance(transform.position, targetGridPos) is 0.8 like on screenshot when in the condition it says it has to be less than 0.05
I struggle to understand why after I move with smoothTransition = true my character is unresponsive (engine is working as expected)
Code: https://paste.myst.rs/stcpacv6
Check comments in the void MovePlayer() for more details
In the screenshot u can see relevant logs,

swift crag
#

nah, it is

rocky canyon
#

is it? 👀

swift crag
#

it's the French/German/etc. decimal separator

rocky canyon
#

why the whacky ohh

swift crag
frail hawk
#

yeah we use that thing here

swift crag
#

do you have "Collapse" turned on in your console?

rocky canyon
swift crag
#

That would cause identical logs to get combined into one

swift crag
#

2,000 (US) became 2,000 (German)

#

the latter is 2 :p

wooden wharf
#

i am still so confused

lyric rapids
swift crag
wooden wharf
#

i dont know what to do

rich adder
wooden wharf
rich adder
wooden wharf
polar acorn
wooden wharf
lyric rapids
#

"AtRest: false" is what I'd expect to

swift crag
#

"throw it out and start over" is not a very practical debugging strategy

wooden wharf
steep rose
#

does this block of code ever get called?

        if (other.CompareTag("Powerup"))
        {
            hasPowerup = true;
            Destroy(other.gameObject);
        }
#

if not then you need to check if one of your colliders is a trigger and if they have the right tag

steep rose
#

he most likely does not have triggers

rich adder
#

gotta see if script is running at all

cosmic charm
#

I fixed it, i didn't assign the Clone_Skill_Controller to the clone 😭😭😭😭

#

that was the problem

#

thank you anyway

#

Thank you

flat sphinx
#

teach me how to make breakpoints not break

#

(not really im busy rn i just want to be able to use them)

cosmic charm
#

Thank you so much, my prblem was in assgining the script to the clone and that's it

swift crag
flat sphinx
slender nymph
swift crag
#

I had middling results with VSCode

#

Sometimes it worked, sometimes it just kinda...got stuck

flat sphinx
#

ill make sure to throw nvim with the fanciest rice on my new gentoo minimalist install

steep rose
slender nymph
steep rose
#

if you are on linux you only have VSC and rider (VS not supported), I heard the latter is good

flat sphinx
#

also, linux

flat sphinx
#

am gonna try rider tho

swift crag
#

gray knight for VSCode

#

not a full-on white knight

#

i think it's ok

#

Rider has been delightful

steep rose
#

keep in mind rider is non-commercial use only for the free version

slender nymph
#

yeah vs code is generally fine, but with unity it tends to break quite often which is why i avoid it and recommend others do so.
rider is and always has been super nice to use, and vs is somewhere in between. though i will say it was super slow when i had resharper installed for it, which is ironic considering rider itself runs like a dream

flat sphinx
#

(the context being im too dumb to actually release a game)

steep rose
#

well if you do, you would need a license

flat sphinx
#

rig

steep rose
#

VSC has worked so far for me, I have not had anything bad happen yet

#

I have not tried rider yet

swift crag
#

I've seen a lot of people with weird issues getting the .NET SDK to work in VSC

#

it'll just...not download

#

After that hurdle, it was pretty smooth sailing. Debugging was hit or miss

flat sphinx
steep rose
#

downloading the net sdk on arch was a breeze

#

and no issues

flat sphinx
#

was p easy to resolve tho

swift crag
#

(several times)

#

I couldn't convince VSCode to use a manual install

flat sphinx
#

do wonder how it's gonna go with portage tho

rocky canyon
#

collapse ur logs. only time it spams if its a different log. not as good as breakpoints better than spam tho

steep rose
#

even better

rocky canyon
#

debug mode in inspector the way to debug values imo, 🤪

flat sphinx
steep rose
#

works for me

flat sphinx
#

also side tangent

#

the fact i can sudo !! is fucking lovely

queen adder
zenith cypress
slender nymph
queen adder
wooden wharf
steep rose
#

you probably want that comparetag you originally had, make sure your powerup is a trigger and has the specified tag on it

wooden wharf
steep rose
#

It is

wooden wharf
# steep rose It is

i love working on something for over an hour have it not work then when you start from scratch now it works

steep rose
#

that is why you debug so you don't have to do that

short hazel
#

By rewriting it, you eliminated the bug introduced by mistake

wispy coral
#

how do i enable and disable a camera with input?

swift crag
#

two separate problems!

  • receiving input
  • disabling a camera
wispy coral
#

recieving input is done already

#

just need to disable the cam

swift crag
#

set its enabled property to false

wispy coral
#

ok lemme try that

#

and if i want to turn it on again with the same button?

swift crag
#

set it to true!

#

you could do cam.enabled = !cam.enabled;

#

this switches it back and forth

polar acorn
#

Set it to whatever it currently isn't

swift crag
#

The missile knows where it currently is...

wispy coral
#

ohh ok lemme try that

#

im doing some unity learn challenges and thats the one i got stumped on

#

ok turns out input was not done already

#

its more complicated than i thought

steep rose
#

how so?

wispy coral
#

could yall explain this to me like if i were 5 this wa the solution listed on the problem
if(Input.GetKeyDown(switchKey)) { mainCamera.enabled = !mainCamera.enabled; hoodCamera.enabled = !hoodCamera.enabled; }

steep rose
#

all that code does is toggle the camera on and off based off an input

#

similar to a toggle boolean

wispy coral
#

i see

polar acorn
wispy coral
#

ohhh ok ok

#

thanks guys

swift crag
#

GetKeyDown is true for one frame at the start of a press
GetKey is true during a press
GetKeyUp is true for one frame at the end of a press

steep rose
real grail
wispy coral
#

would that code work if it were applied for other things? without the camera things of course

steep rose
#

so it is the exact same as a toggle boolean

swift crag
#

Whatever you put inside that if statement will run

#

If you put Application.Quit(); in there, the game will exit

wispy coral
swift crag
#

You don't have to use a special GetKeyDownToTurnOnACamera method

#

Most of programming is just deciding:

  • When do I do this?
  • What do I do this to?
wispy coral
#

wow, i learn more every day

swift crag
#

I do this:

  • When space is pressed

I do this to:

  • The camera stored in the mainCamera variable
short tusk
#

Is anyone able to tell me why my crosshair object refuses to follow the mouse position on the X and Y axis? Cannot figure this out for the life of me but I believe I am using the right ideas just not executing correct.

Vector3 mousePos = Input.mousePosition;

        mousePos.z = distanceFromCamera; 

        Vector3 worldPos = cameraMain.ScreenToWorldPoint(mousePos);

        crosshair.transform.position = new Vector3(crosshair.transform.position.x, worldPos.y, worldPos.z);
wispy coral
#

thanks so so much

swift crag
swift crag
#

figuring out when one problem is actually two separate problems

short tusk
short tusk
real grail
swift crag
#

That is not correct. distanceFromCamera is a distance...from the camera

#

it's not the actual Z coordinate the crosshair should wind up at

#

especially not if the camera isn't pointing in exactly the +Z direction

#

Is this a 2D game or a 3D game?

short tusk
#

Ok then I think my brain is just being jelly at this point and I am just not thinking correctly. Its a 3D game with the goal of putting a 2D crosshair on screen.

#

Might have to come back to this after some sleep cause I think I am not inherintely understanding the fucntions I am working with.

swift crag
#

Okay, then just directly assign the result of ScreenToWorldPoint into the position of the crosshair

#

That will place it at a certain position on your screen, exactly distanceFromCamera meters away from the camera

real grail
swift crag
#

that would be correct if you wanted to stick the crosshair onto the object you're looking at

swift crag
#

and in a 2D game, it would place the object too close to the camera

short tusk
swift crag
#

Ideally, a crosshair shouldn't really...have a distance from the camera; it should just be drawn directly onto your screen (e.g. by an overlay UI)

short tusk
#

Ok that was the other option but any guide I found for doing it via UI was super outdated and had missing/moved tools being used.

#

So I just didn’t know how to proceed.

swift crag
#

A very basic crosshair would be a Canvas with a single child object

#

which would have an Image and be anchored to the center

#

You can write a custom shader to create interesting dynamic crosshairs (:

#

or just stick a + in the middle

queen adder
#

hello

#

how to make a platformer game movements?

#

with Rigidbody 2D and Box Collider 2D

undone depot
#

how would i add that delay

alpine fjord
eternal falconBOT
#

:teacher: Unity Learn ↗

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

alpine fjord
#

The junior programmer path will help you.

steep rose
queen adder
#

i cant understand nothing of tutorial

swift crag
#

Did you actually attempt to follow the pathways on Unity Learn?

queen adder
#

I click in Start Pathway and open a random site of Unity

#

i cant understand what i need make to start

steep rose
#

do the unity essentials first in the pathways, click start pathway, then get started, all you have to do then is read what it is saying to you and remember what it is saying to you.

queen adder
steep rose
#

uhh, sure?

queen adder
#

im a scratch dev(u can see in my name)

#

and i want exit from Scratch and go to Unity

steep rose
#

If you actually learn there might be a chance of that happening, but you have to learn, especially the basics of unity

#

scratch is a "language" made for absolute beginners, unity is the real deal

queen adder
verbal dome
#

I remember doing that when prototyping years ago

elfin isle
#

hi y'all :) i've been working on a project for a while now and i think its finally time i change my pickup system, yet the thing i want i cant seem to figure out and cant seem to find online.

I'm looking for the bare minimum, when player looks at object and presses keybind, reutnr Debug.Log("HI!!");

Anyone know how to do this?

steep rose
#

use a raycast whenever the desired button is pressed to find whatever object you are looking at and find if it is the object you want, if it is log "Hi"

elfin isle
steep rose
#

did you put a debug.log in it to see if the raycast is hitting anything?

elfin isle
#

yeah in the other script

no, i didnt get anything back which i thought was weird

steep rose
#

put another one below the raycast method to see if it is hitting anything

#

Debug.Log("raycast hit" + hitInfo.collider.gameobject);

steep rose
#

Are you sure you have the script on the desired object?

#

show me the new script with the new debug.log in the !code format

eternal falconBOT
elfin isle
#

yes, and uh

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

interface  IInteractable 
{
    public void Interact();
}
public class Interactor : MonoBehaviour
{

    public Transform InteractorSource;
    public float InteractRange;

    void Start()
    {
        
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            Ray r = new Ray(InteractorSource.position, InteractorSource.forward);
            if(Physics.Raycast(r, out RaycastHit hitInfo, InteractRange))
            {
                if (hitInfo.collider.gameObject.TryGetComponent(out IInteractable interactObj)) {
                    interactObj.Interact();
                    Debug.Log("raycast hit");
                }
            }
        }
    }
}```
steep rose
#

I mean't place the Debug.Log("raycast hit"); below the raycast method which would be

            if(Physics.Raycast(r, out RaycastHit hitInfo, InteractRange))
            {
                  Debug.Log("raycast hit");
                    //etc
            }
elfin isle
#

ohh

#

so like t his?

            if(Physics.Raycast(r, out RaycastHit hitInfo, InteractRange))
            {
                  Debug.Log("raycast hit");
                if (hitInfo.collider.gameObject.TryGetComponent(out IInteractable interactObj)) {
                    interactObj.Interact();
                }
            }```
steep rose
#

yes

#

you might also want to use the LayerMask parameter in the raycast method to shorten the search of objects that can be hit

elfin isle
#

how would i do that?

also- the debug didnt work again

real grail
# elfin isle how would i do that? also- the debug didnt work again

Like this:

public class Interactor : MonoBehaviour
{
    [SerializeField] private Transform InteractorSource;
    [SerializeField] private float InteractRange = 5f;
    [SerializeField] LayerMask _mask;
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            Ray r = new Ray(InteractorSource.position, InteractorSource.forward);
            if (Physics.Raycast(r, out RaycastHit hitInfo, InteractRange, _mask))
            {
                Debug.Log("raycast hit");
            }
        }
    }
}
elfin isle
steep rose
#

you should probably configure your !ide

eternal falconBOT
real grail
elfin isle
#

ohhhh

steep rose
elfin isle
real grail
steep rose
#

do you see red squiggly lines in your IDE?

elfin isle
elfin isle
real grail
steep rose
#

Integrated Development Environment, AKA VS or VSC

elfin isle
#

ohhh

#

uh no, i see no squiggly lines in Visual Studio Code

steep rose
#

you should probably configure your IDE using the bot above

#

it will make things a lot easier

elfin isle
#

okayyy

#

update-

i went to those little links you sent and followed it, but everything says thers no update available

real grail
late burrow
#

is there a way to select 2 rigidbodies and quickly define if they the same object based on joints

elfin isle
steep rose
#

download the sdk

#

click the net sdk link and download it

elfin isle
elfin isle
late burrow
#

i mean in script

silent falcon
#

Hi, is it the correct method to avoid the click event being responded to by both the red child and the purple root at the same time by using the method shown in the red box in the figure?UnityChanHuh

elfin isle
# late burrow i mean in script

oh in that case no?

although, you can see if specific properties are the same i think using gameObject.getComponent<script>.property

although in your case it'd be rigidbody

then you can see if (line) = (line)

steep rose
#

you could restart to see if it goes away, also you should continue configuring your IDE if you have not already

elfin isle
steep rose
#

well do you see intellisense (i.e autocomplete) and do you have red squiggly lines and errors in the VSC console?

steep rose
#

Then it is not configured

#

if you followed all of the steps you can regenerate your project files in the external tools menu of preferences in unity

elfin isle
#

can i do the raytracing thing without configuring it?

id prefer to do configuration another day honestly

steep rose
#

sure you could continue tinkering with the raycast but it would be a lot easier if you did configure it

#

I would suggest !learning unity a bit more to understand these basic concepts

eternal falconBOT
#

:teacher: Unity Learn ↗

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

elfin isle
real grail
elfin isle
steep rose
#

show me your inspector with the object in frame

elfin isle
steep rose
#

where is your interact script?

#

"interactor"

elfin isle
# steep rose "interactor"

uh- the video i wa tched said it shouldn't go on the object, rather a different script that checks in the interactor script sot hat i could easily apply it to anything

#

public class TestInteract : MonoBehaviour
{
    public void Interact()
    {
        Debug.Log("hi");
    }
}
steep rose
#

you must have that script attached to something, I'm not familiar with interfaces so I couldn't go in depth into them.

teal viper
elfin isle
#
using System.Collections;
using System.Collections.Generic;

interface  IInteractable 
{
    public void Interact();
}
public class Interactor : MonoBehaviour
{

    public Transform InteractorSource;
    public float InteractRange;
    LayerMask _mask;
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            Ray r = new Ray(InteractorSource.position, InteractorSource.forward);
            if(Physics.Raycast(r, out RaycastHit hitInfo, InteractRange, _mask))
            {
                Debug.Log("raycast hit");
                if (hitInfo.collider.gameObject.TryGetComponent(out IInteractable interactObj)) 
                {
                    interactObj.Interact();
                }
            }
        }
    }
}```
teal viper
#

@elfin isle The other script needs to implement the IInteractable interface for it to work. Go through the tutorial again and pay more attention.

elfin isle
#

(i remember putting it there im gonna be honest i dont know why its not)

but i just tried it again with it and it still doesent work

teal viper
teal viper
#

I don't see your monitor from here.

elfin isle
#

i ran the code and added the IInteractable interface to it

teal viper
elfin isle
teal viper
elfin isle
teal viper
#

And are there any errors?

dapper scarab
#

I added vfx assets in a random moment I got this. How long can it be? Can I avoid it?

#

More than sure it will discard some changes, on top of it if I just close Unity, these vfx assets will be pink

pastel dome
#

yall think it would be practical and possible to do some sort of partial ragdoll physics for character flinch

#

like where the physics would determine the direction you flinch

toxic frigate
#

its for optimizing particlesystems but i think im missing something because with a lot of particlesystems its lagging about as much as the particle systems are

teal viper
teal viper
copper crest
#
using UnityEngine;

public class TUT : MonoBehaviour
{
    public AudioClip stop;

    void OnCollisionEnter ()
    {
        AudioSource audio = GetComponent<AudioSource>();
        audio.clip = stop;
        audio.Play ();
    }
} ```
dosent play on collision.
toxic frigate
#

are there any other issues other than that?

copper crest
teal viper
teal viper
teal viper
#

Does the other colliding object have a rigidbody+collider?

copper crest
#

yes

#

i just duplicated something that does collide and then applied this script to the object and now it dosent collide for some reason

teal viper
#

You'd need to share some more details then.

mint lion
copper crest
mint lion
#

have you tried a new scene with the bare minimum needed?

copper crest
#

ok ill try that rq

heavy knoll
#

anyone able to help with figuring out how to get my current movement script to work with Sebastian Lagues Spherical Gravity implementation?
https://hatebin.com/bvpdpsbkkd
https://www.youtube.com/watch?v=TicipSVT-T8&t=192s

Hi there, welcome to this tutorial on creating a simple first person controller that will function on spherical planets.

Updated source code for Unity5: https://github.com/SebLague/Spherical-Gravity
Original source code: http://pastebin.com/YBbFGZzD

Download the world model package by @danielsound here: https://www.dropbox.com/s/ul53h1g3nb5b9e...

▶ Play video
copper crest
#

bruh nothing works

heavy knoll
#

I also have a bit of a problem with how jumping works, it doesn't seem to detect if my player is grounded or not once it reaches a certain point on the side of the planet

mint lion
mint lion
# copper crest bruh nothing works

so ... new scene, you've added a cube with rigidbody and TUT script, added a plane underneath the cube. press play, cube falls and hits plane but OnCollisionEnter() isn't called?

echo ruin
wind hinge
#

Does unity call component update functions on gameobjects in dontdestroyonload before objects in the main active scene?

#

I want to make sure a certain singleton’s update is executing before a different monobehaviour’s that depends on it being set

teal viper
wintry quarry
wind hinge
#

Or, should I just do it in Update and LateUpdate?

wintry quarry
#

Yes

#

Or just have one script call a function on the other

wind hinge
#

I just thought of that and it makes so much more sense

wintry quarry
#

Or use an event

teal viper
#

If you have to do that, there's probably an issue in your system design

wind hinge
#

LateUpdate still happens before drawing

#

and end of frame

wintry quarry
#

Rendering is basically the last thing that happens in a given frame

wind hinge
#

So I want the order of stuff to mirror it as closely as possible - at least the things that depend on each other

#

This certain timer is supposed to increment right at the start of the update before its used anywhere further

#

But Update/LateUpdate solution will work just fine for this

wind hinge
#

.-.

#

Problem is, I guess that approach will only get me so far. It works for this particular case, but There is no infinite amount of updates in between Update and LateUpdate…

wintry quarry
#

Yes, see earlier suggestions made above

wind hinge
#

Oh the event approach, so like the timer updating thing would invoke one

#

and the listening components would work with it when they receive said event

lilac turtle
#

can anyone explain to me how momentum works?

wind hinge
#

Right praetor? Thank you

lilac turtle
#

so basically i got this normal fps movement script except the only relevant part is the hooking mechanism. basically when you hold e you cast a ray from the player's camera orientation and if the ray detects an object tagged "enemy" you get pulled towards the object. it has its own ease-in and ease-out but that doesnt matter. what i want to do is when i release i dont want to stop in mid-air and instead i wanna keep going in the same direction i was going with the momentum i was going with. can anyone help me out?

mint lion
lilac turtle
#

oh boy

#

alright well thanks a lot

mint lion
#

if the movement direction doesn't change (i.e. is set when you press E initially and you don't want to follow the enemy) then you can use a Vector for the movment (as you don't need to track the enemy)

lilac turtle
#

got it

#

thank you

loud haven
#

idk if this is the channel where i should ask this but im really new to this stuff im trying to get just a png of a gun in front of the camera for an fps no 3d model or anything, how would i do this?

burnt vapor
#

Even easier is to have a gameobject that uses the same coordinates as the camera (don't put it inside the camera because it will just create a lazy dependency on it) and to then put that quad in there. It saves the effort of having to figure out the coordinates

stiff abyss
#

Is it good idea to disable unity editor reloading domain on play

burnt vapor
stiff abyss
burnt vapor
#

If you answer "no" to these, then just leave it as it is

#

Unless you actually have an issue with it or want to speed up switching between edit and play mode, you can disable it. Note it exists for a reason, so you should be very aware that disabling it will have considerable effects on development

#

Also, if you are following a Youtube video which suggests you disable it, but doesn't explain why, I think you should stop watching that video because that person definitely doesn't know what they are talking about

astral sentinel
#

hello guys I'm new to unity and I want to learn it.

Which tutorial channel should I watch?

(Bu cümle türkler için) Unity'de yeniyim hangi tutorial kanalını önerirsiniz? En/Tr farketmez.

eager spindle
# astral sentinel hello guys I'm new to unity and I want to learn it. Which tutorial channel shou...

Learn to develop games using the Unity game engine in this complete course for beginners. This course will get you up and running with Unity. Free game assets included!

✏️ Course developed by Fahir from Awesome Tuts. Check out his channel: https://www.youtube.com/channel/UC5c-DuzPdH9iaWYdI0v0uzw

⭐️ Resources ⭐️
(To download assets you may have...

▶ Play video
eternal falconBOT
#

:teacher: Unity Learn ↗

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

astral sentinel
winter field
#

does anyone know how to add trimping(like tf2) to a non rigidbody character controller?

eager spindle
# winter field does anyone know how to add trimping(like tf2) to a non rigidbody character cont...

this is a side effect of the way source2 is made, all players have their own rigidbody. collisions are resolved by changing the player's velocity. if you have forward velocity, and you hit an angled ramp, your velocity is changed to be facing upwards instead.

to do this in a non rigidbody character controller you'll need to keep track of velocity. when the player dashes, add a forward velocity to your character. when the player hits a ramp, calculate the angle at which the player hit the ramp, and change the direction of the player's velocity from there.

#

even if you do use unity's rigidbody you may not get the same experience as source2's physics. youll want to study source2's physics more in depth

winter field
#

so i need to calculate each angle of every ramp the player is on?

eager spindle
winter field
#

i feel like its kinda expensive

#

like in performance

eager spindle
#

computers are fast enough nowadays youll be fine

winter field
#

ok ty

eager spindle
#

when we talk about "expensive" it matters most when youre doing it for hundreds of thousuands of players, but in your game you probably just have your main character doing it

#

in other words you can get away with it

winter field
#

oh ok

eager spindle
#

good luck

winter field
#

ty

cobalt vigil
#

guys what tutorial would u recommend in making a 2d top down rpg game, im pretty new to unity

grizzled rune
#

hi im trying to make ui for my game, i made a canvas and added a text mesh pro as a child, and this works but in the editor the canvas looks way bigger than the game, id prefer it to be the same size so that i dont have to keep zooming in and out, really not sure what i would google so im asking here 🙏

visual linden
# grizzled rune hi im trying to make ui for my game, i made a canvas and added a text mesh pro a...

I suppose you can scale the canvas down, but reality is you're stuck with your 2D and 3D elements trying to co-exist in the same space (bit of a Unity quirk from its unified 2d and 3d support) so it will always look a bit strange as long as you're dealing with screen space and world space elements in the same scene view.
My tip would be to right click the Scene tab and go to Add Tab -> Scene and have a separate Scene tab that is zoomed and aligned specifically for your UI, or alternatively create a prefab out of your UI hierarchy that you can drop in and out of to make changes.

hexed terrace
#

I suppose you can scale the canvas down
You can't scale a screenspace - overlay canvas

hexed terrace
tulip nimbus
#

Now where is the Death Loop that makes my Unity Editor crash once i collide with an object using this script?

private void OnCollisionStay(Collision collision)
{
    if (collision.collider.tag == "Player") 
    { 
        if (flagPercentMeter < flagPercentMeterMax)
        {
            flagPercentMeter += 0.1f;
        }
    }
}

private void OnCollisionExit(Collision collision)
{
    if (collision.collider.tag == "Player") 
    { 
        while (flagPercentMeter != 0)
        {
            flagPercentMeter -= 0.1f;
        }
    }
}
frosty hound
#

The while loop, the only loop in this code.

#

It's impossible for some random float number to land exactly on 0. You want to check if it's less than, in order to stop.

tulip nimbus
#

just for my personal udnerstanding

frosty hound
#

I guess that's one way to look at it. But it's per frame. The reason you're freezing is because you're stuck in an infinite loop on a single frame.

tulip nimbus
#

Thank you!

tender stag
#

im using the abstract class wrong right

#

should it be a normal class and then just System.Serializable

swift crag
#

An abstract class cannot be instantiated -- it isn't a complete definition

tender stag
#

im still trying to wrap my head around them

#

as i discovered them the other day

#

its like a base class for example for like a weapon

#

which would share all things each weapon would share right?

#

so like Shoot() method

#

ammo and magazineSize

#

or am i thinking wrong

#

and i'd then make another script like sniper, and make it inherit from the Weapon abstract class

eternal falconBOT
#

:teacher: Unity Learn ↗

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

swift crag
#

A sniper rifle is not conceptually different enough from a pistol to be worth the distinction

#

They'd both be a Firearm with different configurations

#

Most of my abstract classes are for things like filters and scorers

tender stag
#

true

swift crag
#
    [Serializable]
    public abstract class Scorer : IPolymorphic
    {
        public abstract float GetRawScore();
    }

    [Serializable]
    public class ConstantScorer : Scorer
    {
        [SerializeField] private float value;

        public override float GetRawScore()
        {
            return value;
        }
    }
#

e.g.

swift crag
#

In that case, a Firearm would be too ill-defined to exist on its own, and you'd have to derive from it and implement its abstract members to get a concrete class

#
Firearm whatever = new Pistol();
whatever = new Rifle();
whatever = new Firearm(); // invalid; you can't construct a Firearm
real thunder
#

I just made a shooting script and weapons exists as scriptableobjects configs

#

wonder if it's better or worse than having shooting logic on weapons

#

so, how do I properly create an empty gameobject via code?

wintry quarry
real thunder
#

totally nothing

wintry quarry
#

And generally it would be better to instantiate a prefab than create an empty GameObject

#

but creating an empty GameObject is as simple as new GameObject()

real thunder
#

is there a way to use instantiate for that?

wintry quarry
#

I don't understand the question. You can use instantiate instead of that.

#

you would instantiate a prefab, as mentioned

#
Instantiate(myPrefab)```
real thunder
#

but like, completely empty one

#

I can set each separately in a line of code

wintry quarry
#

with a prefab

#

the prefab can be empty if you really want.

#

but it seems weird for it to be

real thunder
#

creating an empty preferab feels really wierd

wintry quarry
#

Why does it need to be empty

#

A GameObject without any components is useless, and presumably you plan to do something with it

real thunder
#

I use makeshift origin shift system and I have something which lerps between 2 positions, if I just make those positions simple vector3 on world shift it would broke, so I create empty points so they are in the list of things getting shifted

wintry quarry
#

ok i mean - you have two options:

  • empty prefab
  • make a helper function that does all that in one line.
real thunder
#

fair enough

#

speaking of origin shift - is there anything better than just manually teleporting a list of transforms?

#

and rigidbodies instead of transforms if it's a rigidbody 🤷‍♂️

wind hinge
#

I have a component that makes a text pulse in and out opacity. The thing is, I want every text object that has this component to be completely synchronized. How would I go about doing that?

wintry quarry
#

or make one script that pulses them all in a loop instead of each handling its own

wind hinge
#

There’s no way to handle it with just 1 behaviour is there

wintry quarry
#

Change the script to use some kind of global timer instead of a local one

wind hinge
#

I’d need some sort of MouseTextSystem singleton in dontdestroyonload and a MouseTextPulse or smtn

real thunder
#

somthing like float lerpValue = Mathf.PingPong(Time.time, 1)

wintry quarry
#

Not necessarily... just use a global timer

wind hinge
#

if more instances exist

wintry quarry
#

that comes down to how you write your code

wind hinge
#

I could run it maximum once per frame

#

and cache it

cosmic dagger
wintry quarry
#

sure, that's one option.
Or use Time.timeAsDouble

wind hinge
#

The problem is that i need the opacity variable to be changing even if no object with a MouseTextPulse is active

wintry quarry
#

Then you have two options:

  • some central handler
  • Time.time(asDouble)
wind hinge
#

That’s what I figured

#

I would have to right some strange logic with time.timeasdouble

real thunder
wind hinge
#

Like mathf.pingpong

wintry quarry
#

What's "strange" about it?

wind hinge
#

Those methods are unfamiliar to me so I avoid them usualy

wintry quarry
#

it's just a little math

wind hinge
#

What happens when its a case where its not a linear triangle wave of up and down opacity?

wintry quarry
#

you can write whatever logic you want

wind hinge
#

Are there any cases where Time.timeasdouble would fail me?

#

To get a repeating animation

real thunder
wind hinge
#

Imagine there were 3 states instead

wintry quarry
#

You can even use an ANimationCurve, yeah

wind hinge
#

Fade in slowly, fade out faster and etc.

wintry quarry
wind hinge
#

Oh the animation curve lets me get a value for a given t?

wintry quarry
#

yes

wind hinge
#

Never used an animationcurve before

#

That sounds like exactly what I’d need

#

thank you guys

wintry quarry
#

AnimationCurve is the simplest/most configurable option

wind hinge
#

So then if it gets called more than once on the frame it’ll be deterministic (Using time.timeasdouble)

#

or the same i mean

#

For every object

#

and I can still cache it the first time its calculated, for the rest of the frame maybe? or is that a pointless overcomplication?

real thunder
real thunder
wind hinge
#

the calculation would be redundant to do say 100 times in the same update

real thunder
#

it would be redundat but calling an update for each text instance is also redundant

wind hinge
#

I want to do it from one single behaviour

real thunder
#

this case yeah do it once

wind hinge
#

So i was thinking to make a static field

wind hinge
#

The thing is I have code like lastTime and compare it to currentTime but I dont know how precise this is

#

probably not

wintry quarry
wind hinge
#

Why “in this case” would it be good? Also, thanks, Time.frameCount sounds like what I need.

wintry quarry
#

because Time.timeXXX things only update once per frame

real thunder
wintry quarry
#

even though they're floating point numbers they will bitwise the same value throughout the whole frame

#

I wouldn't really even use PingPong

wind hinge
wintry quarry
#

just something like

public AnimationCurve curve;

void Update() {
  float time = Time.timeAsDouble;
  time %= 1;

  float opacity = curve.Evaluate((float)time);
}```
wind hinge
#

Or is double very accurate

real thunder
#

right, if it's one instance doing it for everything, separate timer makes more sense

wintry quarry
#

but again Time.frameCount "feels" nicer for this anyway

#

so we should use that

real thunder
wind hinge
#

Sorry if that wasnt clear

#

I understand that, what you are saying

real thunder
wind hinge
#

I need to call the method that caches the result of the calculated color only once per frame… so there is a comparison of (lastTime != time.timeasdouble)…. I guess what I’m asking is if when time.timeasdouble increases smally by the next frame, is there low accuracy?

Sorry, this stems from a bad understanding about how doubles work. Am I confusing this for floating point inaccuracy?

lyric rapids
#

So I have my SwipeDetection class that I put on my Managers Empty GameObject (as tutorial suggested), now I wonder how I can emit event from that class and based on that event do some action in my PlayerController class so that I can move my player around.

wintry quarry
# real thunder I don't get it why would you need that

because they would/could do something like this:

static float timer;
static int lastTimeUpdated;


void Update()  {
  if (Time.frameCount != lastTimeUpdated) {
    timer += Time.deltaTIme;
    timer %= 1;
  }

  
  float alpha = myCurve.Evaluate(timer);
}```
rocky wyvern
wind hinge
#

Yes that is what I would use

wintry quarry
#

they change once between frames, and not again at all during a frame

wind hinge
#

By the next frame when it changes

rocky wyvern
#

Not an animation curve like an actual animation

#

Is there a reason ur scripting this

wintry quarry
#

time.timeasdouble increases smally by the next frame, is there low accuracy?
The == operator for double and float check for exact accuracy

wind hinge
#

lasttime and time.timeasdouble arent the same anymore (the latter has increased)

wintry quarry
#

they need to literally be the same bit pattern in memory

wind hinge
#

so the branch should execute once per frame right

#

ohhh

#

thanks

#

that is what I was asking

wintry quarry
#

but yeah I'd still use Time.frameCount if you're doing that

wind hinge
#

yea

#

thank you

cosmic dagger
#

doubles are more accurate. not much of a precision error compared to floats. is there any reason you haven't tested it yet? doing so will quickly see if there is an issue . . .

real thunder
wintry quarry
#

The main thing with Time.frameCount vs Time.time is that frameCount will continue to increment when Time.timeScale is 0

wintry quarry
real thunder
#

also I lost it on
timer %= 1;
what would that do

wintry quarry
#

It's usually more flexible/extensible to use a singleton

wintry quarry
#

it would just keep the value in the range 0-1

#

1.25 would become 0.25

#

it's to make it loop

real thunder
#

so basically pingpong(value, 1)?

wintry quarry
#

no

#

pingpong goes left->right->left-right

#

% will make it cyclical

real thunder
#

ah okay

rocky wyvern
#

I would just use events for this if you’re for some reason set on scripting it and not using an animation

real thunder
#

nevermind I just googled the thing and got a nice understanding

rocky wyvern
#

Just have some event that passes in the time when the frame changes and just listen to that no need for all this duplicate redundant code being run in update every frame

real thunder
#

yeah that's what he said about having a singleton being more useful

rocky wyvern
#

I wouldn’t make it a singleton but yeah

#

Event channel sounds a lot more elegant

real thunder
#

well, something would call the event

#

that would be a singleton?

wintry quarry
#

You would need a single driver to trigger the event yeah

#

And a single place to subscribe to the event

rocky wyvern
#

Well yeah but I wouldn’t hook the text scripts directly to the singleton because it really isn’t any harder takes like 2 minutes extra and just completely decouples them

wind hinge
#

Maybe ill use that instead

#

I thoight if I could contain the whole behavipur on one script itd be nice

rocky wyvern
#

I’ve said this before but why are you not using animations for this

real thunder
#

like... whole animations?

#

whole animator?

wintry quarry
#

Well using an animator seems overkill for this no? And also introduces other challenges with syncing them.

wind hinge
#

agh the issue with Time.time(asdouble) is that it dont get capped like time.deltatime does by default

#

For long pauses between frames

#

or times

wintry quarry
rocky wyvern
#

Animation system isn’t exactly complicated

#

Far easier to tweak the animations if you want it

#

And have multiple ones you just add another animation

#

Instead of having to script

wintry quarry
#

You have to:

  • Attach an animator
  • Make an animation clip
  • Make a state machine
  • Figure out how to sync them all (which needs more code, probably another script)
rocky wyvern
#

Didn’t they say they wanted different speed animations and stuff like one that’s slow one that’s fast or whatever

wintry quarry
#

AnimationCurve and a little code just seems easier to me until they actually start needing all the extra animator features

rocky wyvern
#

Come on this takes 45 seconds and ‘syncing’ the animations is easier than syncing a bunch of stuff with time.time and a bunch of maths

wintry quarry
#

Disagree

wintry quarry
#

there's no maths

#

the curve handles the maths

rocky wyvern
wind hinge
#

The other approach is having a singleton MouseTextSystem singleton that increment a field in Update, and a separate MouseTextPulse behaviour thats as simple as _text.color = MouseTextSystem.Instance.color in LateUpdate

hallow hound
#

Hey i have this public SavesManager but when i try to drag and drop the saves manager script it doesnt let me

rocky wyvern
#

I think you are vastly overstating the time it takes to drag and drop an animation controller onto some text

wintry quarry
#

Anyway this subject has outlived my attention span

real thunder
#

meanwhile you vastly overstating how hard it is to do that without animations

wintry quarry
#

those slots are for GameObjects that have the script attached

wintry quarry
rocky wyvern
#

Of course

#

But animations are just as easy

#

While being 100x as extensible

hallow hound
wintry quarry
#

Probably depends on your familiarity level

wind hinge
#

Im just not sure about polluting dontdestroyonload with such a basic singleton

#

idk if it would have any downsides

#

Or should I not care

rocky wyvern
#

I mean

#

And here we see an issue that would be fixed by not using it with a singleton and scripts

vast isle
#

I was wondering if anyone could help me. I'm on a fresh install of unity, this is my first time using it. All I'm trying to do is get my character to move left and right, nothing special.

Except my character constantly moves left.

I've checked for inputs in the input debugger, nothing. I disabled my movement script to see if it's a physics thing, still goes left.

It seems that for whatever reason, either there is some constant left input from somewhere I can't see, or my linearVelocity is getting multiplied by -1. I've been at this for hours, google is no help.

ebon sigil
#

One message removed from a suspended account.

rocky wyvern
#

Cross scene management is a lot easier without singletons

real thunder
rocky wyvern
wind hinge
#

I need it to be active on every scene anyways

burnt vapor
eternal falconBOT
real thunder
#

just a check on awake

wind hinge
#

If it’s per scene I would just create a single object with teh behaviour attached to it

#

Not use a singleton

vast isle
rocky wyvern
#

Because you can use like… an so event channel in project files instead of an object in a scene that needs to be constantly loaded in a ‘shared’ scene

real thunder
#

I gonna be honest I hate animators because they tank performance but I never really profiled them, instead I just use as few of them as possible

ebon sigil
#

One message removed from a suspended account.

real thunder
burnt vapor
real thunder
#

I never encountered a need for that soo I can't tell about that

frail hawk
rocky wyvern
#

If you want to have a singleton accessible throughout the entire game

#

And you also need to scene switch

#

You probably want to have the singleton on a separate shared scene

ebon sigil
wintry quarry
real thunder
burnt vapor
eternal falconBOT
#

:teacher: Unity Learn ↗

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

ebon sigil
rocky wyvern
ebon sigil
burnt vapor
naive pawn
ebon sigil
wind hinge
#

my singleton implementation already have this

#

it put it there

burnt vapor
rocky wyvern
wind hinge
#

ohhnvm

rocky wyvern
echo ruin
ebon sigil
burnt vapor
naive pawn
# rocky wyvern

most cases being physics. player movement doesn't have to be physics, you can just control it directly if you don't want any fancy acceleration/skid

rocky wyvern
naive pawn
vast isle
real thunder
rocky wyvern
wintry quarry
naive pawn
wintry quarry
burnt vapor
wintry quarry
#

it could be made simpler though with:
body.linearVelocityX = Input.GetAxisRaw("Horizontal");

rocky wyvern
#

Well ok we’ll ignore that there is a different way to do it that results in the exact same outcome while not doing something the documentation says not to do and will cause issues

wintry quarry
naive pawn
real thunder
wintry quarry
#

Unrealistic behavior - in most cases - is desired

#

this is a video game

vast isle
wintry quarry
#

not an industrial simulation

wintry quarry
#

unpluig all devices

#

disable bluetooth

#

make sure your keyboard doesn't have a cat resting on it

burnt vapor
#

I have never heard of a case where an input device can be stuck like that, interesting

wintry quarry
#

Usually I've gotten my keyboard wedged under something on my desk which causes this kind of thing

wintry quarry
verbal dome
#

(At least in 3d)

wintry quarry
#

Modifying velocity is functionally equivalent to AddForce

#

AddForce does one thing and one thing only, it modifies the velocity

#

it's just a matter of additive vs overwriting

#

you can achieve the same thing with either

vast isle
naive pawn
wintry quarry
#

They only have that warning because most people are not thinking carefully about what they set the velocity to

vast isle
#

Still goes left

wintry quarry
vast isle
#

Ok

naive pawn
vast isle
naive pawn
#

rq if you haven't restarted yet; try a keyboard test site

vast isle
#

Already rebooted

#

What is a keyboard test site?

wintry quarry
charred spoke
#

Odly enough I recently run into a problem where Unity would think that certain webcams were joysticks

#

Maybe it’s that

wintry quarry
#

Right ^ which is why I recommended unplugging all devices

naive pawn
vast isle
#

Reboot and it's working

#

Wtaf

wintry quarry
#

weird

echo ruin
#

FBI agent using his spyware and having a laugh

naive pawn
#

ghosts

charred spoke
#

Oh I am not the only in possession of this esoteric knowledge I see

wintry quarry
#

Yeah are you under federal investigation?

vast isle
#

Not that I know of...

wintry quarry
#

If you knew they wouldn't be doing their jobs right

vast isle
#

I work for a rather large tech company though so maybe...

charred spoke
#

Right I bet the reboot yeeted the webcam driver

vast isle
#

If I plug the webcam back in and it breaks, I will cry.

#

Ok, not the webcam

rocky wyvern
vast isle
#

F*** me sideways with a chainsaw...

It was my HEADSET CHARGER

rocky wyvern
#

I suppose you could set once on key down with no drag

rocky wyvern
#

But that has other issues

wintry quarry
#

we want responsive gameplay

rocky wyvern
charred spoke
#

Good to know good to know

vast isle
rocky wyvern
naive pawn
#

ok then what do you mean

naive pawn
#

and especially for beginners, there's less to get wrong

rocky wyvern
#

So I’m not saying physics on the game has to be realistic, but setting rb vel every frame can result in stuttering and stuff when you hit walls or get hit by objects

#

That’s what I mean by ‘unrealistic’

naive pawn
#

in my experience not at all

#

collisions are checked before stepping velocity

#

like the docs for MovePosition mention, lol.

rocky wyvern
#

It has been horrible for 2D in my experience I can say that much

verbal dome
naive pawn
#

make sure you're doing it in FixedUpdate and not Update 🙃

#

though actually doing it in update shouldn't have any issue either

verbal dome
#

With interpolation on (not none, not extrapolate)

naive pawn
#

since it's an overwrite and not a modify

rocky wyvern
#

Either way if super responsive feel good movement is your aim and you don’t care about external objects acting on your players rb I’d sooner use a kinematic rb any day

naive pawn
#

why wiuldn't you care about external forces

#

like mentioned before, gravity

#

and yknow.. collisions

#

why remake it all when it's built-in

rocky wyvern
#

You are directly setting rb.velocity every frame

#

If that is how you decide to go about things I would heavily assume you don’t care about like… having objects hit you and they move the players rb

wintry quarry
wintry quarry
naive pawn
wintry quarry
#

Think about Mario

#

Mario is the gold standard of platformer

#

he does not react physically to objects hitting him (thinking 2D marios here)

naive pawn
#

he dies

vast isle
#

Completely wrong, suddenly not fixed again WTF?!

wintry quarry
#

and do another sweep for USB or bluetooth devices

vast isle
#

I tried. Mike Oldfield showed up instead.

rocky wyvern
#

But if you DO care, directly setting rb.velocity every frame is not it

wintry quarry
#

Sure, and I'm just saying you are acting as if directly modifying horizontal velocity is a very unusual or dangerous thing to do - it isn't.

#

obviously, your movement code depends as always on your game's specific requirements

rocky wyvern
#

I’m not trying to say it’s the end of the world, but I don’t personally see any usecase outside of ‘it’s quick and easy’ for a prototype

#

Just direct setting velocity neither works well with external physics objects, nor does it feel especially good or fluid

wintry quarry
#

There are a lot of games for which physical accuracy is not a priority.

#

The "feel" of it depends heavily on what you set the velocity to though

vast isle
wintry quarry
#

there may be a misconception that we have to directly set the velocity to an analog of the current input value or that our movement code must be two lines long

wintry quarry
vast isle
#

And how does that work?

rocky wyvern
vast isle
#

Interestingly, there only seems to be a -1 input when I have the game window selected

#

Otherwise it shows 0

wintry quarry
#

Well that's... sort of expected as the game usually doesn't process input unless it has focus

vast isle
#

It worked once after that reboot, but hasn't worked again since. I'm so confused

#

I've unplugged everything

wintry quarry
#

Did you test the keyboard thing

vast isle
#

yes

#

It says no keys pressed when I press no keys

#

Went to Edit → Project Settings → Player → Other Settings and changed to new input settings. was previously on both

#

Now errors

#
UnityEngine.Internal.InputUnsafeUtility.GetAxis (System.String axisName) (at <c8b1b15e0c1a4cccb2a9ed91e2ed21c8>:0)
UnityEngine.Input.GetAxis (System.String axisName) (at <c8b1b15e0c1a4cccb2a9ed91e2ed21c8>:0)
PlayerMovement.Update () (at Assets/Scripts/playerMovement.cs:21)```
wintry quarry
#

you should/could switch active input handling to Both for now.

vast isle
#

oh

#

Welp

#

It now works after setting it back to default

#

RREEEE

hexed terrace
#

I personally have no idea, but you haven't given anything for anyone to help you with. See below !ask

eternal falconBOT
willow breach
willow breach
rich adder
willow breach
#

because idk where to put it haha..

rich adder
#

probably #📱┃mobile . But again no one can help unless you show at least the setup

hexed terrace
willow breach
#

i added the socket class i used, ill move the question there

naive pawn
#

im not seeing the issues you mentioned

languid spire
#

top of my head, as your code contains very little debuging I would guess at a CORS problem

rich adder
#

doesn't iOS have its own version of logcat? Check for errors first etc

rare basin
#

Trying to follow good programming practices, what is the best way to reference object A to object B, when object B is created during runtime? Obviously I dont want to use any Find() type methods. Object B is meant to move towards object A

naive pawn
steep rose
steep rose
rare basin
#

so basically my spawner of B objects should have reference to the object A, and pass that reference during initializign the object B?

verbal dome
#

That sounds decent to me

#

Given the info we have

rare basin
#

alright i'll go with that, thanks

#

but that doesn't sound right for me i think, let me break this down a bit. Right now i have EnemyBase.cs that has reference to EnemyStateController. I also have IState interface, and EnemyMoveState. I have Initialize() method in EnemyBase, and im calling it in the EnemySpawner class

#

so it'll be kinda big reference chain

rich adder
rare basin
#

passing from EnemySpawner to EnemyBase, then from EnemyBase to EnemyStateController, and then from EnemyStateController to EnemyMoveState

#

is that ok?

#

like my EnemyBase doesn't need to know anything about the target of movement

rich adder
#

imo not enough info to give a specific solution

rare basin
#

that's all i have right now, what more info would you need?

#

i literally just started and thats all i have

rich adder
#

just how its all going to work

rare basin
#

i could also make singleton from Player but idk if that's okay

rich adder
rare basin
#

well not even EnemyStateController

#

just EnemyMoveState

rich adder
#

i don't understand which reference you're trying to pass through

#

which one is scene object

rare basin
#

the player

#

I want to pass the player to EnemyMoveState

vast isle
#

@wintry quarry
ok
so
bug is back
but
Only when I click off the window and back on.
Then, I have to re-start the unity project to get rid of the bug

rich adder
#

oh okay so store it in 1 central script on the enemy if you need it in multiple places, then maybe fire an event so other scripts can also receive it @rare basin

rare basin
#
public class EnemyStateController : StateController
{
    private EnemyBase _enemy;

    public void Initialize(EnemyBase enemy)
    {
        _enemy = enemy;
        SetNewState(new EnemyMoveState(_enemy));
    }
}
#

and Init from EnemyStateController is called when enemy is created via EnemySpawner

#

i can make private Player _player inside EnemyStateController and chain pass the references but im not sure if this is okay? since only the EnemyMoveState needs to know anything about the player

rich adder
rare basin
#

so can I just store reference to the Player inside EnemyBase

#

if i need it in EnemyMoveState

rich adder
#

if you want something specific from "Player" instead of a Target or something more general

rare basin
#

later on yes

#

i'd need to access player's health

#

for example

#

in EnemyAttackState

#

atleast that is my idea, probably there is better way

slender nymph
#

why should the enemy need to know about the player's health?

rich adder
#

I usually access those at runtime rather than storing a reference, like physics query

rare basin
#

only EnemyMoveState and EnemyAttackState need to know anything about the Player

rich adder
#

why not access the component you need ON the attack

#

like Raycast or Overlap

#

storing Player is dirty spaget imo

rare basin
#

alright but thats different topic, what about the move state thing

#

i need to specify the position where to move somehow

#

for the enemy

rich adder
#

make a iTarget interface and use Transform or .position/TargetPos

rare basin
#

and i dont want the Enemy to know anything about the Player when only EnemyMoveState needs to know the position

slender nymph
rare basin
#

i understand that EnemyMoveState just needs a Vector3 position

rich adder
#

Vector3 targetPos
done

slender nymph
#

okay, and i've already provided a resource to you about how to get a reference to the player

rare basin
#

but i need to get the player's position somewhere somewhat and thats what im struggling with

#

where/when do i get the reference to player's position

verbal dome
#

What's wrong with passing the target player (or its transform) to the state directly

rich adder
#

if its a moving state it makes sense to have a target transform / pos

rare basin
#
public class EnemyMoveState : IState
{
    private EnemyBase _enemy;
    private Vector3 _targetPosition;
    
    public EnemyMoveState(EnemyBase enemy, Vector3 positionToMove)
    {
        _enemy = enemy;
        _targetPosition = positionToMove;
    }
    
    public void EnterState()
    {
        PoolManager.Instance.ReleaseToPool(_enemy.GetStartingData().EnemyType, _enemy.gameObject);
    }

    public void UpdateState()
    {
        //move towards _targetPosition
    }
    
    public void ExitState(){ }
    public void OnEnable(){ }
    public void OnDisable(){ }
}
verbal dome
#

Idk I would probably have a FollowPlayer(Player targetPlayer) method somewhere on the NPC
It would create/set a new EnemyMoveState and pass that player into it

rare basin
#

so the goal is simple, i spawn enemy, set new state to EneymMoveState and that's all

#
public class EnemyStateController : StateController
{
    private EnemyBase _enemy;
    
    public void Initialize(EnemyBase enemy, TowerBase tower)
    {
        _enemy = enemy;
        
        SetNewState(new EnemyMoveState(_enemy));
    }
}
#

i call this Initiailze when spawning the enemy

#

i just need to pass the Vector3 in SetNewState as 2nd paramter

#

and that vec3 should be player's position

#

my question is... how/where to get the player's pos

verbal dome
#

Use a second method?

#

Oh

rare basin
#

i can just have reference to the Player in main Enemy class but i was told its not a good idea

verbal dome
#

Well, is it always "player one" or can they target other NPCs?

rare basin
#

since enemy doesnt need to know anything about player

rich adder
rare basin
verbal dome
#

Keep the player reference in a singleton or such?

rich adder
#

I would just store a Transform or a Target component, incase you want later to change it from the player to something else

slender nymph
rare basin
swift crag
#

There's a whole spectrum of valid options here.

rare basin
#

i understand that and im trying to figure out what's the good way

#

i'd need to access other player's components in other states

#

like EnemyAttackState (i would need PlayerHealth) reference

rich adder
rare basin
slender nymph
rich adder
verbal dome
#

Why is it wrong to have a player reference in the state?

#

I dont get it

rare basin
#

idk im confused

rich adder
#

each scripts should have their own Target component or alike, they are more modular imo

verbal dome
#

There are many ways to make a state machine

rare basin
rich adder
#

each script does different thing with Target

verbal dome
#

There's no single rule for what can know about what

rare basin
#

but that's a topic for later, right now i just want to move the enemy towards player 😢

rich adder
#

store Transform target and be done with it lol

slender nymph
rare basin
#

when onyl EnemyMoveState needs it

rich adder
hallow hound
#

question, im saving some info in a json, it apears to get save correctly but when i restart it snt, is this on purpose that unity deletes the info when restarted or is it something wrong with my code

swift crag
rare basin
tiny vault
#

What's the best way to store a scene object in a SO? I want a specific image per SO, and displayed when it's active, but i can't drag the object with the image into the SO's image field

wintry quarry
rare basin
swift crag
rare basin
#
public class EnemyStateController : StateController
{
    private EnemyBase _enemy;
    
    public void Initialize(EnemyBase enemy, TowerBase tower)
    {
        _enemy = enemy;
        
        SetNewState(new EnemyMoveState(_enemy));
    }
}

@swift crag

slender nymph
swift crag
#

but it's pretty easy to work around

rich adder
rare basin
verbal dome
tiny vault
hallow hound
rich adder
swift crag
#

Oh, you're talking about objects in a scene

#

I thought you were talking about storing references to a specific scene

rare basin
#

is making the player singleton a good idea then

#

so i can easily reference it whenever i need

verbal dome
#

Someone will nag about it but it's extremely common

rich adder
swift crag
#

It becomes a problem if you want enemies to be able to attack other stuff

rich adder
swift crag
#

or, more generally, do anything to anything other than the player

rare basin
#

i guess my entire architecture is fked up

verbal dome
#

Doesnt seem too fucked up to me

slender nymph
#

it also becomes a problem if you want to have more than one player (such as for networking or even local)

rich adder
#

singleton where a bandaid to bigger issue avoiding a simple proper DI

rare basin
#
public class EnemyMoveState : IState
{
    private EnemyBase _enemy;
    private Vector3 _targetPosition;
    
    public EnemyMoveState(EnemyBase enemy, Vector3 positionToMove)
    {
        _enemy = enemy;
        _targetPosition = positionToMove;
    }
}

i'll refactor it like this, and just pass the positionToMove when creating the EnemyMoveState in the state controller

#

so it's more modular

rich adder
verbal dome
#

You might want to follow a player
You might also want to follow another object
So better use a transform reference or maybe an interfacecs interface IPositionTarget { Vector3 GetPosition(); }
That you can wrap the transform into if needed

rich adder
#

v3 just store copies unlike reference type

slender nymph
# rare basin so it's more modular

the "more modular" approach would be to have the enemy object keep track of its target and the states just access it from there. that would then allow you to dynamically change the target if that ever becomes necessary. but of course you've been arguing against this option by saying other people told you not to do that

rare basin
#

just trying to understand, im confused

verbal dome
#
public struct ITransformPos : IPositionTarget { public Transform transform; public Vector3 GetPosition() => transform.position; }```
#

That's what the wrapper could look like

rich adder
#

literally 20 mins ago

#

enemy script gets the target then fire OnTargetChanged?.Invoke(target) and other scripts on enemy react to it

rare basin
#

it's better to create some kind of ITargetable

rich adder
#

I would use something like Target or interface as suggested

verbal dome
#

I like my NPCs to have a member that is basically a dictionary with values that the states need

#

And fields/properties for commonly accessed stuff like target

verbal dome
#

Enums or strings

#

Enums preferred

#

It's commonly called a "blackboard"

rare basin
#

i like that idea tbh

#

so it's like a mediator

verbal dome
#

Like the parameters for a shader/material, or the parameters for an animator