#💻┃code-beginner

1 messages · Page 691 of 1

wicked fiber
#

Im making a 2D game, and I can't figure out why this sprite is rotating on axis other than the z axis. I've tried stuff like locking rotation, but I can"t figure it out.

wicked fiber
#

Oh, that makes sense.

teal viper
#

That would make it face the other object

wicked fiber
#

yeah, using vector 3 right?

teal viper
#

Whether it's vector 3 or not is unrelated

wicked fiber
#

Well I want it to look at the mouse, just only using the z-axis

ivory bobcat
# wicked fiber Im making a 2D game, and I can't figure out why this sprite is rotating on axis ...

Try debugging stuff:cs Debug.Log($"Initial Position: {transform.position}"); transform.position = Vector2.MoveTowards(transform.position, player.transform.position, 100000000); Debug.Log($"Position after moving: {transform.position}"); transform.LookAt(mousePos, transform.up); Debug.Log($"Rotation after looking: {transform.eulerAngles}"); transform.position += transform.up * GunHover; Debug.Log($"Position after offset: {transform.position}");

wicked fiber
#

Alr

teal viper
wicked fiber
#

Heres some pics of what's happening

teal viper
# wicked fiber

Yep. The blue arrow(representing the object forward direction) is probably facing your mouse position.

wicked fiber
#

Than how would I fix this?

#

use another axis?

teal viper
#

Don't use look at. Its specifically for 3d

#

You can assign the correct direction to the object transform.right for example

wicked fiber
#

ok thanks!

#

for some reason the object is rapidly switching directions

ivory bobcat
#

What does the current code look like?

wicked fiber
#

transform.position = Vector2.MoveTowards(transform.position, player.transform.position, 100000000);
Vector3 mousePos = (Vector2)cam.ScreenToWorldPoint(Input.mousePosition);
transform.LookAt(mousePos, transform.right);
transform.position += transform.up * GunHover;

ivory bobcat
#

He mentioned to remove LookAt

wicked fiber
#

What would I replace it with?

ivory bobcat
#

Instead, you'd be assigning a direction to the right property of transform.

wicked fiber
#

transform.up = mousePos - transform.position;

#

is that good?

#

It works!!!!!

#

thank you both for the help

ivory bobcat
#
transform.right = (mousePos - transform.position).normalized;```
#

Maybe you won't need to normalize

wicked fiber
#

Oh yeah...

#

Whoops

lunar hollow
#

Are there any functions for when Animations have Applied in this frame? So that i can modify the transform after the Animation is applied?

lunar hollow
#

Oh youre right! The issue was because of my update mode, thanks!

latent mortar
#

i am doing the junior programmer course on unity learn, there is a part where you have to make a car that can drive and turn and i have done everything as it is shown in the tutorial but the car does not turn when i hold A and D, there is no error in the console, here is my code

eager spindle
#

Good golly this paste site is not usable on mobile

latent mortar
#

pretty much copied it off the tut'

#

that is the problem

#

the turnspeed's value does not change even tho the horizontalmovement value does

latent mortar
rich ice
# latent mortar not sure

if the script is attached to an object (which it should be) you can see the variable's value in the inspector

eager spindle
# latent mortar not sure

At the top of the page, you declared public float turnSpeed; but didn't set it's value. At the moment, it's 0.
The tutorial might expect you to set the value of turnSpeed by going to the GameObject that has the script, and set the value there.

You're doing Vector3.right * Time.deltaTime * turnSpeed * horizontalInput, since turnSpeed is 0 as you haven't set it, the whole thing is 0

eager spindle
#

change it to like 4

latent mortar
#

okay

#

so simply just

eager spindle
#

that works too

#

I'm not sure if the gameobject will update it though

latent mortar
#

hmm still seems to be on 0

eager spindle
#

Just remove public for now if you don't need it to be changed by other scripts

latent mortar
eager spindle
#

Change it to 4

eager spindle
#

Change it to 4

latent mortar
#

oh🤦‍♂️

eager spindle
#

The ones that are greyed out can't be changed, but this one can be changed 👍

north kiln
#

The value assigned to a serialised field in code is just the default

latent mortar
#

works now😭😭😭

eager spindle
#

Huge

latent mortar
#

wait but one last thing

#

now i have to manually change it when i click play

#

how do i make it already at 4

north kiln
#

Just set it before you enter play mode

#

And save

latent mortar
#

kk

rich ice
#

most things changed while in play mode wont save

latent mortar
#

man i am going to fail at the common sense test

eager spindle
#

there are many things to get used to with unity

#

don't be too hard on yourself

rich ice
#

yup, you get used to it eventually

latent mortar
#

thanks yall

past halo
#

auhg

radiant zinc
#

how do I change the color of 2d scene I cant find no background color setting ( UNITY 6 )

eager spindle
#

can you go to your camera

#

there's a colour picker in there

#

just pick the colour you want

radiant zinc
#

nope I dont think so

eager spindle
#

very very old image but something like this

eager spindle
eager spindle
radiant zinc
#

yes I used to have it too in older version didnt use unity for a while now im back cant find that

#

ok

eager spindle
#

Unity 6 things

radiant zinc
#

the env

eager spindle
#

Then you'll get the color picker

radiant zinc
#

omg bruh im dumb

#

also thx helped out

eager spindle
#

Unity 6 things

radiant zinc
#

hey another question I got how do u add an image in the new toolkit ||im trying to figure out how to use it so may be rly obvious but idk it||

radiant zinc
#

forgive me if im wrong but isnt this what the stylesheet is

I cant seem to find any componenet thats an image but ig I should rather check the manuals

ivory bobcat
rich ice
finite mango
#

looking to turn off all trail renderers' emmissions when a float called brakeInput is above 0.5f. Ive confirmed that the input is working as intended but the emission never changes from on to off.
function is called in Update()

    private void BrakeFX()
    {
        bool targetState = false;

        if (brakeInput > 0.5f)
        {
            targetState = true;
        }

        if (isBrakeTrailing == targetState)
        {
            return;
        }

        foreach (Transform child in brakeTrails)
        {
            child.gameObject.GetComponent<TrailRenderer>().emitting = targetState;
        }
        isBrakeTrailing = targetState;

    }

isBrakeTrailing stores current state of trail renderers' emission
brakeTrails is the parent gameobject to the trail renderer gameobjects

nvm, this code works. think i entered gamemode before it updated the script last time 🤦‍♂️

eternal falconBOT
jolly stag
#

Hello all I was wondering if I could get some help with the instantiate, I'm trying to make a simple bow and arrow system which involves getting an arrow to spawn relative to the players using an offset same offset. I've tried tying it to the MainCamera, Player and the bow object the player holds but I'm still not having any luck with it following rotation or across the Z axis. Thanks!

#
{
    private WeaponSwitch weaponSwitch;
    public GameObject arrow;
    public GameObject player;
    public float fireRate = 2.0f;
    public float draw = 0f;
    public bool canFire = true;
    private bool drawWait = true;
    public Vector3 offset = new Vector3(0, 0, 2);
    public Camera playerCamera;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        weaponSwitch = GameObject.Find("Player").GetComponent<WeaponSwitch>();
        playerCamera = Camera.main;

    }

    private void FixedUpdate()
    {

 
    }

    // Update is called once per frame
    void Update()
    {
        if (weaponSwitch.one && Input.GetKeyDown(KeyCode.E) && canFire)
        {
            Debug.Log("Fire can be done");
            Instantiate(arrow, new Vector3(playerCamera.transform.position.x, playerCamera.transform.position.y, playerCamera.transform.position.y), transform.rotation);
            canFire = false;
            StartCoroutine(FireRate());
        } while (Input.GetKey(KeyCode.V) && drawWait == true) // Increases draw while V is held down
        {
            draw++;
            StartCoroutine(BowDraw());
            drawWait = false;
        }
        if (Input.GetKeyUp(KeyCode.V))
        {
            draw = 0;
        }

    }
    IEnumerator FireRate() // creates a methord outside of the update timer
    {
        yield return new WaitForSeconds(fireRate);  // creates a timer that waits for number seconds before deloying code below
        canFire = true;
    }
    IEnumerator BowDraw()
    {
        yield return new WaitForSeconds(0.5f);
        drawWait = true;
    }
}```
keen dew
#

That code doesn't seem to use the offset vector at all

#

but the easiest way is to add an empty gameobject as a child of the player or camera to where you want the arrow to spawn and then use that object's position and rotation when instantiating

crisp glen
#

Sup guys, anyone know where to find a good tutorial explaining how to make 3D first person player movement with the new input system? I am a complete beginner to scripting.

keen dew
devout flume
#

I had a question about games & modding, are compiled C# games moddable no matter what? (Using BepInEx or any other modding injection toolkit)

rich ice
devout flume
#

But I understand that

rich ice
#

yeah it's in the #📖┃code-of-conduct
although afaik, there's no way to completely stop modding, you can just make it more difficult. il2cpp games are much harder to mod if i remember correctly, i've never used it myself though.

devout flume
#

Yeah that's the only thing I saw online so far. My bad for the question, thanks for your time though 🙏

sage mirage
#

Hey, guys! I am currently trying to create smooth rotation of a game object specifically a crucifix to a specified angle but for one reason the game object is rotating in pivot instead of center. Is there a method or something that can handle it?

wallCrucifix.transform.rotation = Quaternion.Lerp(wallCrucifix.transform.rotation, targetRotation, Time.deltaTime * 2f);```
#

It rotates the game object to the target rotation but the issue is that it doesn't happen in the local position of the game object but it seems like in world position

wintry quarry
#

but you are asking about world space vs local rotation?

#

If you use transform.localRotation it will rotate in relation to its parent

#

is that what you are after?

#

It will be using the pivot of the object either way.

sage mirage
#

Yes let me show me very quickly

tiny bloom
#

if I have one prefab that's used as a projectile
is there a way to tell it to pass through specific layers and hit specific layers at runtime?

im trying to do something like an arrow projectile that can be shot by players and enemies
and depending on who shoots, it decides on its own who to hit and who to pass through

lethal meadow
sage mirage
# wintry quarry Rotation always happens around the pivot

Alright, first of all the game object is a parent game object it doesn't have any child objects. The first rotation in the video is what is expected to happen but it doesn't. The second rotation is happening right now like with pivot.

wintry quarry
sage mirage
#

I think you can see it right now

wintry quarry
sage mirage
#

Really? How to do it?

wintry quarry
#

you can also just add an empty parent object to this thing and rotate that

#

then just position the cross where you want as a child of that

sage mirage
#

I have seen many times the gizmo at this place

wintry quarry
sage mirage
#

and in different places

#

How to do it in blender XD I have never used blender only one two times

lapis quail
#

For anyone like me who is just starting from complete scratch intending to make games in Unity, this course from the Microsoft C# documentation website is a great first step and I wish I started with it before losing myself in Unity tutorial hell right off the rip. Here is the link if anyone is in the same boat and doesnt know where to start!

#

hopefully someone finds this useful!

wintry quarry
#

after placing the cursor where you want.

tiny bloom
tiny bloom
rich adder
sage mirage
wintry quarry
#

right under the message you responded to

rich adder
#

btw its the pivot not gizmos, gizmos is the visuals you are seeing that represent that pivot point.. a little bit of pedantic note for ya

foggy yoke
#

I'm a newbie, so sorry if this is a dumb question. How can I check if the player collides with a clone (an object instantiated at the start)?

wintry quarry
#

assuming you're using Rigidbodies

foggy yoke
wintry quarry
#

you can have the collision handling logic on either the player or the obejct the player is colliding with

#

Do wahtever makes sense in your particular case

foggy yoke
#

Alright.

#

Thank you.

dense sparrow
#

Anyone knows why this problem occurs when trying to render a 2D sprite UI element that has a 2 px black border?

#

Some of the sides become invisible and uneven

rich adder
#

also not a code question..

brazen aurora
#

im trying to make multiple attack types like stabbing and sweep attacks for different weapons. i put these attacktypes inside of an enum. when i only had one it worked fine, but then when i added the sweep type, that works fine, but the stab type doesnt work at all. the attack cooldown doesnt reset, the animations dont work, and it doesnt resest the isAttacking bool. ive been at this for hours please help. tell me if you need more code

dense sparrow
brisk flint
#

if always sweep then its how u are setting attacktype

brazen aurora
#

can i not just set it in inspector?

brisk flint
#

ssetting in inspector does not mean something is not overwriting in code

brazen aurora
#

so how would i go about making it when i select the type in the inspector it will actually overwrite a variable or whatever

brisk flint
#

write a debug log to log attacktype in the start of this method

brazen aurora
#

yh i did that and its just giving sweep so thats always active

#

so how do i set the attack type with the enum

brisk flint
#

attacktype = AttackType.Stab

brazen aurora
#

ok i looked into enums a bit more and found that its being set to only sweep because thats how i put the prefabs into the inspector, if the weapon prefabs in a different order, its then the stab weapon that works and the sweep weapon that doesnt work

wintry quarry
brazen aurora
#

ive set it in the inspector, however that attack type just ends up being the last weapon ive placed into the scene instead of just being the weapon im holding

wintry quarry
#

that's a broader logical error in your code

#

nothing to do with enums at that point

rich ice
#

!code

eternal falconBOT
brazen aurora
wooden hill
brazen aurora
wintry quarry
#

This is your problem

#

You have multiple weapons in the scene

#

you're just doing FindWithTag("Weapon")

#

in essence, you are just finding a random weapon

brazen aurora
#

so to fix it would i get the component from the weapon that im holding using the collider?

wooden hill
#

weaponController still is the old one

#

and that's why calling weaponController.Attack() attacks how the old one would because you're literally still using the old one

wintry quarry
#

when you grab the weapon, then you assign the weapon reference

#

you already have grab logic

#

use it

#

in a sense you're already ding it with activeWeapon = collision;

#

but that's a Collider reference, you need to get the Weapon component too

brazen aurora
#

yh i meant to get the component in the grab function

wooden hill
#

yea just get it in the grab interaction

brazen aurora
#

thank you so much it finally worked

wooden hill
#

as long as you learned from it that's good

ember tangle
#

Plane.Raycast(Ray ray, out float enter);

I dont understand float enter here

naive pawn
#

anytime you see Type name, that's declaring something called name of type Type

#

here you're declaring a new variable enter of type float

#

out is a modifier, meaning the function will take the variable given and assign to that variable

#

you could also write the declaration separately:

float enter;
Plane.Raycast(Ray ray, out enter);
```writing the declaration within the `out` argument is just a shorthand
ember tangle
#

I guess what I do not understand is why that float can become a vector3: ```// Calculate the planes from the main camera's view frustum
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(Camera.main);

//different syntax to regular use so far. shoots ray from ship to target direction.
Ray ray = new Ray(player.transform.position, player.targeting.TargetDirection(player));

//not sure
float enter = 0;

for (int i = 0; i < 4; i++)
{
if (planes[i].Raycast(ray, out enter))
{
pointer.transform.position = Camera.main.WorldToScreenPoint(ray.GetPoint(enter));
break;
}
}```

#

specifically here ray.GetPoint(enter)

naive pawn
#

it doesn't

#

it's not transforming the float into a Vector3

#

it's using enter as just another variable in the calculation of ray.GetPoint

#

something like ray.origin + ray.direction * enter

ember tangle
#

hmmm I guess that makes more sense

#

On a related note, my code works if the ray intersects the left or right of the screen frustum, but is above the screen if the intersection is the top of bottom frustum plane:

#

here is more meaningful image of the one that works:

#

second one doesnt have that marker on the top side of the screen

echo ravine
#

I am sometimes having some random errors like "something out of view frustum". I searched it and i didn't find a good solution. It also just gave me a dividing by zero error that fixed when i RESIZED THE GAME SCREEN.

naive pawn
ember tangle
#

I guess frustum planes are infinitely long.

naive pawn
#

planes in general are infinite

naive pawn
vestal cosmos
#

in a game if you have multiple levels how do you make them

rich adder
astral citrus
#

Hi! Could you help me understand - I know there is Animancer asset in Unity3d asset store, I wonder if it's worth using or there are other options?
I've tried using Unity OOTB approach (with states, triggers etc.) and it feels a bit clunky when I need to do something when animation finishes or mid-animation.
For example right now I have this code to check if Animation finishes to trigger some action

            {
                var state = _animator.GetCurrentAnimatorStateInfo(0); 
                return state.shortNameHash == animationNameHash && state.normalizedTime >= 0.90f;
            }, cancellationToken: _animator.GetCancellationTokenOnDestroy());
naive pawn
#

animation events are a thing

#

you generally would use those to sync mid-animation actions

astral citrus
#

I feel it's very brittle to use this, since maping done via some string in some place (not sure how to explain it)

naive pawn
#

magic strings?

#

if you select an animator before setting the animation event, you get a dropdown, so you don't have to type the method name yourself

#

but it is stored as a string and comes with the risk of accidentally breaking the reference with renaming (for example) of course

sour fulcrum
#

Not that I have a better solution but in general I do agree animation events feel a little gross and tucked away compared to a majority of workflow in Unity

grand snow
#

They arent super reliable so observing the animator state like this may not be soo bad

naive pawn
#

i do have a utility type to wait for animations completing specifically, that helps

eternal needle
#

or even Update i guess. either way it gives you access to the same values like normalizedTime

astral citrus
#

Thanks! I will check, didn't see this one. I believe I heared there some issue with it + Animator, but didn't check myself.

earnest wind
#

Hey guys, i need some thinking power again

If i want to make 2 sliders, one for Saturation and one for Value

Then how would i calculate the colors that have to be on both sides in the gradient?

#

For example in RGB (R) i would just do (0, G, B) - (1, G, B)

wintry quarry
#

Same thing here

#

but for HSV

#

in the Hue slider you would do (0, S, V) - (1, S V)

earnest wind
#

Mhm i see

#

Thanks

wintry quarry
#

for the saturation slider you do (H, 0, V) - (H, 1, V)

earnest wind
#

Hue shouldnt change, its like a static rainbow

#

Typo i meant to say shouldnt**

copper ravine
#

Hi, i need to make a transparent Window (except GameObject’s) and borderless on Linux, on windows ik there is a simple api for this, but on Linux it’s hard to make. Has anyone ever done something like this before?

rich adder
#

libX11 through PInvoke etc.

copper ravine
#

For now I have border less window but it’s black not transparent, and idk what I can do next, maybe other USE flags idk

#

I use wayland with kde

#

But unity is running under xwayland

rich adder
#

wayland is even harder to work with

copper ravine
#

Ikkk

#

In Godot I have this done in seconds

#

But export unity projects to Godot is pain

grand snow
#

you can use native code with unity so it surely can be done
if its an in engine function, check the src

copper ravine
#

And I’m in black hole

rich adder
#

could look into GTK#

lapis quail
#

hey my dice roll is not random it returns 5 every time what am I doing wrong?

'Random dice = new(0);
int roll = dice.Next(1, 7);
Console.WriteLine(roll);'

#

oh thats not right. idk how to do code boxes on here

grand snow
#

use UnityEngine.Random instead

#

you are seeding a new Random instance the same each time 😐

wintry quarry
#

yes with the same state (0)

lapis quail
#

its just C# im following the microsoft tutorial it says it should be working

grand snow
#

same seed = same results

eternal falconBOT
wintry quarry
#

whatever tutorial you're following is certainly not creating a new Random instance every time

grand snow
#

this is a unity server too

wintry quarry
#

But yeah if it's not a Unity question, it doesn't belong here

lapis quail
#

okay sorry

rich adder
#

!csharp

eternal falconBOT
copper ravine
#

Can I paste my code here?

rich adder
copper ravine
#

Idk how to use that 😭😭

rich adder
#

for the link ones just paste it on the site , hit save and send generated link

copper ravine
#

Like that?

#

I don’t test it but it’s my idea

grand snow
#

If this was me id make a small lib to do this instead

rich adder
#

my suggestion earlier similiar, use something like GTK# or something to interact with as middleman

#

..actually nvm you'd need to make a new window with it.

#

wayland is a bit confusing lol

copper ravine
#

Fr

#

That is why i use xwayland for unity

rich adder
#

what are you making anyway ? whats the usecase here

#

if its like a specific app you could just embed unity as library in a native app / toolkit

copper ravine
#

I am determined to fork mate-engine for Linux and I want to learn something about unity and C

rich adder
#

...depends on how deep the rabbit hole you're going...

copper ravine
#

I think the worst thing in my idea is everything about window rendering

rich adder
#

yeah no idea, you need a way to make those native calls and seems window transparency is a crucial part of the companion app you want to make

copper ravine
#

Idk, how I can search this on google?

#

Even chatGPT can’t help me

rich adder
#

start with finding out how to do it natively maybe a shell command or library, go from there

copper ravine
#

I can do this very easily with python/C++ natively

rich adder
#

so then do it so, then make that call from unity

copper ravine
#

But how connect this to unity

rich adder
#

use interop calls

#

you can call functions from unity to c++ / python libraries

copper ravine
#

I can with this render full window?

#

Okey okey, so how to set up project settings?

rich adder
copper ravine
#

Sorry, build settings

rough granite
#

File, Build Profile?

copper ravine
#

YEA

rich adder
#

you don't need special build settings

copper ravine
#

Exactly

#

Ou okey

#

Sorry I’m newbie

woeful scaffold
#

Hey guys, im aiming to have the skills to make 3d gamse, do you guys prefer to use a pre-made asset player controller? or do u usually make ur own

#

I'm pretty sure I can't make it on my own, but I assume it'll be good to learn to do it on my own?

woeful scaffold
#

guess so, i'm not sure myself, i wanted to have something similar to risk of rain 2 but i think its hard to make

#

as in the control and third person view

#

i find myself defaulting to first person as its easier?

wintry quarry
#

No way to learn other than trying

woeful scaffold
#

yeah i made sure to get that

#

cool stuff, i need to go through the doc of it

wintry quarry
#

But it's not a full solution, it's a building block

woeful scaffold
#

im a little worried about animations and attaching the animations to attacks or so

#

but thats far ahead so ill just see what i can do for now

wintry quarry
#

Yeah, do that later

woeful scaffold
#

i feel lost when it comes to the code, i used chatgpt a couple times but it really feels just like copy and pasting therefore not learning much

wintry quarry
#

You won't learn by asking CGPT and copying code.

shell knot
#

First question here, sorry in advance if my programming-speak is not up to par yet.

I am so close to adding a "Rotation" to my "Spaceship". I've set up the actions and binds following a tutorial for 3 dimensional movement with some modifications for an Ascend/Descend. All of this is working great, under the ShipMovement -> 3D Vector stuff. But, making the RigidBody of the ship just ROTATE on the Y axis is proving very complicated.

Just looking for some guidance on the next steps, I am trying to add Q and E as Yaw Left and Right controls. Should these also live under ShipMovement for simplicity? Or should I treat them as a new Action entirely like in the screenshot? If I have them as new Actions, I would have to call them separately from ShipMovement in my script, correct?

wintry quarry
#

Oh sorry, misrread your question

#

definitely do not try to shove rotation and movement controls into a single input action,. no

#

that doesn't make any sense and will confuse things

#

Also you haven't actually shown any code here so it's not clear what part you're actually having trouble with

#

making the RigidBody of the ship just ROTATE on the Y axis is proving very complicated
It shouldn't be.

shell knot
#

I guess my first question is what function should I be using to rotate a rigid body in the first place? I've seen rb.MoveRotation, rb.AddTorque, but can't quite get the right combination of variables to make either work. Here's an attempt using rb.MoveRotation:

//using System.Runtime.CompilerServices;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.InputSystem;

public class playerController : MonoBehaviour
{
    private PlayerControls1 playerControls;
    private Rigidbody rb;

    [SerializeField] public float moveSpeed;
    [SerializeField] public float rotationSpeed;

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

    private void OnShipMovement(InputValue inputValue){
        rb.linearVelocity = inputValue.Get<Vector3>() * moveSpeed;
        rb.MoveRotation = inputValue.Get<Vector2>() * rotationSpeed;
    }

And this gives me an error on line 22 (last line) "Cannot assign to 'MoveRotation' because it is a 'method group'".

wintry quarry
#

on a basic level you can just set the angular velocity based on the current input

#

or use AddRelativeTorque

#

And this gives me an error on line 22 (last line) "Cannot assign to 'MoveRotation' because it is a 'method group'".
Yeah this code makes no sense

#

you can't assign a value to MoveRotation

#

MoveRotation is a method that you would call

#

what would work there is:

rb.angularVelocity = inputValue.Get<Vector2>() * rotationSpeed;```
#

it might not be exactly what you want though because angularVelocity is based in world space, and when yawing a spacecraft you most likely want to do so based on its current rotaiton - sort of a local space rotation

#

But it might be a good starting point

shell knot
#

that is, thank you. I will play around with actually "generating" the vector2 value

eager spindle
woeful scaffold
#

I just finished setting up my movement, camera settings, and gravity

#

pretty basic stuff but its nice

#

Now that this is out of the way (for now), time to try and make an interact system

#

@eager spindle my idea is:
have an "Interact Text" in my UI, make sure it's turned off and whenever a ray that is cast in update() hits it within a range I set, it triggers it to be active + it shows a custom text

#

is that a correct way of doing it? or is there a better way?

eager spindle
woeful scaffold
#

ooo okay

#

i just am overthinking the idea of the update()

#

I wonder how i'll get it to be able to do custom functions upon interacting

#

I assume the ray hits, and inherits the function from the interactive object itself?

#

I guess I'll need 2 seperate scripts

#

1 for interactables and 1 for interaction

eager spindle
#

Yep, you should store the object last hit by the ray.
When you interact with the object, call the function on the object last hit by the ray

woeful scaffold
#

storing the last hit within update right?

#

so it doesnt save it for longer than it needs to i assume

#

ooooof this sounds basic but im sure im gonna get stuck

eager spindle
#

Took me a while to make the first time I tried it too

woeful scaffold
#

have u ever seen a more cutie patootie player

eager spindle
#

the bean

woeful scaffold
#

LOl is that what u call them here

eager spindle
#

idk

#

everyone calls it capsules but i call it the bean

woeful scaffold
#

gotta make that nickname so big they replace capsule with bean asset

#

uldynia show me something u made

eager spindle
woeful scaffold
#

Should the Interact script be linked to the player or the camera itself?

#

I assume to the player as it moves with the camera?

#

caffeine junkie..

eager spindle
eager spindle
woeful scaffold
#

which is your fav

eager spindle
#

mango

woeful scaffold
#

the blue one?

eager spindle
#

yep

#

has sugar but i dont mind

woeful scaffold
#

tastes nice

#

i like the pink one

#

punch something?

#

this one is bussinnnnn

eternal needle
#

There's no off-topic in the server

woeful scaffold
#

oh my bad

#

I am making the PlayerInteract script right now, i was thinking of maybe adding a bool for canInteract maybe for the future?

eager spindle
woeful scaffold
#

I am doing that exactly, but I wonder if i'll need that bool of "being able to interact" or not

#

oh wait maybe i should make it so the Interactable itself has a bool not the player

#

so i can lock chests for example or stuff like that

#

specific ones*

#

im struggling with the ray honestly

#

So i need to give it origin, direction, maxdistance

raven yew
#

Hi!
in my start method, i make my cursor invisible and confined, my cursor then disappears and i can look around, but when i bring up my ui, i make visible and make the lockstate .none but the cursor doesn't come back. is this because my game is not built or is it something else. i cant seem to find the issue.

wintry quarry
#

Also make sure the code is running with debug.log

raven yew
#

!code

eternal falconBOT
raven yew
#

the cursor never reappears unless i press escape to leave the window

wintry quarry
raven yew
#

enter

wintry quarry
raven yew
#

is that really necessary if the ui pops up?

wintry quarry
#

Check console for errors

raven yew
#

there are none

wintry quarry
#

Search your code for anything else that is touching Cursor

raven yew
#

can anything indirectly affect my cursor?

woven solstice
# raven yew the cursor never reappears unless i press escape to leave the window
private void DisplayPause()
{
    if (m_pauseActionPlayer.WasPressedThisFrame())
    {
        CinemachineFreeLookCamera.SetActive(false);
        pauseDisplay.SetActive(true);

        InputActions.FindActionMap("Player").Disable();
        InputActions.FindActionMap("UI").Enable();

        // Delay cursor activation slightly to fix Unity input frame bug
        StartCoroutine(EnableCursorNextFrame());
    }
    else if (m_pauseActionUI.WasPressedThisFrame())
    {
        pauseDisplay.SetActive(false);
        CinemachineFreeLookCamera.SetActive(true);

        InputActions.FindActionMap("UI").Disable();
        InputActions.FindActionMap("Player").Enable();

        Cursor.lockState = CursorLockMode.Confined;
        Cursor.visible = false;
    }
} 

wintry quarry
#

Ooh yeah good point - if the two actions are bound to the same button they will both get triggered. Debug.Log would have helped figure that out though @raven yew

#

Although... It is an else if so that probably shouldn't happen?

woven solstice
#

Unity sometimes ignores "Cursor.lockState = None" @raven yew

raven yew
#

ok thank you for the suggestions, ill check them out ❤️

eternal needle
#

i have a sneaking suspicion AI was used for that help

sour fulcrum
#

respectfully dont know what was going on but 99% sure it was probably a code issue

eternal needle
#

unity doesnt just ignore code randomly, thats not how it works. dont use AI to help others please

sour fulcrum
#

thats not unity sometimes ignoring it

woven solstice
#

when i say unity is ignoring code it means there is a problem with the code itself

sour fulcrum
#

thats not what those words mean

woeful scaffold
#

i did ittttt

#

i have an interaction system now, with object types like door, weapon

woven solstice
#

cool how long did it take you to do it

woeful scaffold
#

i think like 1.5-2hrs

#

but hey now i can easily add types

#

Idk what to try and add now lmao i was so invested

eternal needle
rich ice
#

i dont think this is a beginner question, you should try making a dedicated post in #1390346827005431951

lime sigil
#

oh wasn't sure in which of the two to put it
will move it there then

next fable
#

hey guys, trying to figure out what's wrong with my raycasts, etc.

#

I'm trying to raycast straight down from really high up in the scene for collision checking

#

my debug output is like this: check hit at (11317.30, -16.58, -5911.03) unit position is (11317.30, 20000.00, -5911.03) local position is (-376.16, -20013.05, -0.48)

#

the code to output it is

 print("firing check from " + checkPosition + " unit position is " + unit.transform.position + " local position is " + transform.localPosition);
 Ray groundCheck = new(checkPosition, Vector3.down);
 Physics.Raycast(groundCheck, out RaycastHit hitCheck, 100000f, terrainLayer);
 hitDistance = hitCheck.distance;
     print("check hit at " + hitCheck.point + " unit position is  " + unit.transform.position + " local position is " + unit.transform.InverseTransformPoint(hitCheck.point));```
#

oh yeah, for debugging purposes right now the unit.transform.position and the transform.position are in the same area

#

if I fired a ray using Vector3.down and check hit and unit position have the same x and z values, why is the local position different?

next fable
#

it

#

is rotated around the y axis?

#

as in, it spins around the vertical axis (like a 2d top down unit) - it shouldn't affect Vector3.down right?

silk night
#

InverseTransformPoint takes scale and rotation into account, if you just want the offset use hitCheck.point - unit.transform.position

next fable
#

InverseTransformPoint is just for debugging purposes, it matches up with the actual issue in my game which is a child of the unit at (0,0,0) is suddently returning (-376.16, -20013.05, -0.48) when I run this raycasting function

#

I would expect it to return (0,-20013.05,0)

silk night
#

for what is it returning it?

next fable
#

uhh don't quite get you

earnest moss
#

Im new to unity
out of nowhere i legit changed nothing but i got this error

next fable
silk night
#

child of the unit at (0,0,0) is suddently returning (-376.16, -20013.05, -0.48)
what function is returning that position? is it teleporting to that position?

next fable
#

ah

#

yes, let me post the full function

earnest moss
next fable
#
{
    if (transform.position - previousPostion != Vector3.zero)
    {
        transform.rotation = Quaternion.LookRotation(moveDisplacement, Vector3.up);
    }
    if (!ignoreGroundCollision) //if the unit ignores ground collision, do nothing, otherwise snap to terrain
    {
        Vector3 checkPosition = new(transform.position.x, 20000f, transform.position.z);
        print("firing check from " + checkPosition + " unit position is " + unit.transform.position + " local position is " + transform.localPosition);
        Ray groundCheck = new(checkPosition, Vector3.down);
        Physics.Raycast(groundCheck, out RaycastHit hitCheck, 100000f, terrainLayer);
        hitDistance = hitCheck.distance;
            print("check hit at " + hitCheck.point + " unit position is  " + unit.transform.position + " local position is " + unit.transform.InverseTransformPoint(hitCheck.point));
            Debug.DrawRay(groundCheck.origin, groundCheck.direction * 100000f);
            if (debugObject != null)
            {
                debugObject.position = hitCheck.point;
            }
            transform.position = hitCheck.point + new Vector3(0f, colliderDepth, 0f); //this is not producing results as expected when offset
            print("after collision check, local position is " + transform.localPosition + ", world position is " + transform.position);
        }
        transform.rotation = Quaternion.FromToRotation(transform.up, hitCheck.normal) * transform.rotation;
    }
}```
#

@silk night each 'unit' contains a number of child objects

#

the unit moves around and the children snap to terrain, which is where I use this function

#

I raycast from high in the scene and find the point where the ray hits the ground, then I teleport the unit to that location

silk night
#

cant you just let them snap to hitCheck.position?

next fable
#

transform.position = hitCheck.point + new Vector3(0f, colliderDepth, 0f); //this is not producing results as expected when offset

#

that's this line of the function

#

but hitCheck.point is not returning the correct location

silk night
#

but your hitcheck is outputting values as expected

#

(11317.30, -16.58, -5911.03)
which is directly underneath your unit

next fable
#

well, yes that part is

#

but the local position is not correct

#

if hitcheck is (11317.30, -16.58, -5911.03) unit position is (11317.30, 20000.00, -5911.03) local position should be (0, -20013.05, 0) right?

#

the x and z is not right

silk night
#

localposition - yes
inversetransformpoint - maybe (only at 1,1,1 scale and 0 rotation)

next fable
#

inversetransformpoint I don't actually use in the function - it's just to output the log

silk night
#

print("after collision check, local position is " + transform.localPosition + ", world position is " + transform.position);
so what does this print?

next fable
#

after collision check, local position is (-376.13, -20011.56, -0.48), world position is (11317.30, -15.10, -5911.10)

#

I'll post a screenshot with all of the relevant debug logs

silk night
#

oh wait, local position is again relative to rotation

#

so if your parent element is rotated the results will be off

next fable
#

ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

#

maybe that's why??

silk night
#

most likely

#

if you rotate an element by 180° and you put a localposition directly below it, it will instead be above 😄

#

as it takes the parent elements rotation as base

next fable
#

hold on

#

but only in a certain axis, right?

silk night
#

different axis will return different results ofcourse, but it will respect all of them

next fable
#

here the bottom sphere is child of the top sphere, local position -10

#

if I rotate top sphere on the y axis only, local position is the same right?

north kiln
#

Why are you not using the return value of Physics.Raycast? It returns false if it didn't hit anything, which is important to know

next fable
#

oh, this is a simplified function

#

if it doesn't hit anything I raycast up because the unit might be underground

silk night
next fable
#

I got rid of those parts cause not relevant to the problem lol

silk night
#

so if the parent is rotated and you place the object directly underneath you have to counteract the rotation in the localposition

#

which gives you the weird local position 😄

next fable
#

I think I get where you're coming from

#

let me see if I can fix it

silk night
#

i mean in the world space it IS directly underneath

#

i dont think its a bug

#

if you want the offset value just subtract both world positions from each other

next fable
#

i got it

#

the unit transform was not (0,blah,0) 🫠

#

it was like -0.02,blah,0.02

#

almost perfectly horizontal, but when you combine it with raycast distance of 20k, suddenly small error in the rotation becomes 300 units difference in the local position

next fable
#

but because it was very slightly off, the local position changes

#

thanks!!! we got there in the end

olive oriole
#

I always get super confused what type of initialization in my scripts I should put in Awake vs. Start. And honestly, it's quite inadequate to have just those two, so I extended Unity's control flow.

eternal falconBOT
naive pawn
#

oh wait thta's not asking for help

rich scroll
#

I dont have code atm, but my character cant jump with the new input system. I have the default setup that comes with unity 6.1 and no matter if I use SendMessages or UnityEvents the public void OnJump(InputValue value) function doesnt trigger the jump. When I use the same jumping functionality with the old system it works just fine

#

Every other function (OnMove, OnLook, etc.) works just fine

rich scroll
#

This heat is killing me

olive oriole
#

But nonetheless, pastebin or similar would be useful yeah

#

Next time I'll do that!

naive pawn
#

not saying it's against the rules, just that it's not really gonna stick around

slender nymph
naive pawn
#

oh yeah that channel's a thing

olive oriole
brazen compass
#

Damn man I've forgotten how to code

#

Sorry folks, I'm supposed to be alright at this but I have a question

naive pawn
#

just ask your question lol, we don't judge*

-# *results may vary

brazen compass
#

The following is part of a function. thisBlock is a code that denotes a tag for finding a part of a string to split at.

 string pattern = thisBlock + ":";
        print("The pattern is: " + pattern);

        string test = "this is a string that contains t1: and then another t1: and another t1: but also it has a c1: followed by another t1: with some stuff after";
        string[] result = Regex.Split(test, pattern);

        print("RESULT:\n");
        foreach (var line in result)
        {
            print(line);

        }

        string[] result2 = Regex.Split(test, "t1:");

        print("RESULT:\n");
        foreach (var line in result2)
        {
            print(line);

        }

Somehow, despite the identical nature of pattern and "t1:", they are producing different results

#

How is this possible?

#

I need the regex pattern to be variable based on thisBlock which is passed into the function. So I can't hard code it obviously. result2 is what I'm looking for, but I can't get it with a variable

#

I just don't have much experience with regex

naive pawn
#

perhaps try logging pattern.Length to make sure there's no weird invisible chars

brazen compass
#

Oh

#

It's returning 4...

#

That's,,, huh. How is that happening

naive pawn
#

cool, that's a very solid hint

#

try logging each char code out

#

uhhh not sure how to do that in c#, one sec..

wooden hill
#

atwhatcost null terminated string

naive pawn
#

perhaps something like this

for (int i = 0; i < pattern.Length; i++) print($"index {i} -> {(int)pattern[i]}");
naive pawn
brazen compass
naive pawn
#

ah that 13 shouldn't be there

#

that's way too low

brazen compass
#

I see

naive pawn
#

13 is a carriage return, aka \r

brazen compass
#

Waow

#

What a cool edge case

#

How do I kill it with fire

naive pawn
#

it may be from a line break from windows that you haven't split/cleaned up properly

brazen compass
naive pawn
#

where are you getting thisBlock?

brazen compass
wooden hill
#

it's weird because normally /r is followed by /n

#

oh

naive pawn
#

yep there it is

brazen compass
#

Would it be that \n?

#

Yeahh. Damn

naive pawn
#

well no

#

it's more something missing

#

to split lines properly regardless of format, you need the regex \r?\n

wooden hill
#

your file has crlf line endings

brazen compass
#

Crap this is why you study up on regex before making a text parser

naive pawn
#

eh well it's not really a regex thing

#

it's a file format thing

wooden hill
#

works on my (linux) machine™️

naive pawn
#

there's 2 flavors of line endings - CRLF/\r\n/Carriage Return+Line Feed, and LF/\n/Line Feed
the former is primarily used on windows, the latter on *nix (mac/linux/etc)

#

(that's why %n exists in some formatting contexts - \r\n on windows, \n on *nix)

brazen compass
#

So would the best solution here be to pop the carriage return out of pattern or to change my file's line endings

naive pawn
#

either split by \r?\n or change the file's line endings

#

you can also set your ide to use lf/crlf by default, same for git if you're using that

wooden hill
#

I'd rather split for both cases than have another issue because of this

brazen compass
#

Like this?

eternal needle
#

Do you really need to use \r?\n. It should be fine just using \r\n since you know which OS this is being written on

naive pawn
#

(also yes what bawsi said - if all your files are crlf then this isn't a concern)

brazen compass
#

Oh oops idk how the space got there

wooden hill
naive pawn
#

but also this is a regex, string.Split is split by string iirc

wooden hill
#

oh right lol

naive pawn
brazen compass
#

Oh I gotta change that to regex split too don't I

naive pawn
#

it's a much more complex thing, it comes with more flexibility at the cost of being more expensive

wooden hill
eternal needle
#

Its not a performance issue thing either. Its just not a risk

naive pawn
#

it might make a difference if you have a massive text file

eternal needle
#

They arent gonna go to their 2nd pc on Linux and start editing this file

naive pawn
#

they might have a colleague using *nix (now or in the future) that ends up sending them a file with LF line endings 🤷

wooden hill
#

well while at it make a pre build script that ensures all file endings to be crlf

brazen compass
#

Yippie

naive pawn
wooden hill
#

nano

brazen compass
#

I really appreciate that. I was worried it was something exceptionally simple, but nah I actually just didn't know about the carriage return being included in the string. I appreciate it

naive pawn
eternal needle
# brazen compass Like this?

Another thing to consider here could just be splitting this text asset up into multiple text assets so you arent manually processing this > character to split data. You could have a list of text assets that you drag in

brazen compass
#

I want to avoid this due to the fact I'll be doing a lot of writing

#

It's a dialogue system

#

But one with mechanical elements

naive pawn
#

also SOs are a thing if you don't want the layer of parsing (or less of it)

eternal needle
brazen compass
#

No yeah that's what I mean

#

i'm typing it in .txt files

#

This is an example. Essentially I'm trying to make it so I can write in choices and dice rolls into my txt

#

And then the parser will just go "ah it's a c block. That means I should run the choice protocal"

#

Etc etc

#

Should really be using inkle

eternal needle
#

Yea thats gonna get messy fast

brazen compass
#

Maybe lol :P

#

I'm trying to roll my own for a little bit, and if I get overwhelmed I'll pack it in.

#

I like to give myself space to do things the wrong way and learn a thing or two before doing it the right way.

drowsy flare
#

Picking up Unity again for a new project, after being away for half a year.
Should I start using 6.x or continue 2022.3.x that I know from before?

naive pawn
#

they aren't that different

#

if you're used to 2022/have it installed, you could just go with that

eternal needle
naive pawn
drowsy flare
brazen compass
grand snow
brazen compass
#

Idk I like making games it's fun

grand snow
#

Ha well not just me

#

regular expressions can become nasty quickly, see how it goes first i guess

brazen compass
#

I have made really cool things the wrong way before and gotten #goodGrades and now I'm in industry (not a programmer thank god) so I'm enjoying my little freak processes

grand snow
#

enjoy some nice regular expressions i once wrote to extract some data:

        private const string LineValueRegex = @"(?<=\= ?""?)-?[0-9]{1,}.?[0-9]*(?=""?)";
        private const string LineValueComplexRegex = @"(?<=\= ?""?)-?[0-9E+.]+(?=""?)";
        private const string LineArrayValueRegex = @"(?<=\[) ?(\d+), ?(\d+), ?(\d+) ?(?=\])";
naive pawn
brazen compass
#

Beautiful

eternal needle
short hazel
#

My addition to this: there's a parser generator called ANTLR in which you define the grammar and syntax of your "language", and then it can generate a parser for you in quite a bit of different languages. It's Java-based and can generate a C# parser just fine

eternal needle
#

Also a hill ill gladly die on is regex is easy. Mostly people forcefully use it in scenarios they shouldn't and make it harder upon themselves

naive pawn
#

-# i am that person

#

hell, i made a date parser that checks for valid days according to the month and leap years lmao

brazen compass
#

Please don't worry. I know abt tech debt :P I'm just a silly artist type but I still know how to get for real if I wanted. I'm playing with code. But to put your mind at ease, I graduated in the top 8 students out of 100 students for my game design degree at a prestigious uni.

I'm not a programmer, I'm a designer, so I still am not good at coding. But in terms of development pipelines and tech debt and project management, I know my stuff, I'm choosing not to do it because I have a job and this is play, not work.

eternal needle
brazen compass
#

It's not insistance on one way or another

#

It is play

#

It's a lovely way to make games

#

And hey I'm alright at coding. Sure I didn't know about carriage returns but like. Idk I've made cool stuff.

#

Idk I'm saying dw about it man

grand snow
#

I remember once needing to write something to get rid of these weird alternate new line characters from a document this writer did for us so this stuff happens

naive pawn
grand snow
#

its more to idenfity if there is anything non visible in some text from somewhere

naive pawn
#

ah you mean like with the debugger?

hardy galleon
#

hello guys i cant load scene for client with NetworkSceneManager i read the document but i didn't understand at all because of my language barrier. I just know i have to load scene with host or server and Network doing rest of sync for clients.

If somebody wanna help me i can share my code ^^ thx

hardy galleon
#

oh there is a channel for it thank youuu

kindred iron
#

Guys how can i make a healthUI script with using observer pattern also event system?
I tried to make the code but i cant because i have to get max health and calculate healt / maxhealt. I guess i cant use observerpattern here its not good. What do u think?

rich adder
#

not sure what you mean here

tried to make the code but i cant because i have to get max health and calculate healt / maxhealt.

kindred iron
#

i need to update the ui so i have to get maxHealth of the player

grand snow
#

the player has an event for when its health changes, the UI subscribes to this to know when to refresh itself

rich adder
#

like OnHealthUpdated?.Invoke(currentHealth)

kindred iron
kindred iron
grand snow
#

or give both as event args: public event Action<float, float> OnHealthChanged;

rich adder
#

if you want you can also make it a struct or tuple to pass multiple values at once
there is also delegate type you can use so you can give the floats labels and be more explicit etc

kindred iron
#

hm ok ima try this way ty guys

ashen hound
#

helu, im trying to implement audio into my physics based game but sofar it turned out either delayed or glitchy
because when changing or playing based on linear velocity its rather meh because the velocity is changing a lot because the thing iwant to add sound to is bumping a lot in tight space

#

im trying to add friction sound

rich adder
#

do you have an example or something ?

topaz hatch
#

Morning everyone, I'm trying to disable the Image component of objects in a specific list through code. For whatever reason the Component.enable call does not work. Here is what I have:

` if (imgBulletIndex < imgBulletClips.Count -1)
{
Image imgDisplay = imgBulletClips[imgBulletIndex].GetComponent<Image>();
imgDisplay.enabled = false;
imgBulletIndex += 1;

}`

ashen hound
#

how do i snip code?

rich adder
topaz hatch
rich adder
rich adder
eternal falconBOT
empty cairn
#

I am very very new to unity coding and want to make a simple 2D movement system, what would the best way to code that be?

topaz hatch
rich adder
slow idol
#

is there a way to modify Unity’s built-in scripts? for example, add a pitch variation to all audio sources by default, without extra code upon instantiating one

topaz hatch
rich adder
wooden hill
#

you can also look at the top of your file to see which it is "using"

rich adder
#

but probably configure your IDE if it isnt;

past halo
#

Lets gooo i managed to kitbash two different tutorials together to get the movement, physics and input systems i wanted raah

topaz hatch
#

It seems to be using the 'Image' from the Visual Editor.

rich adder
slow idol
#

damn :(

wooden hill
rich adder
#

I belive VS puts whatever namespace is first if you dont explicitly select it

topaz hatch
#

Okay I'm adding in that library

wooden hill
#

just click on 2nd and it should do that

#

wondering if we can set priority to unity first UnityChanThink

topaz hatch
#

UnityUI is not even showing up in the drop-down. Trying to fix up my library calls now

wooden hill
#

oh then probably not set up right

topaz hatch
#

Microsoft Visual Studios

wooden hill
#

Visual studio Code ?

#

there is a difference in like vs2022 or vsc (vscode)

topaz hatch
#

I feel like this is a recent issue for me. I fixed up the libraries at the top so lets see if this code works now.

rich adder
#

if you did all the steps n still not working, check the troubleshooting section

topaz hatch
#

There we go. It works.

#

Hmmm, I really don't remember having to care about knowing this in the past. Like Unity 2018 and such.

#

BUT, it's good to know now so in the future I can let others know

kindred iron
# rich adder which editor are you using

there is a new problem. I made the script separately so that i can put the health script to anything. But if i invoke a event this happens on every gameobjects where i put the healthscript and even tho the health is not players my ui updates (5min afk)

topaz hatch
#

Now I know why the older tutorials always did the using Unity.UI thing at the top.

rich adder
grand snow
#

if the events not static its for that instance only, you are confused 😆

grand snow
#

no its UnityEngine.UI

topaz hatch
#

Yeah. My bad

grand snow
#

System.Collections.Generic ❤️

topaz hatch
wooden hill
#

I think that was just an example. the main thing being that you have to put the using statement yourself

#

huh im pretty sure even in unity 5 i didnt do that

#

what ide were/are you using?

rich adder
topaz hatch
#

I didn't know there were other code uses for the Image call. But for context on myself I am someone who only knows C# through Unity. So I am not familiar with the hard C# programming stuff

rich adder
#

I guess it makes sense now that 3.0 is Unity.Cinemachine instead of redone as UnityEngine ig since it was an asset acquired

grand snow
#

guess for new stuff they decided to do this

rich adder
topaz hatch
#

oooh okay

rich adder
#

namespaces help encapsulate these within their own "group"

topaz hatch
#

So Image is a general C# class and Unity has it's own UI version called Class?

rich adder
#

na Image is just a common class for multiple different namespaces

#

the only ones that are built in are ones usually found in the System namespace

wooden hill
rich adder
#

System.Drawing has one but don't think it woks in unity

#

gool ol windows forms (i think?)

kindred iron
# rich adder that doesnt sound right, show the code maybe ?

the code is:

using System;
using UnityEngine;

public class Health : MonoBehaviour
{
    [Header("Health")]
    public float health;
    public float maxHealth;
    public float defense;
    public float defenseMultiplayer;

    void Awake()
    {
        health = maxHealth;
        defense = 0;
        defenseMultiplayer = 1;
    }

    private void OnEnable() => EventManager.OnDamageTaken += Character_OnDamageTaken;
    private void OnDisable() => EventManager.OnDamageTaken -= Character_OnDamageTaken;

    private void Character_OnDamageTaken(DamageEvent damageEvent)
    {
        if (damageEvent.DamagedObject == null)
            return;

        if (damageEvent.DamagedObject != damageEvent.owner && damageEvent.DamagedObject == gameObject)
        {
            TakeDamage(damageEvent.damageAmount);
        }
    }

    public void TakeDamage(float amount)
    {
        //EventManager.SendHealthChange(health, healthChangeAmount, maxHealth);
        health -= (amount - defense) * defenseMultiplayer;

        if (health <= 0.1)
        {
            Die();
        }
    }

    public void Die()
    {
        Destroy(gameObject);
    }
}
rich adder
#

yup EventManager.OnDamageTaken seems to be a static event so everyone(Health) subscribed to player taking damage will call that methodCharacter_OnDamageTaken

kindred iron
#

even the enemy will invoke the event

wooden hill
#

Just like you checked the owner there you would need to check on your ui if its the player

rich adder
#

why should ALL health listen for it

kindred iron
#

the same health scripts has everybody

#

it changes nothing

polar acorn
wooden hill
rich adder
#

rather than listenening for a specific instance invoking it

#

every health component should subscribe to their own instance object they are on

visual linden
#

I generally don't mind static events, but it's true that there seems to be some spaghetti happening in this specific case.

polar acorn
#

To be honest, why is the health script the one subscribing to an event? It seems like it should be the source of the events

#

The script named Health should probably be the canonical source of data

grand snow
#

that would make too much sense

rich adder
#

Yeah I guess they wanted to make it more modular but you should just call a TakeDamage method from whatever is taking damage from

kindred iron
# polar acorn To be honest, why is the _health_ script the one _subscribing_ to an event? It s...

there is one already:

public class EventManager : MonoBehaviour
{
    public event Action<DamageEvent> OnDamageTaken;
    public static event Action<float, float, float> OnHealthChanged;

    public static void SendDamage(DamageEvent damageEvent)
    {
        OnDamageTaken?.Invoke(damageEvent);
    }

    public static void SendHealthChange(float currentHealth, float healthChangeAmount, float maxHealth)
    {
        OnHealthChanged?.Invoke(currentHealth, healthChangeAmount, maxHealth);
    }
}
rich adder
#

health component can have events for UI and sound effects or whatever else as Invoker instead of listener

naive pawn
#

yeah, we're saying to change the source of the events

polar acorn
kindred iron
kindred iron
#

like the name says event manager

rich adder
# kindred iron can u give me an example for ui pls

Player/Enemy takes damage call TakeDamage on health component
on Health component INVOKE an event OnHealthUpdate?Invoke or whatever (Other scripts subbed to it react, like UI for player specific etc.)
this way other objects can have it(Health) as long as they call Take Damage on Health component

polar acorn
# kindred iron for events yeah

So then what's the problem? If this is the one source of information about the concept of "Health" it seems to be behaving as expected. This one thing changes, everything that listens to it updates.

kindred iron
grand snow
#

isnt that the point

#

player damaged -> notify stuff -> update ui?

kindred iron
#

no this ui just for the player

grand snow
#

then make it do just that???

rich adder
#

so then only UI listenes for event on Health for player

kindred iron
#

enemy damaged -> notify stuff -> update ui

grand snow
#

have some amazing art

rich adder
#

You can have the same event in Health, that doesnt mean other scrips have to listen to that event and react the same way

kindred iron
rich adder
kindred iron
#

its hard to understand for me 😭

rich adder
#

put OnHealthChanged event in Health
then in player you += to it and react whatever you want from it, UI , Sound etc.

kindred iron
wooden hill
#

If you know how to make events then that means you're almost there

rich adder
#

all HEALTH have that event, but only in the Player one do you want to += for the UI or anything player specific reaction

#

for Health on enemy maybe you'd only subscribe to it for a sound to play or whatever else

kindred iron
grand snow
#
public class PlayerUI : MonoBehaviour
{
    [SerializeField]
    Slider healthSlider;

    public void Init(Player player)
    {
        player.OnHealthChanged += (float newHealth) => {
            healthSlider.value = newHealth;
        };
    }
}
#

UI subscribes to event on player and updates itself

polar acorn
# kindred iron if i change something on health script it changes for enemy too

You have one script that handles all health events. That script is the canonical source of all information about "health". If you want multiple different "health"s, you cannot have a single script with a static event handle it all. You would need to include information about which "health" you are sending a message about.

rich adder
kindred iron
grand snow
#

plz ditch this dumb design

polar acorn
visual linden
#

(Also just a heads up, I think posting gifs is against the rules)

kindred iron
#

at this point

polar acorn
#

Reaction images in general, not "gifs" as a format

rich adder
#

no reaction gifs this obnoxious

grand snow
#

[man talking to brick wall meme]

visual linden
#

Yes, sorry, reaction images specifically 😮‍💨

naive pawn
#

[man tapping forehead gif]

kindred iron
#

so i shouldnt send this gif?

naive pawn
#

yes

kindred iron
#

oh

naive pawn
#

if you want to react, you can use reactions
reacting in general isn't against the rules, but using images/gifs is kinda obtrusive - that's why that specifically is against the rules

visual linden
#

Going back to the problem though, I really think Rob's code snippet above illustrates a much better approach. You could give that a go

kindred iron
rich adder
kindred iron
visual linden
#

Well, you need a reference to the instance, which is probably what they mean

rich adder
#

being static just means only 1 of that event exists, and everyone subscribes to it
(which in this case is not what you want)

kindred iron
#

but there is no event in playercontroller

rich adder
polar acorn
#

This is what is known as an "example"

kindred iron
rich adder
#

forget that crap right now

polar acorn
kindred iron
polar acorn
kindred iron
polar acorn
#

Object

#

Instance

ember tangle
#

It should be a health manager or a unit manager, not an event manager

polar acorn
# kindred iron oh yes

So, if there are multiple things that have a "Health" value

You can not have one static event handle all of it.

#

Static is shared between everything

grand snow
#

my example is meant to be that you initialize the UI with the specific Player/Health INSTANCE that matters.

ember tangle
#

and if you need static access use a static instance of the class, not static events

kindred iron
wooden hill
#

There are many solutions to this.
If you really want to use an "EventBus" then you would have call the ui only from the player's health reduction and not literally every entity that has the health script

kindred iron
kindred iron
polar acorn
# kindred iron why cant i and what happens if it has

You literally cannot. It's very simple. One thing is not two things.

Think of it this way, you have two cats. Those cats have two food dishes in different rooms (because cats fight over food). You ask someone to let you know when a cat's food bowl is empty. You're in your room, someone walks up to you and says "A Cat's bowl is empty".

Which cat do you go feed

kindred iron
#

guys i gotta go rn i will come back in 30 mins ty for ur helps 🙏

wooden hill
stuck field
polar acorn
ember saffron
#

i don t understand the issue?

stuck field
#

Think about what could be missing 🤔

slender nymph
ember saffron
#

im just beginning to start learning scripting so i dont know

sharp jay
#

Comma innit

naive pawn
#

wouldn't the error message tell you

ember saffron
naive pawn
#

"expected a ) or a ,"

polar acorn
naive pawn
#

yeah exactly

grand snow
#

yea what does "expected comma" even mean smh /s

polar acorn
ember saffron
#

do i remove the ,? or

polar acorn
#

It tells you what it expects to be there

sharp jay
#

We need british translation for the console

polar acorn
#

and you can see that it is not

naive pawn
#

you didn't give it one

sharp jay
#

"oi fam. missin a comma innit"

polar acorn
ember saffron
#

but then i have two commas

#

do i delete the one after the )

polar acorn
sharp jay
#

Oh. we're doing this are we

naive pawn
#

oh god

polar acorn
#

Do you know what a comma does

sharp jay
#

I see not much has changed in 3 years 😎

naive pawn
#

it's saying the 0 is unexpected, because it expected a , first

slender nymph
ember saffron
#

i don't know why people are getting pissed off?? from what i remember this is code-beginner 😭 im literally just starting out so, no!! i dont know anything abt coding atm

sharp jay
#

PERFECT

#

do that

polar acorn
polar acorn
slender nymph
frail hawk
#

new Vector3(x,y,z)

grand snow
stuck field
#

new Vector3(0, 0 0,) ❌ too

#

(What you did)

ember saffron
#

ohhhh i think i fixed it? 😭

frail hawk
#

yeah!

rocky canyon
#

ez sauce

sharp jay
#

have you written 0 as an O for offset

#

What

ember saffron
# ember saffron it's like

from what i remember (i can be wrong cause i wrote this last night and im following like a learning the basics tutorial) i think its the like y and x rotation?

rocky canyon
#

h31gh70ff537

sharp jay
#

Oh, hi spawn

rocky canyon
#

👋 hi bud

ember saffron
rocky canyon
#

fancy seeing u around here

sharp jay
ember saffron
rocky canyon
#

well don't do that

#

use letters for words

frail hawk
#

dion if your rotation is weird after instantiating, you might want to use Quaterion.identity instead transform.rotation, just saying now

sharp jay
#

who are these bogans doing youtube tutorials

#

jesus

ember saffron
#

👍

ember saffron
#

im tweaking

#

he's going so fast

rocky canyon
#

you have to build up exposure..

ember saffron
#

im just basically copying off code

#

and playtesting it

#

😭

rocky canyon
sharp jay
#

watch @rocky canyon tutorials instead

short hazel
#

Look at the difference between the "O" in Offset and the zero of the line 40 indicator

rocky canyon
#

took me hours to do my first 15 minute tutorial

#

nothing stopping u from pausing as u go..

#

dont try to do it all in one go

kindred iron
ember tangle
#

Make slight changes to the code of the tutorial so you can better understand what is going on and get more comfortable messing around.

slender nymph
ember tangle
#

Dont just copy

kindred iron
polar acorn
#

That is why you cannot have a single static event handle multiple things having health

ember saffron
kindred iron
slender nymph
# ember saffron oops

also next time it would help make it more obvious if you didn't intentionally crop the top part of the video out because line 28 has a 0 on it and the difference between that 0 and the O is fairly obvious

polar acorn
# kindred iron and now how should i do?

As we said, the thing that actually controls the health should be the thing that has the event (Not a static event), and things that need to listen for changes in a specific object's health would subscribe to that object's event

#

Furthering the analogy from before, imagine if instead of having one guy tell you when any cat's bowl is empty, imagine if you had as many guys as you had cats, and each one checked one bowl. When that specific guy shows up you know which cat to feed

kindred iron
#

OH NOW I UNDERSTAND IT FINALLYY

#

but i have a question

#

at this point i have to get the health of the player

#

so i can get the event

#

dont i?

sharp jay
#

you can get anything you want

sharp solar
#

inside classes
defined variables are allocated new memory for every new instance of that class
do defined methods take up more memory for every new instance as well or does c# handle that part

wintry quarry
#

the method is part of the class, not part of an instance in memory

rocky canyon
#

Think of methods as "instructions", not data. You don’t need a copy of instructions for every object—just one shared version. But instance variables are data, and each object needs its own set.

kindred iron
rocky canyon
#

try it and see

polar acorn
rocky canyon
#

don't forget to unsubscribe ondestroy or disable.. don't want memory leaks

kindred iron
polar acorn
rocky canyon
#

the health stuff and the ui stuff..

kindred iron
#

oh ok

polar acorn
rocky canyon
#

reference one with the other 😉

sharp solar
polar acorn
#

While still being private

sharp solar
#

so it doesnt show when interacting with the class in script?

kindred iron
polar acorn
#

Or are either of them spawned in at runtime

rocky canyon
#

you can use [SerializeField] private ... in that case

sharp solar
#

ok

rocky canyon
#

no reason for it to be public just to have it exposed in the editor

sharp solar
#

is there any performance cost associated with public variables or is it just a cleanliness thing

naive pawn
#

there is, it looks nice 🙃

wintry quarry
#

yes - it gets serialized

naive pawn
sharp solar
#

but serialized private is also serialized

wintry quarry
#

that costs memory and some cpu to copy it arund

kindred iron
rocky canyon
naive pawn
polar acorn
polar acorn
#

Then on Start, subscribe to its events

polar acorn
kindred iron
#

ohh ok

rocky canyon
#

having a public variable thats never needed outside the class just is another vulnerability... accidental changes can be made..

naive pawn
# sharp solar sure

there probably would be a difference just based on how unity acquires the variable but they both would use reflection anyways so there's not gonna be a significant difference

kindred iron
# polar acorn Or serialized

but wouldnt it be like a lil messy because we still trying to get the script from our script then we dont use observerpattern at this point right?

rocky canyon
#

well for me yea..

polar acorn
rocky canyon
#

when i first started coded i made EVERYTHING public

hexed terrace
rocky canyon
#

lmao

polar acorn
#

Public vs. Private is like putting your clothes in a drawer or just piling them up on the sofa.

It's easier to access them on the sofa but a whole lot harder to find the specific thing you're looking for.