#💻┃code-beginner

1 messages · Page 80 of 1

rich adder
#

then why are you checking tag on nothing

thin sedge
rich adder
#

this method OnTriggerEnter is giving you a Collider2D of whatever was hit

polar acorn
thin sedge
polar acorn
thin sedge
polar acorn
thin sedge
polar acorn
thin sedge
#

So I need to serialize it?

polar acorn
#

You would know it's the player then

polar acorn
thin sedge
polar acorn
#

What object are you checking the tag of

thin sedge
polar acorn
thin sedge
#

I feel so stupid in this conversation right now notlikethis

cosmic quail
#

why is there a multiple page long conversation on something that can be solved by saying four words notlikethis

polar acorn
polar acorn
polar acorn
#

What is the name of the variable

thin sedge
polar acorn
#
thin sedge
polar acorn
thin sedge
#

It's either a string or a float

#

I think

rich adder
#

its a Collider2D why would be a string or float

polar acorn
#

What

thin sedge
rich adder
#

in the code you're looking at

polar acorn
#

I'm not asking for the type

thin sedge
#

I thought you meant the variable itself notlikethis

polar acorn
#

I do mean the variable itself

#

What is it called

#

The name of the variable

#

Not the type

#

Not what function it's in

#

The name

thin sedge
#

This white text?

rich adder
#

thats a variable name, but not one in the function is it

polar acorn
#

This isn't in the code you've sent

#

Where are you looking

thin sedge
#

I never gave it a name 😅

polar acorn
#

Why did you make a new variable

#

Use the one you already have

#

That comes from the function

#

The parameter to the function is the collider you have collided with

rich adder
#

@thin sedge variables in a function( ) work exactly the same naming them outside of a function

#

Type name

thin sedge
#

instead of the "other" thing?

rich adder
#

🎊

dense root
#

How do I get the reference from my Ball.cs script?

[Header("Timer UI")]
public GameObject timerText;

private float TimedText;

public void TimerText()
{
    timerText.GetComponent<TextMeshProUGUI>().text = TimedText.ToString();
}
thin sedge
#

Thank you for the help then!!UnityChanSalute

rich adder
dense root
#

Yeah

thin sedge
rich adder
#

code doesn't do things magically by itself lol

#

only when it gos awry 👿

rich adder
# dense root Yeah

same way you made the other references before [SerializeField] private Ball ball

thin sedge
#

Thread takes up less space :)

dense root
#

Okay I've serialized the field how do I call it on my TImerText()?

digital lynx
#

i do not know why my character is not jumping. No matter what i do. I already checked my input settings. It just doesn't work. Anybody got an idea?

rich adder
#

public fields are already serialized in inspector

dense root
#

Oh right

#

So how do I take that value from the inspector and dispaly it to the text field I created?

rich adder
#

you have to expose the current timer if you want to display that

#

not the TargetTime

#

since thats the starttime

rich adder
digital lynx
rich adder
#

!code

eternal falconBOT
rich adder
digital lynx
#

it didn't show anything in my end.

#

i already tried everything.

rich adder
#

screenshot the whole console window in playmode

digital lynx
rich adder
#

well then there you go

#

answer shall always be revealed to you debugging

#

look at your jump condition again

#

if (Input.GetButtonDown("Jump") && isGrounded)

#

do you see whats wrong?

digital lynx
#

alright

hollow dawn
#

should i use visual studio code for coding c# in unity? im a beginner which one is the best to use?

rich adder
#

best tool for the job is always visualstudio

#

vscode is catching up though, maybe in a few years

frosty lantern
#

i like the colored brackets in vscode tho

rich adder
#

VS has that too

#

since last year

#

or more

frosty lantern
#

how do i turn it on?

rich adder
#

It made my rainbow brackets useless

rich adder
#

VS 2022

frosty lantern
#

i don't see it

#

it highlights bot doesn

#

color on mine

digital lynx
#

i tried searching for any possible solutions.

frosty lantern
#

i see the setting i think but it's not doing it

rich adder
#

what part of it didn't you notice the bool

#

isGrounded is never tru myguy

#

you can't jump

digital lynx
#

sorry i really do not know.

rich adder
#

well try to understand what you're copying lol

rich adder
#

forgot how to enable it tbh

#

mine was just on

#

see if Viasfora still works

buoyant knot
desert elm
#

How could I write a command that would raycast between two objects and report if it intersects with any collider other than the target object?

queen adder
#

yo Im having some issues with the new input system where i will look around for a while then suddenly it feels like i miss a frame and my character is looking way further thant it should be or just straight up looking upwards for some reason```private void Update()
{
//looking (camera rotation)
float mouseX = playerInputActions.CameraLook.MouseX.ReadValue<float>() * rotateSpeed * Time.deltaTime;
float mouseY = playerInputActions.CameraLook.MouseY.ReadValue<float>() * rotateSpeed * Time.deltaTime;

    xRotation -= mouseY;
    xRotation = Mathf.Clamp(xRotation, -90f, 90f);

    cameraHolder.transform.localRotation = Quaternion.Euler(xRotation, 0, 0);
    transform.Rotate(Vector3.up * mouseX);
}```
buoyant knot
desert elm
#

oh okay thanks

wintry quarry
buoyant knot
#

there is Raycast, RaycastAll, and RaycastAllNonAlloc

#

pick the one that is best for you

#

Raycast just gives one hit, but is simple if you can filter out the two objects by layer in a contact filter.

#

RaycastAll gives you a whole array to sift through.
RaycastAllNonAlloc gives you a whole list/array, but you can keep the list/array as a variable to avoid repeatedly allocating/deallocating. If you are going to call this a lot.

buoyant knot
#

i think the math here is just not correct. He would need to figure out his units

desert elm
#

shouldnt I use a layer mask though?

buoyant knot
desert elm
#

oh okay

buoyant knot
#

if A, B and C all have the same layer, then you can’t call Raycast from A to B without hitting A and B by default.

buoyant knot
desert elm
#

can you invert layermask?

wintry quarry
buoyant knot
#

this guy needs to convert from mouse space to something normalized/dimensionless. Probably needs to divide mouse pos by screen size or something first. Just get that in a 0-1 or -1-1 range

#

then he can multiply by his rotation speed, which would have units of degrees/second, I assume

#

I’d first get mouse position into a -1 to 1 scale. Then multiply it by rotationSpeed (angular velocity in degrees per second) times deltaTime. This would output a value in degrees, which is what he wants to make a quaternion based on euler angles.

#

his main mistake here is not converting Mouse position from screen space.

frosty lantern
desert elm
#

whats the problem here now?

rich adder
rich adder
#

most likely targets is not the same type as your script

#

you probably need to add the hit.whatever instead of this

#

what is the type for targets ?

desert elm
#

I do not want to add the thing the collider hits too the list

unreal imp
#

Guys, sorry for asking for the 99th time but I want the definitive answer on how to make an object carrying system like half life 2? (They had already told me this before but I lost the message)

rich adder
unreal imp
#

this is the last time I will ask that

desert elm
desert elm
rich adder
#

from the loop

desert elm
#

a.position

eager elm
rich adder
#

you said targets is Transform

desert elm
#

oh I
somehow didn't realize that- I assume just having it be a will be okay?

desert elm
#

thanks

rich adder
#

although name it something better than a

#

lol

#

enemy would've made more sense in this context

amber spruce
#

anyone know why that happens

polar acorn
# amber spruce

Make sure that there are no compile errors and that the file name and class name match.

amber spruce
#

they all match and i dont see any compile errors

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;

public class CreateAndJoinRooms : MonoBehaviourPunCallbacks
{
    public InputField createInput;
    public InputField joinInput;

    public void CreateRoom()
    {
        PhotonNetwork.CreateRoom(createInput.text);
    }
    public void JoinRoom()
    {
        PhotonNetwork.JoinRoom(joinInput.text);
    }

    public override void OnJoinedRoom()
    {
        PhotonNetwork.LoadLevel("MultiPlayer");
    }
}

thats my code

polar acorn
#

Show your console first

amber spruce
polar acorn
#

Clear errors first, then see what's still around

amber spruce
#

when i clear them nothing new shows up do i gotta run the game first?

polar acorn
amber spruce
#

CreateAndJoinRooms

polar acorn
amber spruce
polar acorn
#

Try restarting the editor

amber spruce
#

why cant i drag my input field into the input field thing

#
public InputField createInput;
#

i have 2 of them

polar acorn
#

Is it an input field or a TMP InputField

amber spruce
#

TMP

#

i always forget that

#

thanks

dense root
#

Any idea how come my pen isn't logging to the console?

slender nymph
#

is the component attached to an active object in the scene?

dense root
#

Oh weird I thought you needed to do that but in the tutorial he doesn't do that

#

It's logging an unusual name though, this is fairly common wacom

desert elm
#

how can I have an If statement have two conditions?

lone sable
#

I got two code related questions to some UI elements.

1: I'm running into an issue where if I mouse over a button inside of a ScrollRect, then, I can no longer use the mousewheel to scroll through the scrollrect is there a code related fix for this? Or is it a Unity Bug? It seems really strange.
2: Does anyone have anything that would support controllers inside of a ScrollRect? It seems very strange of Unity to not support Controller for this...

north walrus
#

Can something like this be simplified?

short hazel
#

public CharacterController CharacterController { get; private set; }

steep crown
#

is this comment precise enough?

#

i feel like it wasnt clear what it meant

rare basin
#

yikes

rare basin
lone sable
rare basin
#

but wdym supporting controllers in scroll rects

slender nymph
lone sable
#
  • Select an object in the scroll rect.
  • Move it down
  • As you move it down it will select objects out of view of the scroll rect.
rare basin
#

about no.1 scroll rect won't be detected if you have mouse over different UI element

fierce shuttle
rare basin
lone sable
#

Yeah, both options aren't "Normal" behaviour for a Scroll Rect in the real world.

rare basin
#

seems pretty normal to me

#

all scroll rects i know behave exactly like that

fierce shuttle
edgy prism
#

Working on UI sliders that I want to stop moving when the total value is 508 or greater and Im having an absolute nightmare when I set the value to say 507 and click the far right of the slider to give it a value much higher than 508 any help is greatly appreciated

https://gdl.space/recevuhihi.cs

lone sable
rare basin
#
            if(sliderValues >= 508)
            {
                sliderValues = 508;
                return;
            }
edgy prism
rare basin
#

Mathf.Clamp the sliderValues

edgy prism
rare basin
#

if you don't want your sliderValues to be greater than 508

#

just clamp it

edgy prism
rare basin
#
    if (sliderValues >= 508)
    {
        // If total value is 508 or greater, set all sliders to their maximum allowed values
        foreach (Slider slider in evSliders)
        {
            slider.value = Mathf.Round(slider.value / 4.0f) * 4.0f;
        }
        return;
    }
#

or just add this

edgy prism
short hazel
#

So the sum of all slider values must not exceed 508 is what you're asking?

rare basin
#

so if you have 2 sliders, one is at 500 let's say

edgy prism
#

Sorry my brain is a bit fried I think what Xaxup just said might work let me test it

rare basin
#

the second one can't exceed 8?

edgy prism
blissful trail
edgy prism
rare basin
edgy prism
#

Im checking its below 508 but I think I need to track the increase im just not sure how

wet heath
#

Creating particles on a specific surface when a raycast passes through

blissful trail
fierce shuttle
polar acorn
blissful trail
#

oh so its overwriting not just the x and z velocity but y too?

short hazel
# edgy prism Im checking its below 508 but I think I need to track the increase im just not s...

As long as you both check that the sum doesn't exceed 508 and correct the slider in the same frame, you won't see the difference.
You'd need a way to know which slider was just interacted with, so you can "clamp" it. Sum all the sliders except the one you just touched. If sum + sliderYouTouched.value > 508 then set value to 508 - sum. There might need to do a - 1 or + 1 somewhere to land on the 508 after the subtraction

lone sable
fierce shuttle
blissful trail
edgy prism
short hazel
#

Yeah that would be a way to do it

lone sable
blissful trail
#

nevermind i figured it out thank you for your help digiholic!

#

❤️

fierce shuttle
lone sable
#

Yeah I'm just not sure how to fix that though...

#

I was using that to trigger mouse over/selection popups.

short hazel
fierce shuttle
# lone sable I was using that to trigger mouse over/selection popups.

Well a Button already inherits from Selectable which allows that functionality, you could either make a script that inherits from Button to access that functionality too, or maybe try using IPointerHandlers like IPointerEnterHandler, there is one for Exit, Click, Drag, etc as well

edgy prism
short hazel
#

I guess that's the easiest solution, and if it works it works

edgy prism
waxen mulch
#

await AuthenticationService.Instance.SignInWithUnityAsync();

I need help with this method. It requires a token but I do not know where to get it from and using AuthenticationService.Instance.PlayerId results in an error
Here is my code:

        AuthenticationService.Instance.SignedIn += OnSignedIn;
        await UnityServices.InitializeAsync();
        await AuthenticationService.Instance.SignInWithUnityAsync(AuthenticationService.Instance.PlayerId);
dense root
#

How do you get over the fear of breaking things in code?

polar acorn
dense root
#

lol

languid spire
eternal needle
#

using git is super easy to pickup these days now that all the good GUI's that exist, i use github desktop. Take a day to just experiment with it and how it works, and save yourself the fear of breaking things. If you arent using version control then you are always running the risk that something corrupts and you lose months of work

dense root
#

right

#

thanks

vast vessel
#

Also apparently unity has its own free version control thing now

#

You can enable it with a "link" button in the unity hub

#

On the left side of your project name

eternal needle
#

unity has had some version control things for awhile from what ive seen online, but really you're better off just using git

vast vessel
#

Yea ig so. It dosnt have alot of things that git has. For eg it dosnt have anything like gitignore. It saves every single .meta file in your project

rich adder
#

pretty sure it has some similiar thing

#

meta files are important

eternal needle
#

Git is pretty much the only tool you'll see used in every other aspect of CS

languid spire
vast vessel
#

Why?

rich adder
#

because all your scripts would be unkown or missing

languid spire
vast vessel
#

Wont unity just auto generate them if any files are imported into a project?

rich adder
#

hence why if you move files in project from outside unity without moving the meta that goes with it unity takes a shit

languid spire
#

ha, ha, you wish

vast vessel
#

I thought they were only useful when you moved a file and so they wont be importent when uploading to git

languid spire
#

don't think, know

eternal needle
#

i mean unity will autogenerate them if they arent there, but you're gonna have a bad time if u delete them all

polar acorn
polar acorn
lone spear
#

I have a player that is using the new Input System (not new now but hey) and all I want is the player to move left and right and up and down from a top/down view. Code here:

    Vector3 playerPosition = Vector3.zero;
    Vector2 _move;
    public float speed = 2;

    private void OnEnable()
    {
        controls.Enable();
    }

    private void OnDisable()
    {
        controls.Disable();
    }

    void Awake()
    {
        controls = new PlayerControls();
        controls.Player.Move.performed += ctx => _move = ctx.ReadValue<Vector2>();

    }

    void Update()
    {
        Debug.Log(_move.x + ", " + _move.y);
        transform.Translate(speed * Time.deltaTime * new Vector3(_move.y, this.transform.position.x, _move.x), Space.Self );
    }```

Produces this movement...

Which is plain wierd. Left/Right on keyboard is -1,0/1,0 in _move and Up/Down produces 0,-1/0,1 in _move...
#

Can anyone explain why it goes crazy like this?

polar acorn
lone spear
#

Turns out transform.Translate(speed * Time.deltaTime * new Vector3(_move.y, _move.x, 0.0f), Space.Self ); works nicely!

#

@polar acorn that's what I thought, and it turns out we're both right

verbal dome
#

Yeah, seems like your player's forward direction is actually its right direction

lone spear
#

@verbal dome perculiar- something from blender maybe?

verbal dome
#

You would need to fix it in blender, yes

#

The model's forward direction should be Y forward in blender

#

And you need to look up the correct settings when exporting from blender to unity, they use different coordinate systems

spiral narwhal
#

Is it possible to create presets that are saved for multiple projects? Because I almost never find myself in the need of creating animations with loop time set to true, always to false.

#

Kind of like overriding Unity settings

ripe shard
# spiral narwhal Kind of like overriding Unity settings

everything in project settings and preferences is saved to a file that you can copy to new projects but unity in general is not a tool where you have default settings for every toggle and value on each component, its more like a framework on top of which you build your own tools that would then optionally give you this kind of preset. Nevertheless in some areas, like say asset import, you get the option to save presets. but nothing like you describe there.

spiral narwhal
#

Ok

#

Thanks

warped pendant
#

does anyone know how to address the diagonal idle direction problem in top down 8 way movement?

basically, the player would have to simultaneously let go of the 2 cardinal directions making up the diagonal direction to get a diagonal idle direction, so what's the simplest logical answer to this problem?

dense root
#

what is the difference between the physics material being in the rigidbody or the box collider? it appears to have the same affect in my PONG game

slender nymph
#

not a code question, but i'm pretty sure that the difference is that on the collider it only affects that one collider but on the RB it affects all of the RB's colliders

dense root
#

Not sure what you mean by that

#

WDYM by affects all of the RB's colliders?

#

I know best practice is to put it in the Rigidbody2D since that's where physics are generally being applied but like I said in this simple case if I put it in BoxCollider2D it produces the same effect

slender nymph
#

every collider that is part of the rigidbody. in your case that is just the one on the same gameobject

#

child colliders of a rigidbody become part of the rigidbody's compound collider

dense root
#

Could you put it in simpler terms? I'm not quite comprehending

#

I guess the question is related to PONG how are they producing the same desired effect?

slender nymph
#

since you only have a single collider that is part of your rigidbody's compound collider it shouldn't make a difference which you apply it to

dense root
#

Huh? Player paddles have Box Colliders too

slender nymph
#

that's a separate collider obviously

polar acorn
dense root
#

@polar acorn wdym

polar acorn
#

Multiple colliders can be part of the same rigidbody

#

Are yours

dense root
#

Not that I'm aware of

polar acorn
#

Then there's no difference between setting the material on the collider or rigidbody

slender nymph
dense root
#

What's an instance of PONG where I would want to specifically set it to RigidBody2D and not BoxCollider2D?

#

And the other way around

slender nymph
#

why are you so hung up on pong having any relation to the question you've asked?

polar acorn
dense root
#

@slender nymph it makes it easier to understand

slender nymph
#

the physics material will apply to either the single collider it is assigned to or every collider that is part of the rigidbody if it was assigned to a rigidbody instead of a specific collider

dense root
#

@polar acorn when would you have multiple colliders on the same rigidbody?

polar acorn
slender nymph
dense root
#

Alright I think I'm getting it

#

Basically unless you have an instance where there are multiple colliders on the same rigidbody you can apply your physics material to either/or BoxCollider or RigidBody

slender nymph
#

it also helps reading the docs
https://docs.unity3d.com/ScriptReference/Rigidbody2D-sharedMaterial.html

The PhysicsMaterial2D that is applied to all Collider2D attached to this Rigidbody2D.

The PhysicsMaterial2D specified here is applied to all attached Collider2D unless the Collider2D specify their own PhysicsMaterial2D in Collider2D.sharedMaterial. If no Collider2D.sharedMaterial or Rigidbody2D.sharedMaterial is specified then the global PhysicsMaterial2D is used.

dense root
#

I'll give it a read, thank you

nimble sorrel
#

when working with coroutines can you put something after the while loop to have that thing happen when the while loop is over?

#

like so

cosmic dagger
summer stump
# nimble sorrel like so

Unless you yield break, destroy the object running the coroutine, StopAllCoroutines(), or StopCoroutine(cachedCoroutine), it will run all code just like normal

weary moss
#

FixedUpdate will run at the same speed doesn't matter if a person has 2 or 200fps right?

ivory bobcat
weary moss
#

so, framerate doesn't affect it?

ivory bobcat
#

What do you mean by frame rate doesn't affect it? Can you give an example?

weary moss
#

Update is linked to framerate, FixedUpdate just happens every couple of milliseconds

#

doesn't it?

ivory bobcat
#

If you acquired some delay of say ten seconds.. The Fixed Update loop will forcefully interpolate all of the lost frames.

weary moss
#

so it runs on it's own time?

summer stump
ivory bobcat
weary moss
ivory bobcat
weary moss
#

so if the framerate is lower it will happen like 2 or three times in between frames

ivory bobcat
#

It can also not have occurred at all per frame if you've got more frames than what the physics frames were set to

weary moss
#

so it's independent of framerate

#

but is it affected by Time.timeScaled?

ivory bobcat
#

If you're getting less than 50 frames per second, it'll buffer extra calls to fixed update. If you're making more than 50 frames per second, there may be no physics call on certain frames.

weary moss
#

thx dude

ivory bobcat
solemn fractal
#

!code

eternal falconBOT
solemn fractal
#

Hey guys,

I am trying to understand and follow some stuff I found to save and load the game in a simple way, as for what I need is just a few information. When I have the button save or load to appear, the game is under cs Time.timeScale = 0;
Here I have 3 classes.
SaveSystem: https://paste.ofcode.org/NJJgpWpb7g9dxf5wMWQKFR
PlayerData: https://paste.ofcode.org/UvGhGSreUqLfATYqAbCpQ
Player: https://paste.ofcode.org/qcqkvy9JJkAkrvmpeRREZ8

It is not working and seems to be all good. any insights? Thank you!

teal viper
#

What exactly is not working and what steps did you take to debug it?

solemn fractal
#

I put some debug logs to see if the i was getting into the SaveGame and LoadGame methods inside the SaveSystem, and also to see if the data was being fetched etc.. all looks fine.. when I start the game, there is a intro screen where I have load.. and inside the game while it is running when I use ESC the game pause with Time.timeScale = 0; and I click the button save. Stop to play the game.. play again hit loading and thigs doesnt change

teal viper
solemn fractal
#

True, because after I tested I deleted it

#

What I do to test is lose some HP

#

and save

#

close the game, open again, hit LOAD and nothing happens my hp should be instead of 30 should be 28

teal viper
#

You should keep the debugs when you ask for help. It makes it easier to see what you have attempted.

solemn fractal
teal viper
#

There is a slight chance the issue is due to the binary formatter being obsolete.

#

Did you check the file that is getting saved? Does it have any contents?

#

Are there any errors in the console during saving/loading?

solemn fractal
#

Not sure where is this saving, I will look for it: cs string path = Application.persistentDataPath + "/player.save";

solemn fractal
#

Oh

#

I got a IOException Sharing violation on Path

teal viper
#

Open the console and take a proper screenshot. Do you always check for errors like that?

solemn fractal
#

Oh yes sorry how is the correct way?

#

You mean like that?

#

I used like that: cs string fileContents = File.ReadAllText(path); Debug.Log("Path: " + fileContents);

rich adder
#

unrelated , but do avoid BinaryFormatter btw

solemn fractal
#

ok so which other method you advice me to use as a save?

rich adder
#

just json is fine

solemn fractal
teal viper
#

For binary there is a binary writer.
Though, I feel like the issue is unrelated to it being obsolete(I don't think it is in the dot net version that unity uses).

rich adder
#

yeah def unrelated was just saying prob not even needed

rich adder
solemn fractal
#

hmm ok, will try the json method. Thank u guys

rich adder
#

you're already saving json format no need to just use formatter

rich adder
solemn fractal
teal viper
#

Sharing violation implies that something else is opening the file.

#

Or writing to it.

rich adder
#

this is how you died

#

interesting name

solemn fractal
#

hahaha

teal viper
#

I wonder if you put that line inside the stream block...

rich adder
#

You tried writealltext already ?

#
        PlayerData playerData = new PlayerData(player);

        var stringData = JsonUtility.ToJson(playerData);

        File.WriteAllText(path, stringData);```
@solemn fractal
unreal imp
#

Guys, how can I generate a raycast in front of an object and have the line also point in front as if it were the player's camera? here part of the specified code:

solemn fractal
unreal imp
wintry quarry
#

do note that a ray coming directly from the camera in the direction the camera is facing is not going to be visible from that camera

#

it will be a dimensionless point from the camera's perspective

unreal imp
#

Yes but I want to see it from the perspective of the scene when I pause the game

wintry quarry
#

to make it the correct length it should be Debug.DrawRay(raycastOrigin, raycastDirection * raycastLength, Color.green, 3); though

wintry quarry
unreal imp
#

ahh duration xd

wintry quarry
#

Did you turn gizmos on?

unreal imp
wintry quarry
#

Do note you're only drawing this once in Start

#

if the object moves after the start of the game, this won't be that helpful

unreal imp
#

ahhhh ahahaha

#

zhank you

#

nahhhhh (the green line is my raycast)

#

And if you're wondering, the object holder is in front of the player's camera as if it were a raycast

rich adder
#

i just looked at your code again lol idk how i missed this

weary moss
#

is there a way to reliably sync a texture's offset speed with an object's transform speed?

rich adder
# solemn fractal What?

pretty sure that error is because you're trying to access the same file twice at same time

solemn fractal
#

why if i click one time in the btton?

rich adder
#

might be stream never cleaned properly

teal viper
solemn fractal
rich adder
#

ohh

teal viper
rich adder
#

ops spoiled myself with using statements now 😅

#

you got it working now though right ? @solemn fractal

solemn fractal
rich adder
short grove
queen adder
#

I have a list of sounds, like 1 heal folder have 40 heal soundeffects, what's the best way to get a random healing sound? I was thinking of resources, or AudioClip[] HealingSounds, dunno what is better and may there be any better way?

short grove
queen adder
#

if your game is 3d, use overlapsphere

short grove
#

Is 2d

queen adder
#

since it can lag the editor while open

slender nymph
#

but just a scriptable object that has the array and a method to pick a random one would be fine. then anything that needs to play one of the sounds can reference the SO

queen adder
#

that's probably better yes, I dont even have to make a global library that grabs an audio

halcyon osprey
#

I wanna be able to make triggers-to-spawnpoints like in here, but I cannot find the right guide for it

rich adder
amber spruce
#

so im making my game have multiplayer and this is my script that does the players animations and the animation is messed up for multiplayer it doesnt sync and when one person does it both do

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;

public class PlayerMovement : NetworkBehaviour
{

    public CharacterController2D controller;
    public Animator animator;

    public float runSpeed = 40f;

    float horizontalMove = 0f;
    bool jump = false;
    bool crouch = false;
    public float jumpcounter = 0f;
    public CharacterController2D charactercontroller2D;

    // Update is called once per frame
    void Update()
    {

        horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;

        animator.SetFloat("Speed", Mathf.Abs(horizontalMove));

        if (Input.GetButtonDown("Jump"))
        {
            if (jumpcounter < 2)
            {
                jump = true;
                jumpcounter++;
                if (jumpcounter == 1)
                {
                    animator.SetBool("IsJumping", true);
                }
                if (jumpcounter == 2)
                {
                    animator.SetBool("IsJumping", false);
                    animator.SetBool("IsDoubleJumping", true);
                }
            }
            

        }

        if (Input.GetButtonDown("Crouch"))
        {
            crouch = true;
        }
        else if (Input.GetButtonUp("Crouch"))
        {
            crouch = false;
        }

        if (Input.GetButtonDown("Sprint"))
        {
            runSpeed = runSpeed * 2;
        }
        else if (Input.GetButtonUp("Sprint"))
        {
            runSpeed = runSpeed / 2;
        }

    }

    public void OnLanding ()
    {
        animator.SetBool("IsJumping", false);
        animator.SetBool("IsDoubleJumping", false);
    }

    void FixedUpdate()
    {
        // Move our character
        controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
        jump = false;

       if (charactercontroller2D.m_Grounded == true) { 
        jumpcounter = 0;
        }
    }
}
cosmic dagger
rich adder
#

also probably to early for you to make a network game just my 2c

cosmic dagger
eternal falconBOT
amber spruce
#

sorry mb will do that next time

halcyon osprey
cosmic dagger
rich adder
timber tide
rich adder
#

you wanted pain.. welcome to pain

queen adder
#

Why do we have to type the parameter names of CreateAssetMenu btw? The suggestions doesnt even show after typing ,

#

For SO's

queen adder
#

yea

rich adder
#

wdym doesn't show ? what code editor ur using?

#

should work like any other method

fickle stump
#

I'm having a tunnel vision right now... Why is my function not working when I'm ticking "is clicked" on runtime facepalm

slender nymph
#

where are you calling collectPlans

wintry quarry
#

if (!isClicked)

fickle stump
#

basically what I'm trying to do is to follow this: https://youtu.be/cLzG1HDcM4s?si=iXZL7hf_fXq2DEQE&t=63 while making subtile changes like instead of doing an animation i want to unload my object

BMo

Interacting with GameObjects within your scenes is a core tenet to game development within the Unity Engine. I wanted to engineer a system that would show off Unity Events, while also being generic enough to slap on to any of your objects and wire up quickly.

Admittedly there are many ways to improve upon the basics I show in the video (as well...

▶ Play video
wintry quarry
static cedar
queen adder
static cedar
#

Not sure if it's possible in C# 9. But it's pretty similar to constructing new objects.

new MyObject() //these parenthesis is optional if you don't use a paramed constructor.
{
   ThisGetter = my_value,
   TTheOtherGetter = my_otherValue
};

The compiler will also recommend doing this by default. And if the setter is an init, you can only set it under those curly brackets.

amber spruce
rich adder
timber tide
#

you can search in the documents

amber spruce
#

so if im reading this right all i ahev to do for animations to sync is do instead of animator.SetTrigger("Jump"); i do networkAnimator.SetTrigger("Jump");

copper perch
#

I am about to release my game for internal testing.
With these 3 error messages is it just saying now that I just need to upload my game to the Play Store Console for Internal Testing and this is all I have left to do, and for the warnings, in my game there is no ads so the ads message does not apply to me right?
Also my game is 99cents to play for all 68 zombie bosses

wintry quarry
unreal imp
tawdry mirage
#

how do you name methods that do a lot at once? do you split them for clarity? i only need it to be done all at once. Maybe DoXDoYDoZ or DoX(bool doY, bool doZ) ?

summer stump
wintry quarry
#

But conceptually, let's say x y and z are "put clothes in washer" "put clothes in dryer" "fold clothes" then a method that does all 3 would be called "do the laundry".

#

And conceptually it should call those 3 other methods to do the individual tasks

tawdry mirage
#

so you would make public method DoTheLaundry and three private methods?

wintry quarry
#

Maybe? Access modifiers aren't really part of the discussion at hand.

#

That's basically a whole separate topic

#

Called encapsulation

#

Basically the idea with both naming and encapsulation is that someone who wants the laundry to be done shouldn't necessarily care about the details of how it gets done

#

So it's much better to name it "DoLaundry" than "WashDryAndFoldClothes"

tawdry mirage
#

i have Ship that can contain ShipPart, ShipPart can be isAdded true or false, and before i add ShipPart to Ship i snap ShipPart to local grid, update it's XY, update it's internals XY, then i use it's internals XY to check if this position is already occupied inside Ship. Then add or not add. So, i name it PrepareForAddingToShip?

summer stump
#

And make it check things first, if it can, do it

tawdry mirage
#

I have written it wrong. I snap, update xy in PrepareForAdding and i check XY in TryAddToShip

summer stump
#

Well, as they say, the two hardest parts in computer science are cache invalidation and naming things

#

I'm not sure why you don't check the position BEFORE snapping it and setting its local positions. Like just using a spatial query like checkbox or raycasting

tawdry mirage
#

i snap with step of 20m, 20m means 1 in XY

polar acorn
summer stump
#

That is so much better

digital lynx
teal viper
digital lynx
#

ol

#

ok

#

note: I'm literally hammering the spacebar while i was walking

#

according to the console, the Isgrounded was always false. I don't know how to fix it.

teal viper
eternal falconBOT
dense root
#

How do I get my ball component and set the color via code?

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Ball"))
        {
            if (!isPlayer1Goal)
            {
                Debug.Log("Player 1 Scored...");
                
                // TODO Create a serialized field
                GameObject.Find("Game Manager").GetComponent<GameManager>().Player1Scored();
            }
            else
            {
                Debug.Log("Player 2 Scored...");
                GameObject.Find("Game Manager").GetComponent<GameManager>().Player2Scored();
            }

            GameObject ball = GameObject.Find("Ball").GetComponent<Ball>();
            var ballRenderer = Ball.GetComponent<Renderer>();

            cubeRenderer.material.SetColor("Color", Color.red);
        }
    }
teal viper
dense root
#

Like this? I'm getting reference errors

var ballRenderer = Ball.GetComponent<Renderer>();

ballRenderer.material.SetColor("Color", Color.red);
#

How do I reference the ball component in code?

teal viper
#

What happened to the code that you shared previously with the Find method?

#

Also, if the colliding object is the ball, you can get the Ball component from it.

dense root
teal viper
#

Don't you see that it's a different variable?

#

Or rather a type name

dense root
#

I do now lol

teal viper
#

Case matters in programming

#

Usually

dense root
#

Hmm no compilation errors but it won't change the color

GameObject ball = GameObject.FindWithTag("Ball");

var ballRenderer = ball.GetComponent<Renderer>();

ballRenderer.material.SetColor("Color", Color.red);
#

Maybe it has to do with material being set instead of something else?

#

Something like .color

teal viper
#

Make sure the material/shader had a property with that name.

dense root
#

I'm just using the simple sprite renderer

teal viper
#

That's a sprite renderer. You should not modify the material then.

#

Instead of getting the base class, get the SpriteRenderer. It has a color property.

dense root
#

okay let me see what I can do

#

Got it thank you! @teal viper

#

How do I set it to a random color?

teal viper
dense root
#

It points me to Random.ColorHSV which doesn't seem work with it

slender sinew
#

you aren't calling the function properly

#

it's a function call

#

read the error message thoroughly

#

you are trying to do color = Method; instead of color = Method();

dense root
#

Yeah I figured that out

#

Thanks all

tawdry mirage
#

isn't it too painful to look at?

if (shipPartTiles[forX, forY] != null) shipTiles[shipPartTiles[forX, forY].x + 50, shipPartTiles[forX, forY].y + 50] = shipPartTiles[forX, forY];
sharp wyvern
#

(IMO)

#

Tile part = shipPartTiles[forX, forY]; I'd make that, then use it in the if and following

static cedar
#

Yes.

tawdry mirage
#

better?

shipTileToAdd = shipPartTiles[forX, forY];
shipTileToAddX = shipTileToAdd.x + 50;
shipTileToAddY = shipTileToAdd.y + 50;
if (shipTileToAdd != null) shipTiles[shipTileToAddX, shipTileToAddY] = shipTileToAdd;
#

ahh null reference

wary sable
#

When attempting to access an animation clip using AssetDatabase I get Failed to load "path" File may be corrupted or was serialized with a newer version of Unity. Our project has stayed on the same version and these animations can be handled and used in editor without issue...

#

Have no clue what could be going wrong

sharp wyvern
# tawdry mirage ahh null reference

this way will handle the ifnull part, AND is still easy to read if (shipTileToAdd != null) shipTiles[shipTileToAdd.x+50, shipTileToAdd.y+50] = shipTileToAdd;

tawdry mirage
sharp wyvern
sharp wyvern
#

warning- may take a longtime to rebuild

sullen rock
#

is it possible to somehow serialize this?
public int teleportIndex { get; set; }

gaunt ice
#

field:serializefield

wary sable
#

figured out the issue

#

when testing I was using an animation clip I had made in editor (meaning it was an actual .anim asset) whereas the files I was actually running the script on were .fbx despite them both being 'clips'.

#

so changing .anim to .fbx in the script solved it ThumbsUP

velvet herald
#

Im trying to make a game where u can upgrade ur attack

#

And upgrading it would provide different properties

#

Like maybe a swing will add a spawn small projectiles to shoot

#

Or maybe it can reflect enemy bullets

#

If thats the case, should I use scriptable objects?

wary sable
#

that really depends on a lot of different things, but its good to note that you can't serialize SO's, so if and when you modify data like weapon level that will have to be stored elsewhere. With that said SO's are great for static properties / methods... So if you have an upgrade path that you want pre-defined you can have that all pre set in the SO.

sullen rock
velvet herald
#

Does that mean SOs arent odeal

gaunt ice
#

**field:**serializefield

wary sable
velvet herald
#

So how should I approach it

#

Make multiple variations of th weapon with different properties?

wary sable
#

Depends… especially with inventory type stuff there isn’t really a great one size fits all answer. But generally in this case, if you are only going to have one of each weapon then SO’s will be great. If there is duplicates but only a set number of them, so long as that number is reasonable then SO’s would still be great. If you are planning on having the same weapon drop multiple times and you want the player to be able to have multiple of the same weapon with different levels you can still use SO’s but you may have to store the weapon level elsewhere like a POCO (plain old C sharp script)

velvet herald
#

I was planning to do smth like Hades

#

But instead of a selection to choose from we only have one

#

And as u progress in stages, you can choose upgrades that adds new properties to the weapon

#

Aside from that are boosts like movement speed and health

#

I think solid stats arent too dofficult to adjust

#

But the weapon additions are what im struggling with

wary sable
#

From the sounds of it Scriptable Objects for each of the weapons will be a solid system. As for upgrades that one can be tricky depending on how scalable and or universal you want things to be. I don’t know if I can give you any good answer for adding them to attacks as combat is a whole other ordeal that I’m just beginning to learn as well. But I would recommend starting by handling attacks from each SO where the attack code includes all of the effects / upgrades to the attacks locked behind if statements… that may not be the best system in the world but starting on something simple like that will get you moving in the right direction.

#

Unfortunately running into problems is really the only way to learn if something works or not. You just kinda have to go for it and throw stuff at the wall as sucky as it is

blazing relic
#

Can someone explain why this code doesn't print SUCCESS ?

{
    int seed = UnityEngine.Random.Range(1, int.MaxValue);
    System.Random oneInSix = new System.Random(seed);
    System.Random fiftyOneinSixtyTwo = new System.Random(seed);
    int roll1_6 = oneInSix.Next(0, 6);
    if (roll1_6 == 5)
    {
        int roll51_62_fourTimes = fiftyOneinSixtyTwo.Next(1, 63);
        if (roll51_62_fourTimes < 52)
        {
            roll51_62_fourTimes = fiftyOneinSixtyTwo.Next(1, 63);
            if (roll51_62_fourTimes < 52)
            {
                roll51_62_fourTimes = fiftyOneinSixtyTwo.Next(1, 63);
                if (roll51_62_fourTimes < 52)
                {
                    roll51_62_fourTimes = fiftyOneinSixtyTwo.Next(1, 63);
                    if (roll51_62_fourTimes < 52)
                    {
                        Debug.Log("SUCCESS!");
                    }
                }
            }
        }
    }
}```
Is my brain completely failing to grasp something or is this an issue with pseudo-random generation? I am trying to complete a 1/6 trial followed by 4 consecutive 50/62 trials. If my math is correct, which it may not be, I would expect about a 6% success rate, yet in 10,000 trials, Success is never printed. I feel i am definitely missing something regarding the way Random works...
languid spire
blazing relic
languid spire
#

to try what you want you need to change

int seed = UnityEngine.Random.Range(1, int.MaxValue);

to

int seed = i;
#

and it's all well and good just printing out SUCCESS!. You still have no idea how it got there so the whole exercise is pointless

blazing relic
blazing relic
languid spire
#

the difference is it gives you control over what happens after. At the moment you have no clue as to what is being fed into the algorithm. So Garbage in, Garbage out

languid spire
blazing relic
#

No

languid spire
#

Then ask yourself, how far down my logic do I get?

blazing relic
#

It shouldn’t matter if you stay with the same seed or change the seed every trial… if the Next() number is always random, then it should be just as likely to hit the success on the first trial as the next… no?

languid spire
#

yes, and the chances of that happening 5 times in succession are virtually zero

blazing relic
languid spire
#

but that is not what your code is doing

blazing relic
#

well what would the code look like if thats what it was doing lol

languid spire
#
for (int i = 0; i < int.MaxValue; i++)
{
    int seed = i;
blazing relic
#

thats gonna run 2 billion times...

gaunt ice
#

2 billion iterations...
probably multithread it

languid spire
#

yep

eternal needle
#

you're trying to find a seed which does something very very very specific, this is gonna take time no matter what you do

languid spire
blazing relic
#

why do i need to run 2 billion times if my expected success is 6%?

gaunt ice
#

or looking at the algorithm on how the .Next output the int and try to find out the bit patterns

languid spire
#

you need to find which one of the 2 billion is the right one beacause you do not know

craggy lava
#

How do i make a firework and tool system like firework mainia

gaunt ice
#

what is firework mainia

craggy lava
#

A game on steam

blazing relic
eternal needle
modest dust
blazing relic
#

is my calculation of 6% wrong?

modest dust
#

How about something more specific, what exactly are you having a problem with?

eternal needle
gaunt ice
#

it is not cryptosecurity random number generator so it should be possible? though it is still quite hard to reverse engineering

eternal needle
#

true but still would require some decent beginner knowledge to even know where to begin

blazing relic
#

closer to 7%

gaunt ice
#

is 51/62 indeed, so a bit higher

#

the range is [1,52) so 51 possible number, the min should be inclusive

languid spire
#

Also this is based on one seed. You need to know the seed value first

blazing relic
#

if i repeat for a ton of different seed shouldnt i get a success after 100000 seeds?

languid spire
#

so stop changing the seed every loop, do what I first said and move that out of the loop

languid spire
#

right which means that your 7% is wrong

blazing relic
#

yes but why

languid spire
#

no idea, I'm not a mathematician

eternal needle
#

are u sure u saved your script or something after moving the code?

#

i tested this on a online compiler and i get success printed

blazing relic
eternal needle
#

quite literally the same thing you posted, with moving the seed part outside the loop

#

only changed debug.log and the unity random because im using an online compiler

blazing relic
#

My goal is to find a seed which will grant a success on its first attempt, so i need to check a new seed every-time...

languid spire
#

which your code does not do but my amended for loop does

blazing relic
#

sorry im getting sassy lol

#

yall just trying to help

#

but it doesnt make sense

languid spire
blazing relic
#

Not that one. 2 billion is gonna freeze up my machine

languid spire
#

coz thats the only way to find the seed you want

blazing relic
#

but why.... the success rate should be so high

#

need a math person to explain it to me

#

i need to go back to stats class

languid spire
#

logically.
If the success rate is 7%
and you want to hit it on the first go then...
the correct seed should be 7% of all possible seeds so...
you need to find that 7% within the int.MaxValue range
so how much of int.MaxValue is 7%?

blazing relic
#

about 140mill

#

lightbulb

languid spire
#

right so logically if you loop for 140m you should find 1 which works

blazing relic
#

it finally makes sense

#

lol

languid spire
#

assuming non random spread

blazing relic
#

ok im running it now 🤞

keen dew
#

Sorry but that makes no sense at all. If there's a 7% chance then running it 100 times gets you through on average 7 times, regardless of how many possible seeds there are. By the same logic if there's 100% chance to succeed on first try you'd need to loop through all int values to find one.

#

I think this is the problem:

    System.Random oneInSix = new System.Random(seed);
    System.Random fiftyOneinSixtyTwo = new System.Random(seed);
#

You're using the same seed twice. If oneInSix rolls high then fiftyOneinSixtyTwo also rolls high on the first go

languid spire
#

I'm not sure why he has 2 different randoms either

#

his probability calculation is surely based on using the same random seed for all throws

eternal needle
#

From experimenting actually, this seems like the perfect number choice to be impossible with what Nitku said. If the first number rolls 5, the second number is always 52 or higher..

eternal needle
blazing relic
blazing relic
eternal needle
#

Very unlucky that you needed the exact numbers that weren't possible with your code

blazing relic
#

when i was first running it i was like why is the first number (after 1/6 trial) always high? but then i kinda got rabbitholed

eternal needle
#

I assume random.next uses decimals then and multiplies to get within the range specified, rolling a 5 from 0-6 would be 0.833 and above. 0.833*62 is just 52 if rounded up

blazing relic
#

damn thats brutal

#

woulda saved myself so much time if the numbers were just slightly different

#

it has to do with item droprates

#

but i wouldnt have learned 🤓

eternal needle
#

Guess it's good to know for my game too which relies on rng heavily

vale blade
#

how do I handle coroutines in non-monobehaviour classes?

i.e.
I have a GptApiClient class that I use to post a message and receive a response from the OpenAI API

what I did before was make GptApiClient : MonoBeheaviour and then access it through a singleton. that allowed me to start a coroutine for the PostMessage function.

Trying to refactor my code now so that GptApiClient is just a public static class that doesn't extend from MonoBehaviour, but now I'm confused as to how I would handle the coroutine?

eternal needle
blazing relic
#

oml so many successful seeds 😭

burnt vapor
#

Though this does need to call back to the main thread

#

But you're better off having a Monobehaviour do it

#

But you can totally iterate the IEnumerator from a Coroutine yourself in a way, it just takes time to implement and I doubt it's any better

eternal needle
# blazing relic oml so many successful seeds 😭

Are u just reusing the same one random instance now? I assume that's the easier fix for this. I was reading before 1 in 140m seeds and was thinking this makes no sense but had no other explanation why it didnt work lol

burnt vapor
blazing relic
#

The instances must stay separate cause they control different aspects of the game

#

so random instance 1 checks the first value and random instance 2 checks 2-5 values

eternal needle
#

I see, I guess that can be useful to get the same generation each time with a certain starting seed

languid spire
blazing relic
#

my tutorial finally has the perfect seed for the start of the game :)

#

thanks all

naive pumice
#

Hi guys, i am building a linux build using IL2CPP on my Mac (intel chip) for a dedicated server, and it's taking forever on the Linking GameAssembly.so (x64). Is it normal ?

rare basin
naive pumice
#

not really but i could not find where else to post it, can you tell me please ?

tawdry mirage
#

cannot do that?

static cedar
#

Set it on Awake.

tawdry mirage
#

oh okay. That could be 150% quality of life

static cedar
#

Just replace it with { get; private set; } of course.

burnt vapor
#

Not sure why you would need to do this since it looks like a bad dependency loop, but maybe you want to use a generic type instead?

tawdry mirage
#

i'm not sure, i'm just refactoring my code to make it look more clear and with less lines

burnt vapor
tawdry mirage
#

ActorLogic will use this Actor later. ActorLogic had SetActor method and i wanted to remove it

#

yesterday it all was in Actor class, today i wanted to split my giant wall of text into several classes

#

ActorLogic will only exist inside Actor

burnt vapor
#

Right, usually something depends on another thing but it would not go into a loop like this

#

Because this is a way to get stuck with dependencies

#

So if both things depend on eachother maybe it should just be one class

#

Or maybe Actor should inherit from ActorLogic

teal viper
#

If you want to separate logic from data, it's usually the other way around: MonoBehaviour contains the logic, while a plain class is used for data.

tawdry mirage
#

Actor has logic related to basic things like moving, turning, shooting while ActorLogic has logic related to it's AI

#

i'm bad at organizing it)

teal viper
#

Might be better to name it appropriately then. Maybe even make it a separate MonoBehaviour.

burnt vapor
#

And the logic class inherits itself from MonoBehaviour

tawdry mirage
#

do people usually spilt their big classes with inheritance?

burnt vapor
#

Well your class is a base class that contains movement and all that

#

You can also just keep it a separate class and emit events from it depending on how you move

#

Whatever you do, you should not have to make a looping dependency like this

tawdry mirage
#

if i call some method inherited from parent class, is it faster than calling some method from other class?

burnt vapor
#

Don't worry about performance

#

It's not something you should think of, especially not here

#

There are some specific rules but those are not related

tawdry mirage
burnt vapor
#

Yes

#

You should not need that because then it should just be a single class

#

Usually A depends on B, and B will emit events that A should then subscribe to

vale blade
burnt vapor
#

JsonUtility 🤮

#

Right makes sense I guess, you're using the Unity web request system

vale blade
#

yeah

vale blade
burnt vapor
#

Eh I'm usually against these things, especially now that Unity has better support for Tasks so you could just use HttpClient

rare basin
#

the old web request system

serene mango
#

I get this error but how can I search and find my object by this ID?
Can't Generate Mesh! No Font Asset has been assigned to Object ID: 88474

solemn bobcat
queen adder
#

i want to make a game where a storm is created every 1/10000th frame. i have 2 scripts at the moment. 1 where i want to start the storm itself based on what type it is. but in my 2nd script i have the type of the storm that i want to give to the first script.

my question is, is it easier to just combine this into 1 script or is there a way for me to easily link these 2 scripts?

timber tide
#

I think you should revaluate how much you want to get done in a single frame

queen adder
#

quite new to unity and dont know how everything completely works. seems to be working fine atm. just want a way to link 2 scripts between one another or if i should do it in one script.

rich adder
timber tide
#

Oh, you want to spawn one for every 10000 or so frames that have passed, is that what you're doing.

swift crag
#

do you really care about frames, though

timber tide
#

or 10000 objects per frame, maybe I should make myself a coffee

swift crag
#

or do you care about time

#

You almost never measure durations in frames, since the player's framerate will be varying (and different players will experience different average framerates)

queen adder
#

i have a 1 in 10.000 randomizer that gets pulled every update()

#

;-;

wintry quarry
queen adder
#

maybe doesnt work that i usually work on arduino and other embedded systems that use a "loop()" function

queen adder
rich adder
#

communicating between scripts isn't that much different in unity than standard c#

gaunt ice
#

unity update is running inside a loop

while(1){
  update() and other monobehaviour messages
}
rich adder
#

the only differences is monobehaviors + inspector

queen adder
rich adder
#

since monobehavior can't be created with new()

queen adder
#

so if i want to refer to another script, i can drag it into my other script using the inspector or what?

rich adder
#

unity does that when its on an object

queen adder
rich adder
queen adder
#

ahh gotcha, thanks alot. ill go try that now

wintry quarry
queen adder
#

yea no i got that. to me that translates over p well from c# itself

swift crag
#

If you want an event to happen once every 1000 seconds, I'm pretty sure that's just:

#

oh wait, it's not just that

#
if (Random.value < 0.001f * Time.deltaTime))

This is wrong. If Time.deltaTime was 1000, you'd have a 100% chance to trigger the event

#

(well, unless Random.value returned 1, which it can do: it's inclusive)

#

it's been a few years since i took that randomized algorithms class. i am bad at this

#

oh god i'm getting nerd sniped here

#

the objective is to, for a time interval, calculate how many events have occurred

#

it's easy to calculate the expectation (the average value), but I'm not so sure about randomly drawing

swift crag
#

it's a decent enough approximation

cosmic quail
#

isnt it better to use coroutine for this?

swift crag
#

That would be a reasonable choice! you'd just randomly pick a delay.

#

That sounds more consistent. The player wouldn't expect two rare events to occur back-to-back

#

what is this component?

#

check the value and options properties

autumn tusk
#

how would i make a prefab have a sprite then switch to an animation after colliding with an object in unity 2d

autumn tusk
rich adder
#

switching to animation would be as simple as switching state

novel shoal
#

public class airplanemovement : MonoBehaviour
{
public float speed;
public float turnspeed;
public float axisx;
public float axisy;
void Start()
{

}
void Update()
{
    axisx = Input.GetAxis("Horizontal");
    axisy = Input.GetAxis("Vertical");
    transform.Translate(Vector3.forward*speed*Time.deltaTime);
    transform.Rotate(0,axisy * Time.deltaTime * turnspeed,0);
    transform.Rotate(axisx * Time.deltaTime * turnspeed, 0, 0);
}

}
this script should change the direction of the plane:
with the horizontal axis it should change between left and right, with the vertical it should change the height, but it inverts them: with the vertical left and right and with the horizontal the height

novel shoal
rich adder
blissful heart
#

im doing that rn

#

at paste of code

#

navarone is the real OG

novel shoal
blissful heart
rich adder
#

X axis is always up and down

#

rotation wise

novel shoal
#

oh i think i get it

rich adder
timber tide
#

z forward, x right, y up

blissful heart
#

So, just started working with unity like a week ago. I already got experience in GameMaker, but i wanted to do more "professional" games.

Im doing a mobile game that everytime you click on the screen, you spawn a new unity thats called "ally". It'll already have enemys in the scene, and both allies and enemys will have an AI, so they will run to eachother and attack when they have range. The enemy will be stronger than the ally, so you will need to create a strategy to win (for example, click faster to spawn a lot of allies, or flank the enemys clicking on different locations of the screen).
Ok, the "gamedesign" is basically that. The playerr only job going to be click on the screen, and watch the war happens.

But im having an issue. Since in new to this, im having MAJOR issues at programming the attack damage, and the hp.

heres the code for both EnemyController and AllyController: https://paste.ofcode.org/wjd7SkmhDtTfuUYMfj2QZu

So i guess the problem is there im calling the damage a lot of times and its not proper working, the ally is not killing the enemy while the enemy can kill the ally without problem. PLEASE can someone help me?

Oh, and another thing, ignore the // comments, im Brazilian and I wrote the // comments on portuguese, my language. Just ignore.
And also ignore the animations code, i used a transition.

Please help me to get my game going correct ❤️

#

Sorry for the huge text wall guys

rich adder
#

lol we didn't need the whole backstory 😆

blissful heart
rich adder
#

nah im just jk but yeah its hard to read what the problem actually is

#

so the ally can't kill enemy right ?

blissful heart
#

i havent send the code for GameController, but is basically just instantiate when u click

rich adder
#

all the attacks and debugs are working ?

blissful heart
rich adder
#

printing

#

ok

blissful heart
hexed terrace
subtle hedge
#

Hey is there a channel for playstation here ? Cuz I get lots of wired bus on a playstation port but in editor everything seems fine

rich adder
#

esp Update

hexed terrace
subtle hedge
hexed terrace
#

ok?

north kiln
#

Use the closed Playstation forums

#

you can't legally discuss PS development outside of the closed forums

blissful heart
rich adder
#

oh jeez someone needs to learn about OBS 😅

#

lets make a thread rq so we don't flood chat

blissful heart
#

hahahahahaha im no streamer bruh

blissful heart
#

thanks a lot for your willing to help

rich adder
#

Ill try hehe

#

So, just started working with unity like

umbral bough
#

Hi, is there a way to retrieve the current focused go from the standalone input module component?

timber tide
#

currentSelectedGameobject?

#

or is focus a different attribute

umbral bough
#

currentSelectedGameobject from the EventSystem doesn't appear to be working on UI elements

timber tide
#

Ah, UI specifically I think I recall a method for that, but usually the event system has that info too.

#

maybe I could find it if unity decides to be nice and open one of my projects

#

Ah, this maybe what I'm thinking of. Was using it for a hybrid keyboard w/ onscreen

abstract finch
#

I want to spawn some orbs after an enemy dies in a parabola arc until they hit the floor. Is it more performant to use code driven arcs rather than rigidbodies w/ gravity?

timber tide
#

if you're not using colliders for your first method than it would probably be more performative otherwise probably not too different.

#

actually non-kinematic rigidbodies would still have a lot more overhead so if you are spawning hundred of orbs then it's best to avoid it

umbral bough
timber tide
abstract finch
# timber tide if you're not using colliders for your first method than it would probably be mo...

I see I could use colliders but also have them do overlap sphere even?
Heres what im trying to replicate
https://youtu.be/B7IHMtRMR50?feature=shared&t=63

How to loot the Mimic/Fake treasure chests in Nioh 2.
-When you come across a chest in Nioh 2 that has three gold bands on the side instead of two this means that it is a mimic chest.
-To deal with it without fighting simply use the whistle gesture and then copy whatever gesture the clone uses.

More Nioh 2 Guides!
Purple Kodamas Explained: http...

▶ Play video
umbral bough
#

yes

timber tide
# umbral bough yes

There's IPointerHandler for when you want to specifically call an event when you're over that specific UI element

umbral bough
#

yeah, wish I could use that

timber tide
#

oh, there's also probably a buffer you can read from for current hovered gameobject

umbral bough
#

I'd just use a regular unity event and then pass that object in the inspector

#

but our uni forces us to use visual scripting and I don't feel like living :/

#

ik that this isn't the visual scripting channel, that's why I asked a specific question about the thing that held data that I needed and it's fine if it's not possible to retrieve it, will find another way ig

timber tide
rare basin
#

why can't you use IPointerEnter, IPointerExit?

#

and cache the last hovered UI object

#

oh okay didin't read the visual scripting part

umbral bough
rare basin
#

yea that's pretty much the same

timber tide
rare basin
#

just cache the game object you've hovered

#

the do whatever you want with it

umbral bough
umbral bough
#

mao recommended rc which seems reasonable but I was hoping that it's possible to retrieve it from the standalone input cuz it has a focused object var but it is prob private

rare basin
#

make a "SelectionManager" singleton or something

#

and cache it there

#

whenever OnPointerEnter triggers

timber tide
#

yeah ive no clue about visual scripting beyond the vfx / shader graph haha

rare basin
#

for sure you can do this

#

can't do it from EvenSystem.current iirc

#

you either need, as Mao said, make a custom raycast (graphic raycast, not phyiscs raycast)

#

i think you can also do EventSystem.current.RaycastAll()

#
EventSystem.current.RaycastAll(new PointerEventData(EventSystem.current) { pointerId = -1 }, results);

        if (results.Length > 0)
        {
            GameObject hoveredObject = results[0].gameObject;
            Debug.Log("Hovered object: " + hoveredObject.name);
        }
timber tide
#

I would expect currentgameobject from the event system to work if you're hovering over buttons and stuff, or any UI element with selection interface implementation

rare basin
#

sth like that

rare basin
umbral bough
#

and I do have my event system properly set up in the scene

rare basin
#

text components are not Selectable

#

so they cannot be selected

umbral bough
#

i see

rare basin
#

You need a Selectable inheriting component

#

such as Button, Slider, Dropdown, Input fields, toggle etc

timber tide
# umbral bough

So in this case you'd raycast and compare against if it's selectable

#

oh wait, you're looking for a transform here. You'd want a rect transform.

#

better to grab by the type than transform values anyway

#

Get Current Selected GameObject -> Get ISelectable, or button if you only need that specific type.

umbral bough
#

well the issue is that even tho the element has a button component attached, es doesn't recognize it as a selected object :/

modest barn
#

Hi. What is the name of the library that fills the blank for using ___ for the TextMeshPro (TMP) library?

[SerializeField] TMP_DropDown dropDownObject;

I'm trying to do this but Unity says that it can't find the type TMP_DropDown so I suspect my library name is wrong. I've tried a few, like TMP, TMPro, TMPPro, etc. but none work.

#

Also struggling to find this information online (probably looking in the wrong places).

rich adder
#

are you not?

modest barn
#

I tried that because I sw it at the link @polar acorn sent, but it still doesn't work?

modest barn
#

Oh 🤦

rich adder
modest barn
#

DropDown vs Dropdown. Sorry guys

polar acorn
#

.value

modest barn
rich adder
modest barn
#

About to send 🙂

modest barn
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class DropDown
{
    public DropDown()
    {

    }

    [SerializeField] TMP_Dropown dropDownObject;

My code ^^. The error:

CS0246: The type or namespace name 'TMP_Dropown' could not be found (are you missing a using directive or an assembly reference?)

Line 13 is the line where I serialize and define dropDownObject.

polar acorn
modest barn
#

Oh ffs

#

Can't believe myself sometimes. Thanks

rich adder
#

what "doesn't work" mean

polar acorn
#

Neither of those are .value

#

If you need the value from a slider, .value is how you get the value of a slider

modest barn
#
'Dropdown' is missing the class attribute 'ExtensionOfNativeClass'!

What's this?

wintry quarry
wintry quarry
modest barn
#

And it did that

#

But I've done that a bunch of times before, and it always work.

wintry quarry
#

show what you're trying to do

polar acorn
modest barn
# wintry quarry There should NOT be any constructors on a MonoBehaviour

It's not a MonoBehaviour

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

public class Dropdown
{
    public Dropdown()
    {

    }

    [SerializeField] TMP_Dropdown dropDownObject;
    TMP_Text dropDownValue;
    
    void OnValueChanged()
    {
        dropDownValue = dropDownObject.captionText;
    }
}
polar acorn
modest barn
#

Ahh that'll be the issue then. Can I still use it in a TMP_Dropdown gameobject's OnValueChanged() function, for example? Where I drag the script in and select a method to be ran.

polar acorn
#

How would you reference an instance of it?

#

Also probably not a good idea to name a class the same thing as a Unity component

modest barn
polar acorn
modest barn
#

I just want the script's OnValueChanged() method to be run whenever the TMP_Dropdown object has its value changed. Then I would need to access the text of the selection made, which is within the captionText attribute. I would need the class to be instantiated for that, right?

rich adder
#

desnt dropdown already have its own ValueChanged you can sub to another MB?

#

whats the point of this class being a poco

modest barn
rich adder
#

plain old c# object

modest barn
#

Haha

polar acorn
modest barn
rich adder
rich adder
#

ie run this method when value changes on dropdown

#

there are multiple events too

modest barn
#

So I've created a method in a script and I've added that as a component to the TMP_Dropdown GameObject. Is that what you mean by subscribing to an event?

modest barn
polar acorn
modest barn
#

Yes I believe I did that. Let me send you a screenshot.