#archived-code-general

1 messages · Page 213 of 1

thick socket
#
 Vector2 position = transform.position;
        position.x += groundedBox.offset.x;
        position.y += groundedBox.offset.y;
        RaycastHit2D[] hit = Physics2D.BoxCastAll(position, groundedBox.size, 0, Vector2.zero, 0, mask);
#

however I have no idea why its not grabbing the box/offset correctly

main shuttle
#

Is the tag/layer of the right wall correct?

thick socket
#

is there a way to debug this? drawRay isn't the answer

        RaycastHit2D[] hit = Physics2D.BoxCastAll(position, groundedBox.size, 0, Vector2.zero, 0, mask);
main shuttle
#

And the whole wall is 1 piece with the correct layer then I would guess?

thick socket
#

its only the hitting the left side of walls thats the issue

#

when it hits the right side of walls it works fine

static matrix
#

does making an array initialize all the elements in the array to null, or does it just say "There can be two elems here, but there aren't right now"

#

like if I get Array[1] right after creating it what does it return

rocky helm
#

if its an array of integers, it will return 0 I believe

#

if it's an array of lists for example, it will return null

static matrix
#

ok null then

prime sinew
#

Google "how to use lerp unity". There's an article

rocky helm
gaunt blade
#

guys I think I've got some fundamental misunderstanding about how to design something in unity. I have a composition based ability system where I create projectiles GameObjects then attach components to that have behaviours. How am I supposed to change the fields in these components? They need to on a GameObject to be edited because of monobehaviour, but then they would cause their specific behaviour on objects I don't want them to. I thought about making prefabs but I also want items that contain the components and copy them to the abilities. Should I just put the components on objects but dissable them? or is there some other method of designing this which I am not aware of?

static matrix
#

? not sure what you are asking but did you make the variables public

gaunt blade
#

hmm let me try explain

#

its not that I understand that

rocky helm
#

As to me, a ScriptableObject sounds like what you are looking for, like a data container kind of

gaunt blade
#

yeah

#

but scriptable object doesn't have monobehaviour so I can't use update and stuff?

lean sail
static matrix
#

if the value type is a gameobject

#

id presume it null?
it worked anyways

rocky helm
# gaunt blade but scriptable object doesn't have monobehaviour so I can't use update and stuff...

Yes, but for that perhaps you could have 2 things? One projectile script that handles the logic and stuff, and then a scriptable object for each of the projectiles that contains their data? https://www.youtube.com/watch?v=aPXvoWVabPY

When making a game you need a good way of storing data. This is where Scriptable Objects come in! In this video we’ll learn how to use them by looking at an example: Making cards for Hearthstone.

● Project on GitHub: https://github.com/Brackeys/Scriptable-Objects

♥ Support Brackeys on Patreon: http://patreon.com/brackeys/

····················...

▶ Play video
lean sail
static matrix
#

cool

gaunt blade
lean sail
gaunt blade
#

This is with the items

#

i suppose i should just use refereces to prefabs?

#

a prefab for items and prefab for abilityt?

static matrix
#

I leave for two seconds and you've brought up diagrams

rocky helm
# gaunt blade This is with the items

If you are putting a monobehaviour on a gameobject just because you need to edit variables from the editor and not because you need the monobehaviour to control the gameobject, then you can use ScriptableObjects, which are just data containers

static matrix
#

if you need a ticking function in a scriptableobject, you could use a tickmanager that iterates through all the scriptableobjects and calls OnTick for each of them (although you would need a base class then)

that may possibly be the worst possible solution but eh

lean sail
# gaunt blade This is with the items

You'll probably need to explain more about what an items relation to abilities are or like why these are even copied in the first place. Right now your diagram shows 2 completely unrelated scripts communicating to an instantiated object so it doesnt really make sense.

rocky helm
# gaunt blade oaky thank you

When making a game you need a good way of storing data. This is where Scriptable Objects come in! In this video we’ll learn how to use them by looking at an example: Making cards for Hearthstone.

● Project on GitHub: https://github.com/Brackeys/Scriptable-Objects

♥ Support Brackeys on Patreon: http://patreon.com/brackeys/

····················...

▶ Play video
gaunt blade
#

my question i suppose is just how should I store these components such that they are easily editable in the edtior and can be instantiated on the projectile object with the correct values

lean sail
gaunt blade
#

the items just store the behaviour components to be added to the object

#

like 'explodes on hit' or something

#

then i copy these to the game object

#

the projectile will not communicate with the item

lean sail
#

Hmm that might start to cause issues, like you wouldnt be able to use object pooling too easily in this case

thick socket
gaunt blade
lean sail
#

Maybe you could have an event for when damage is dealt, then have a player script decide what effects to do after (like explode in the area that was hit)

gaunt blade
#

yeah that's what i've got basically

#

So if I got down the scriptable object route would I need two scripts? A monobehaviour script to carry out behaviours and then a scriptable object to store value in the editor? like this?

steady moat
# gaunt blade

Pretty much, you can also use POCO (Plain Old C# Object). That being said, using Prefab can really help because you get free copy.

public class Explosion : ScriptableObject 
{
  [SerializeField] private GameObject _prefab;

  public void Spawn(...)
  {
    _prefab.Instantiate(...);
  }
}

hard viper
#

You can do something like making a movement parameter SO, with things like speeds, gravity etc. And have several different obj with that SO.

#

The benefit is: 1) You can couple multiple things by using one SO instance for multiple gameobjects. So editting the one SO saves you from having to go find and edit them all. 2) You still reserve the right to make another instance of the SO if you want to make another that is decoupled

#

eg You have an EnemyMovementData : SO, make a GenericEnemyMovement.asset from it, and tie it to a goomba and koopa,

turbid hazel
#

hey guys, any idea why it always stay null?
tried both GetComponentInChildren and GetComponent

The script is monobehaviour and on the player parent.

hard viper
#

null means it did not find a component of type Rig in the children

turbid hazel
hard viper
#

is the child inactive?

#

and does the child have a component of type Rig?

#

and by child, you sure it is a child in the hierarchy?

turbid hazel
#

yes please check the second screen

mellow sigil
#

Why are you using Find and GetComponents instead of dragging the references in the inspector?

hard viper
#

GetComponent is good

turbid hazel
#

most likely i will add coop and have different characters

hard viper
#

but can get messy if you start splitting scripts across multiple gameobjects

turbid hazel
#

so it need to find it "dynamically"

mellow sigil
#

That makes no sense

hard viper
#

that is not true

#

that does make no sense

mellow sigil
#

If you have different characters you drag their references too

hard viper
#

i would first check rigMelee is correct

#

should be a non-null reference to the right object. And also it only needs GetComponent since it isn’t in children

#

then debug.assert non-null

turbid hazel
hard viper
#

yeah, I would not use .Find

turbid hazel
#

what could i use instead?

hard viper
#

I would [SerializeField] private Transform rigMelee;

#

I would not fuck around with those GetComponents and find methods in this case. You want a direct reference to the thing

west lotus
#

The rig is on the parent object right?

hard viper
#

Rig component is on the RigMelee object which is a child of the main Player object

#

which has the script

mellow sigil
#

Find and GetComponent will also get just one specific rig from one character so that doesn't solve anything

#

If you want a reference to multiple child objects then make arrays and drag all the references to there

hard viper
#

in general, if you have multiple child objects, you want to avoid using Find or GetComponentInChildren. You want direct reference to the one thing you’re looking for

turbid hazel
mellow sigil
#

That's not a good way to do it

hard viper
#

yeah that’s bad

#

don’t do that

#

Serialize the field

#

specifically, serialize the transform of the child object

#

Seriously don’t fuck around with that

#

you don’t want your code for finding components to depend on what is or is not active at the time, unless you actually want it to depend on that

mellow sigil
#

Assign the script that handles these things to all characters, then the one that is active automatically does what it should. Don't have one script that tries to pick the things it needs from the one character that happens to be active

hard viper
#

just use a prefab, bro

#

prefab can serialize field for specific components in the prefab, and it will reference them correctly

turbid hazel
#

hehe should we continue in beginner?
please continue...

just use a prefab, bro
ok fair enough, i never had a problem this way, heck my whole weapon sys is like that haha

normal arch
#

I've decided to make a 2d top down platformer (like CrossCode or Alundra) and i had a basic idea: starting with all the colliders being not where they look, but rather where they would be if they were on the ground, so if there was a house on a hill, the collider of the house would be much lower on the y axis. When the player jumps it only moves the sprite renderer and not the colliders and stuff (similar to the shadow idea before). I'm using layers so when the playerHeight (a variable set in a script named PlayerHeightEntity)gets above a certain value, the player can only interact with colliders also at that height value (objects are dynamically changing layers to affect this). i also had a gravity variable which brought the players sprite renderer back down if the playerHeight was higher than the float currentFloorHeight. And that was it. Does anyone know if this would work well, because this is something that I'd really like in a game, although it might be hard to implement

turbid hazel
#

thanks guys

hard viper
#

gl

#

you don’t want to use Find, like ever, btw

#

anything where you search for a reference by string is a big red flag, unless you are super sure you know what you are doing

turbid hazel
#

but theoretically it should find it right?

hard viper
#

you need to establish really firm rules for a game, and “you don’t actually know where you are” is a terrible premise

normal arch
#

wdym?

hard viper
#

if you are decoupling colliders, I expect the player to have good knowledge of where they actually are, and what the current gamestate is

#

if sprites get totally decoupled from colliders, that is a big red flag

normal arch
hard viper
#

so…. why?

normal arch
#

because the jump isn't supposed to actually move the player up the y axis, it's just supposed to look so

hard viper
#

you mean you have an artificial z axis

#

which is really different

normal arch
#

yeah

hard viper
#

that is done all the time already

#

you probably need to screw with Z, and depth

normal arch
#

how so?

#

btw it would probably be good if you saw what i mean

hard viper
#

a lot of Cast methods for 2D have depth parameters, which I think are for objects of different Z

normal arch
#

i could show a clip of crosscode or alundra if you want

hard viper
#

i think I understand

#

this isn’t too hard to do, afaik

#

on collisions and triggers, you need to check Z as well, and for casts, you need to specify depth

#

I don’t think you need to make an artificial height system

normal arch
#

what are casts btw?

hard viper
#

Cast is when you project a collider by a vector to check collision

normal arch
#

ok

normal arch
hard viper
#

in any scenario, you can just check Z for any collision

#

no. 2D

normal arch
#

or just in code

#

if the z axis isnt the same

#

then yada yada yada

hard viper
#

Example, BoxCast. Look at the last 2 optional parameters

#

it auto filters by Z

#

by default, it does not. But if you use the optional params, it does

#

Most casts are like that, and whenever you check collision, you could check depth

normal arch
#

i still find it a bit confusing

hard viper
#

i don’t understand the confusion

#

there are three ways to check for collision in code

#

you use Cast methods (Raycast, BoxCast, etc), Overlap methods (OverlapBoxAll), and collision callbacks (OnCollisionEnter2D)

#

in all of them, check that what you hit is in a specific range of Z

#

Cast can let you filter automatically

#

Overlap also lets you filter automatically

devout harness
normal arch
#

like how the cast is used

devout harness
#

Ohhh- it's a method you would use for detecting collisions before moving something typically

hard viper
#

you use casts to check collision outside of physics update

#

eg if I need to know if my character is on top of ground right now (this frame), I want to probabably Cast down

#

OnCollisionEnter etc happen after physics update

devout harness
#

It might help to understand casts in general

The most basic form are Raycasts, which you might know from "hitscan" in shooters. Since just a line is a bit restrictive, we have shapes we can cast as well (Boxes, Circles, Spheres, etc).

They're just ways of checking for colliders along a path

hard viper
#

does this make sense?

normal arch
hard viper
#

if I CircleCast from (0,1) by (4,3) with a circle of radius 10, then I am basically checking the area that a circle of radius 10 covers as it moves from (0,1) to (4,3), and reporting back anything I hit along the way

#

casts also return other info like distance until the hit, contact normals, etc

normal arch
#

but how would this change whether two objects collide or not?

hard viper
#

So if my character has a BoxCollider2D, and I want to see if there is ground in the 0.1 units below him, then I will BoxCast a box of his shape by 0.1 units down. And then I will look through the hits to see if there was ground anywhere there

hard viper
#

i think you’d need to check with someone to see how to fuck with the interaction between Z depth and Box2D (unity’s 2D physics engine)

#

do you have dynamic rigidbodies?

normal arch
#

yes

hard viper
#

then you’ll need to do some digging to see if there are settings for Z in the hitbox

normal arch
#

ok

hard viper
#

you’re basically looking for 2D with a Z axis like Link to the Past

#

i would lead with that

normal arch
tall salmon
#

how do i share a script code?

normal arch
normal arch
#
//your code here
#

unless it's too big then you can put it in a paste website and post the link here

tall salmon
#

its to big

#

kewk

somber nacelle
#

!code

tawny elkBOT
tall salmon
#

okey

#

ill explain what im trying to do

#

im trying to do a basic movement set with a dash and a double jump

#

but i run into some issues

#

it normaly has to do with looking left side

#

whenever i dash to the right the dash works just fine but if i try to do it to the left then the speed is lowered to base speed

#

also i need to have a special movement codeline inside the if (GetKeyDown(KeyCode.A))

#

because either way it wont work

#

if someone can help me he would be a life saver

#

been trying to correct the problems for nearly 3 hours

polar marten
#

it means "run the annotated static method when the player starts"

normal arch
#

first you could probs change this

if (horizontal == 1)
        {
            rb2d.velocity = new Vector2(dashingPower * 3, 0f);
        }
        if (horizontal == -1)
            rb2d.velocity = new Vector2(dashingPower * -3, 0f);
        if (horizontal == 0)
        {
            rb2d.velocity = new Vector2(dashingPower * 0, 0f);
        }

to this


            rb2d.velocity = new Vector2(dashingPower * (3 * horizontal), 0f);
#

im just looking at the rest of it

polar marten
#

do you have a screenshot of your game?

somber nacelle
# tall salmon https://hastebin.com/share/buyutikeme.csharp
        if (Input.GetKey(KeyCode.A) )
        {
            horizontal = -1;
            rb2d.velocity = new Vector2(-1 * movementSpeed, rb2d.velocity.y);
           
        }
        else
        {
            horizontal = 0;
        }
        if (Input.GetKey(KeyCode.D))
        {
            horizontal = 1;
        }
        else
        {
            horizontal = 0;
        }

take a look at this bit. what do you think this is doing?

tall salmon
#

i had it like that before but then it didnt dash correctly left side

tall salmon
somber nacelle
#

is it though?

#

if you are holding A, what is the value of horizontal after that code has run?

polar marten
#

you weren't having any issues with JSONUtility, you got null because you probably simply had an ordinary typo. like you probably wrote JSONUtility.FromJSON<ErrorResponse2> when you meant JSONUtility.FromJSON<ErrorResponse1>()

normal arch
tall salmon
#

-1?

somber nacelle
#

look again

tall salmon
normal arch
#

() these things

bronze tide
tall salmon
tall salmon
normal arch
#

these are curly brackets or braces{} these are sqaure brackets[]

somber nacelle
tall salmon
bronze tide
tall salmon
normal arch
somber nacelle
normal arch
#

you can have if, else if then else

polar marten
#

maybe, idk

tall salmon
#

so instead of if it would just be a math equation with the horizontal float choosing its direction

versed pagoda
#

does anyone know if dotween removed SpriteRenderer.DoColor? I had this intro scene i've used for my games but now it suddenly started giving me this error even tho i didn't changed anything

normal arch
#

since you have 2 seperate if statements

tall salmon
#

what does having 2 separate if statements do?

normal arch
#

then if 1 isnt true then horizontal will be 0

tall salmon
#

oh

#

now i see it

#

holy

#

then what can i do to change that?

#

remove 1 of the else?

#

well no

normal arch
#
if (Input.GetKey(KeyCode.A) )
        {
            horizontal = -1;
            rb2d.velocity = new Vector2(-1 * movementSpeed, rb2d.velocity.y);
           
        }
        else
        {
            horizontal = 0;
        }
        if (Input.GetKey(KeyCode.D))
        {
            horizontal = 1;
        }
        else
        {
            horizontal = 0;
        }

change it to this

if (Input.GetKey(KeyCode.A) )
        {
            horizontal = -1;
            rb2d.velocity = new Vector2(-1 * movementSpeed, rb2d.velocity.y);
           
        }
        else if (Input.GetKey(KeyCode.D))
        {
            horizontal = 1;
        }
        else
        {
            horizontal = 0;
        }
tall salmon
#

so then i can also delete the rb2d.velocity = new Vector2(-1 * movementSpeed, rb2d.velocity.y);

#

right?

#

OMG

#

YOU ARE GOD

#

i just saw it

normal arch
#

kk good luck

tall salmon
#

ill tell you how it goes let me check

#

IT WORKS

normal arch
#

nice

tall salmon
#

you made my day

normal arch
#

yw

tall salmon
#

ty!

tall salmon
# normal arch yw

rb2d.velocity = new Vector2(dashingPower * horizontal * 1.7f, 0f);

#

changed that big part to this

#

and now it works

#

well it worked before but now its a cleaner code

normal arch
#

yeah

hard viper
#

i guess I’m confused why Box2D has many functions to deal with depth of Z, but there don’t seem to be any Z-related settings for the physics step

hybrid turtle
#

hi I have written a coroutine for an animation I want and I want to make a script that allows it to run in one direction when a button is clicked and another when anothe button is clicked?

#

does anyone have some intuition on how to do this

leaden ice
#

It could be a vector or even just an int (-1 or 1)

hybrid turtle
#
        {
            offset = offset * direction; 
            float elapsedTime = 0f; 
            var startingPosition = phoneHolder.transform.position; 
            var endingPosition = phoneHolder.transform.position = new Vector3(0, offset, 0);

            while(elapsedTime < duration && buttonOperation)
            {   
                float t = elapsedTime/duration;
                t = animationCurve.Evaluate(t); 
                phoneHolder.transform.position = Vector3.Lerp(startingPosition, endingPosition, t); 
                elapsedTime += Time.deltaTime; 
                yield return null; 
            }
        }
        // correct now how can you do this
        void Start()
        {
            StartCoroutine(TranslateModels(animationDuration));
            flipButton.onClick.AddListener(delegate {
                flipButtonClicked = true; 
                foldButtonClicked = false; 
            }); 
            foldButton.onClick.AddListener(delegate{
                foldButtonClicked = true; 
                flipButtonClicked = false; 
            }); 
        }
#

I have this so far

#

then I tried before to just call StartCorotuine in the delegates with the different directions

#

but then it isn't smooth and happens instantly rather than executing over frames

#

I made this as well and tried another approach where I wait for one of the buttons to be pressed

#
        {
            while (true)
            {
                while(!flipButton && !foldButton)
                {
                    buttonOperation = false; 
                    yield return null; 
                }
                    buttonOperation = true; 
                yield return null; 
            }
        }```
leaden ice
#

This looks busted

#

Did you mean + here?

hybrid turtle
#

yup

#

that may be whats busting it then

leaden ice
#

Almost certainly

hybrid turtle
#

ok that was definitely jank but now when I just start the coroutines they dont even move

#
        {
            offset = offset * direction; 
            float elapsedTime = 0f; 
            var startingPosition = phoneHolder.transform.position; 
            var endingPosition = phoneHolder.transform.position + new Vector3(0, offset, 0);

            while(elapsedTime < duration)
            {   
                float t = elapsedTime/duration;
                t = animationCurve.Evaluate(t); 
                phoneHolder.transform.position = Vector3.Lerp(startingPosition, endingPosition, t); 
                elapsedTime += Time.deltaTime;    
                yield return null; 
            }
        }
    
        void Start()
        {
            flipButton.onClick.AddListener(delegate {
               StartCoroutine(TranslateModels(2f, 1f)); 
            }); 
            foldButton.onClick.AddListener(delegate{
                StartCoroutine(TranslateModels(2f, -1f)); 
            }); 
        }```
#

my suspicion was that if you tried to interrupt it by clicking the other button then it would break because the coroutine would be restart however it not even running is not expected

leaden ice
hybrid turtle
#

1f and -1f as parameters and I made offset serializable

#

unless inspector reset it to zero

#

in that case id have bruh moment

gaunt blade
#

Hey guys if I have a delegate in script A that calls a function from script B that uses a variable in script B, why do I not get a null reference error when I delete script B and call the delegate? Does it remember the last value used?

sharp lotus
#

hey gang, im once again puzzled by how unity rules work. i have this object:
knight_wooden has a mesh collider and an Enemy tag
weak_spot has another mesh collider and an Enemy_Weak_Spot tag

#

like so

#

when i hit the enemy and log the raycast hit tag i always get enemy tag

#

any way to get around this?

#

i want to be able to shoot the knight mesh and do one thing but if i hit the head i do something else, im trying to achieve this by getting the tag of the mesh that the raycast is hitting

rough tartan
#

Hello , I have a weird issue with my script
as you can see when I am shooting on an other player, the game of the other player receive a message to say that he has been hit, when he receive a message he verify the form of the message to see what kind of message it is (if it's a message of the position of a player, if it's damage that receive a player or if it's a player that disconected ) but the problem is that when he receive a damage message, the script see that it's a damage message because it's starting with "(" and ending with "#" but the script sometime analyse the wrong message because as you can see it sometime analyze a coordinate message instead of the demage message so it send me an error. It's like if the script receive message so fast and the computer so slow that when it's see the message it make the verification of what kind of message is it and directly switch to an other message that bypass the verification. Do you know how I can solve this issue ?

steady moat
steady moat
sharp lotus
steady moat
sharp lotus
#

yea, got it

#

thank you! cute

rough tartan
steady moat
rough tartan
green breach
#

anyone have a good way to prompt the user to download a text file with the operating system's native file explorer?
Basically I want players to have the option to save a certain string as a text file wherever they'd like

steady moat
# rough tartan no I don't want because I already try them and it was so hard for me to understa...

My friend, this is the first and worst mistaken that every programmer does. I know it is harder to work with something else, but believe me when I say that you are going to be more productive by using what has already been proven. It would be even more valuable knowing how to use the other framework.

You are still free to do what you want, however note that is way of thinking is in almost every case wrong,

rough tartan
# steady moat My friend, this is the first and worst mistaken that every programmer does. I kn...

of course It would be better to use those framework right now and will permit me to gain a lot of time , but even if my script and my work is not as good and as clean as those framework I feel like maybe later I would need this knowledge on something else than unity. also I know that by using those framework I would give up way early because i won't be patient anought to learn all that stuff while here it's been 3months that I am working on my multiplayer and even if it's not going that fast i'm still motivated because I'm proud of all the achivement I made by myself

steady moat
rough tartan
steady moat
dawn nebula
#

Hey so RaycastHit2D can implicitly be converted to a bool to check if it actually stored a hit. What's the equivalent for the normal RaycastHit?

somber nacelle
#

check its .collider property for null. that's all the implicit cast to bool for RaycastHit2D is doing

dawn nebula
rough tartan
somber nacelle
dawn nebula
somber nacelle
#

and the reason for that is likely because of what i just pointed out

spring creek
dawn nebula
#

Can't define implicit operators outside the class, so an extension method will have to do :/

    public static bool DidHit(this in RaycastHit hitInfo)
    {
        return hitInfo.collider != null;
    }
simple egret
#

Fun fact RaycastHit2D has that

#

But not the 3D version

heady iris
#

that's what prompted this :p

heady iris
#

2D and 3D are ~just~ different enough to configure you from time to time

simple egret
#

Yeah I just arrived lmao

#

Naming for properties in ContactPoint and ContactPoint2D are awfully inconsistent, and confusing when you try to compare the property names between the two types

main coral
#

Hello, is there a way to determine at Unity Gaming Services whether a player is an admin or a normal user?

halcyon isle
#

Hi, can anyone help with issues about sound recording from device? I used MeltySynth to play a soundfont and used NAudio to record it. The issue is that although it can play the sound, it doesn't record the sound it play but the environment sound instead.

somber nebula
#
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Tilemaps;

public class BuildMenu : MonoBehaviour
{
    public bool inBuildMode;

    public Tilemap tilemap;
    public TileBase tileToPlace;

    public Camera mainCamera;
    public AudioSource placeSound;

    void Update()
    {
        if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject() && inBuildMode)
        {
            Vector3 mousePosition = mainCamera.ScreenToWorldPoint(Input.mousePosition);
            Vector3Int cellPosition = tilemap.WorldToCell(mousePosition);

            if (tileToPlace != null)
            {
                tilemap.SetTile(cellPosition, tileToPlace);
                placeSound.Play();
            }
        }
    }
}
``` Script for building with tiles, this works on 1920x1080 but not any other resolution
#

On other resolutions it just places it way away from the cursor, not sure how to fix it

latent latch
#

Is it screentoworld method? Figure out exactly the method giving bad values.

somber nebula
#

the mouseposition variable is just not the same with different resolutions

rigid island
somber nebula
rigid island
#

ohh

somber nebula
#

Sorry, it's orthographic. I have two cameras, I display the orthographic player camera (the one I'm getting the values from for this script) in a render texture

#

the other camera which isn't relevant is perspective, so I got confused for a second

rigid island
somber nebula
#

When I did the print line for the mouseposition variable, the Z value didn't change depending on resolution

#

it was the other ones that did

rigid island
latent latch
#

Thats such an interesting method for 3d for having no depth parameter

#

Oh wait your mouse has depth ah

#

Still what

#

Anyway, a bandaid if you can't figure it out is just use a large collider and specify the space

#

Then use a raycast for the point

heady iris
latent latch
#
point = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));```
Is the example btw
heady iris
#

like, what does it do for ScreenToWorldPoint if the camera isn't literally rendering to the screen?

latent latch
#

Imput.mousePosition doesn't have depth so it draws it directly at the camera I guess?

heady iris
latent latch
#

Ah, ok I see.

heady iris
#

this demonstrates the issue

somber nebula
heady iris
#

perhaps something coincidentally lines up

#

With no target texture, the camera uses the screen size to determine world-to-screen pos. With the render texture, it'll use the render texture's width/height instead. If you then try and use that pos on the screen, there'll be a mismatch.

#

What is the size of the render texture?

somber nebula
#

Ah, 1920x1080

heady iris
#

there you go

#

So what are you trying to do here? Figure out where on the render texture you clicked?

heady iris
#

If you know where the bottom left and top right corners are, you can do it pretty easily

#

if you compute the screen positions of the corners, you could do Mathf.InverseLerp(bottomCorner.x, topCorner.x, inputX) to get a value between 0 and 1

#

0 on the left, 1 on the right

#

I feel like there should be a snappier way to do this, but you are just drawing this render texture onto an arbitrary chunk of your screen

#

you can turn off warnings project-wide with a file called csc.rsp

#

I've kind of struggled to find information about it

#
-nowarn:8524

this turns off warning 8524 entirely, for example

#

If you want to turn off individual instances of warnings, then I think you can add something to the source files

#

I think this is what you want. I actually need to look into this myself more..

#

There's supposed to be a suppress keyword that only turns off the warning for one line

somber nebula
heady iris
#

But I guess it's introduce in a later version of C#

somber nebula
#

100% a better way to go about it probably, I'm just dumb cowboy_sad

heady iris
#

You need to know how large the thing you're displaying the render texture with is

inner yarrow
#

I'm testing around with compute shaders, and I just started getting this error and I can't figure out what's causing it.
CircleTracingVisualization.compute: Kernel at index (0) is invalid
UnityEngine.StackTraceUtility:ExtractStackTrace ()

This is the line it's upset about.
computeShader.Dispatch(0, renderTexture.width / 8, renderTexture.height / 8, 1);
The compute shader only has 1 kernel, and this wasn't previously giving an error. Any ideas?

#

Nevermind, there was a compile error that wasn't showing up in visual studio.

proud juniper
#

Kinda wondering if I have completely the wrong understanding of UI Toolkit paradigms. I'm about to write a script where in Start() I use .Q() to grab a bunch of references and do things like set button callbacks. With the legacy UI system, I would be writing a callback and setting it as the action for a button in the editor. Am I doing this wrong?

#

MainUiDocument.rootVisualElement.Q<Button>("Buildings").clicked += OnBuildingsClicked;

#

There's going to be a lot of this sort of statement with this pattern

slate trellis
#

hello, I am trying to change the value of the sliders to match the values in the StatsHandler script. Sliders get the correct maxValues but not the correct normal values (so far tested with my HP slider as it is my point of focus). I have looked through documentation, forums, QnAs but I seem to find out my approach is correct. The values are correctly assigned, no errors. The script just won't change the values through Slider.value

Here are the most relevant scripts:
https://pastebin.com/8UL1Ssqm (Sliders Script)
https://pastebin.com/XhRWRtsi (StatsHandler script)

#

is this a "this works on my computer" due to a drunk Unity or me done goofed up scenario?

spring creek
slate trellis
#
using UnityEngine;


public class EnemyAssetHandler : MonoBehaviour
{
    private static EnemyAssetHandler _enemyHandler;
    public static EnemyAssetHandler enemyHandler {
        get 
        {
            if (_enemyHandler == null) 
            {
                _enemyHandler = new EnemyAssetHandler();
            }
            return _enemyHandler;
        }
    }
    public bool isDamaged;
}
#

sorry for the paste. Thats the relevant script all it's calculations are handled eslewhere

spring creek
slate trellis
#

changeSliderValue = EnemyAssetHandler.enemyHandler.isDamaged;

spring creek
#

And your update in the Sliders script is behind the condition of changeSliderValue being true

slate trellis
#

change slider value isn't relevant

spring creek
spring creek
#

Don't you want to change the slider value?

slate trellis
#

the sliders don't initiate correctly from the start

spring creek
#

Ohhhh, ok. Gotcha. Ok I misunderstood, sorry

slate trellis
#

The start HP is 1000, and so is max, but it starts with a slider value of 1

spring creek
#

set max value first, then the value

#

I think default max is 1

slate trellis
#

I am so dumb

slate trellis
#

I feel embarassed

spring creek
#

No worries at all!

slate trellis
#

also, thank you for the debug, will take a look if it is really the case

ember hinge
#

Anyone have any issues with RaycastAll sometimes skipping an object?

signal cape
#

i have an object at pos [0,0] i want it to go to a random position at 1 distance from is current position (example : [0.5,0.5] , [0.9,0.1]) how do i do that.

signal cape
lean sail
latent latch
signal cape
latent latch
#

Unless there's a vector3 random range which I forget

signal cape
latent latch
#

Oh, vec2, then random the axis of both with your range.

#

Ah, you want an area of a distance. Then yeah unit circle then

ember hinge
#

Sometimes itll hit when spraying but most of the time it misses some objects.

        RaycastHit[] hitResults = new RaycastHit[resultAmount];
        int hits = Physics.RaycastNonAlloc(ray, hitResults, Mathf.Infinity, shootableLayer, QueryTriggerInteraction.Collide);

        for (int i = 0; i < hits; i++)
        {
            RaycastHit _hit = hitResults[i];

            if(!_hit.collider.isTrigger)
                allHits.Add(_hit);

            Debug.DrawLine(ray.origin, _hit.point, Color.magenta, 5f);
            Debug.Log(_hit.collider);
        }
        allHits = allHits.OrderBy(hit => (hit.point - ray.origin).sqrMagnitude).ToList();```
lean sail
ember hinge
#

its missing the column and hitting the floor behind it, then gizmos are showing start to end

lean sail
#

yes there is no guaranteed order for this

ember hinge
lean sail
ember hinge
#

well i actually had it at 2, for the minigun since it shoots more then one bullet at once, so my apologies

lean sail
#

consider things like if you need it on QueryTriggerInteraction.Collide, since it doesnt really make sense for a trigger to get hit by a bullet. And how many things are on the shootableLayer

lean sail
latent latch
# signal cape oh yea
float angle = Random.Range(0.0f, 360.0f);
float radians = Mathf.Deg2Rad * angle;
float radius = 1;
        
float x = center + radius * Mathf.Cos(radians);
float y = center + radius * Mathf.Sin(radians);```
That should work too
lean sail
#

but it shouldnt be a common case that it goes near the limit

ember hinge
#

thanks !! you helped alot lol i was going crazy.

latent latch
#

that too (probably better point sampling here, right)

cosmic rain
#

How is it that there are more than 10 shootable objects though? I can only see a few at best on that screenshot

ember hinge
#

it was set at 2 not 10, if the gun shot more then 1 bullet at once i set it at 2, i didnt realize lol

cosmic rain
#

Ah, ok.

lean sail
#

yea you'll probably need to change that logic so it still detects everything shootable and then manually choose the closest 2

#

🤔 or possibly a single raycast followed by another after the first hits.. probably bad for massive piercing projectiles

ember hinge
unreal temple
#

Any way to get a stack trace on these?

#

Ah, nvm. Seems to be due to a bad interaction between gizmos and UI. Closing and reopening the game tab solved it.

earnest epoch
#

Hello, everyone! Not strictly a shader issue: I'm trying to think of a way to get a semi-random number from an object's position such that it can vary wildly from another object with a position that's just slightly different. The purpose of this is to seed a vertex shader so that near objects have different starts to their animations, while avoiding instancing. So far, I'm not getting satisfactory results. Does anyone have any ideas?

Edit: I know division is sloppy, but I'm trying to get a result.

latent latch
#

Perhaps instead of the absolute position, divide out the decimals?

lean sail
quartz folio
unreal temple
#

thanks

#

weird that a setting in that menu would change build :-S

night harness
#

Why does that window look so clean and sexy and not the windows xp sterilised white

quartz folio
#

Because 2023 menus use UI Toolkit and are searchable

night harness
#

🌜🌛

#

I see

latent latch
#

for some reason my logging wasn't giving a stack trace in my project either

earnest epoch
earnest epoch
polar jewel
#

Hello, is it possible to make a method listen to two event Actions? So that it will only execute when both actions have been invoked?

cold parrot
#

You can look into async programming patterns to do such things

polar jewel
hoary monolith
#

Hello, I am using Unity Cloud Save to save my Player Data. So I have a Cloud Manager that uses async programming to Initialize and Get Player Data from the Cloud in its Awake() method. But now I have another manager that will get the data from the Cloud Manager, but the thing is the other Manager is already trying to get the Data even when Cloud Manager is not yet done with loading the Player Data. How should I approach this problem? It would also be cool if you can give examples with code

#

both are Singletons btw

lean sail
scarlet viper
#

does Debug.Log get completely stripped from builds?

#

do i have to compile as RELEASE for this

spring basin
#

@scarlet viper if you mean you don't want to display logs then check this out

broken isle
#

i have some code that is supposed to detect it the player is touching the target and display it on the console but it only work when the player is on top of the target and doesnt work if touching the side.

#

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

public class Collidable : MonoBehaviour
{
public ContactFilter2D filter;
private BoxCollider2D boxCollider;
private Collider2D[] hits = new Collider2D[10];

protected virtual void Start()
{
    boxCollider = GetComponent<BoxCollider2D>();
}

protected virtual void Update()
{
    //collision
    boxCollider.Overlap(filter, hits);
    for (int i = 0; i < hits.Length; i++)
    {
        if (hits[i] == null)
            continue;

        OnCollide(hits[i]);
        //clean up array
        hits[i] = null;
    }
}

protected virtual void OnCollide(Collider2D coll)
{
    Debug.Log(coll.name);
}

}

cosmic rain
#

Why not use OnCollisionEnter anyways?

harsh root
#

Could someone help me with an editor problem?

So I got rooms. KoboldRoom, KoboldLootRoom, KoboldBossRoom all inheriting from RoomType So I can call the same methods but with diffrent changes to the method
now I save an array off RoomType
and what I want is that when you add a new value to that array it gives you the option of all the existing RoomTypes
And when selecting the roomtype you want it will then show the properties of that roomtype

harsh root
#

Thanks that helps alot

drifting bear
#

hey all, I do have a simple question. It's more like a math question really. so:
I do have a Stat which has flat and percent modifiers. im confused of order to get the modified value.
modifiedValue = (baseValue + flatModifiers) * percentModifiers;

or
modifiedValue = (baseValue * percentModifiers) + flatModifiers;

which will result in different stat values. what is the general way in this?
or would it result in different results, fck now I wrote it down, im more confused.
so let's say base is 100 and I have +15 flat modifier on top of that i have %10 increase.
in first formula it'd result in ~126 rounded down.
second one would be 125.

cosmic rain
#

It depends on which one you want to have. In the first case the flat mod is affected by percent mod. In the second it doesn't.🤷‍♂️

drifting bear
#

since it's flat, I think it makes more sense that it doesnt I guess.

latent latch
#

usually games have flat modifiers apply first

#

at least good games ;)

#

so I'm more of a fan of the top calculation

drifting bear
#

interesting point.

mellow sigil
#

It depends on what those modifiers are and how they're communicated to the player. If the player picks up a bonus effect that does +15 damage, they might wonder why it does +16 damage instead. But if a character has a trait that gives them 10% damage boost, players probably expect it to appy to flat modifiers as well

somber tapir
#

You definitely want flat first, than percent. Let's say you have 100 base and 900 flat bonus, your player deals 1000 damage and picks up 10% damage increase, he would except to deal 10% more damage( 1100 damage), but with the first calculation it would only be 1% (1010)

latent latch
#

Can always add like a true flat modifier that wouldn't be increased by other modifiers, because there could be items or abilities that have a gimmick of just adding a large flat amount of damage.

cosmic rain
#

It really depends on the formula and it's intent. Some games have complex formulas that include both a flat bonus before multiplier and a flat bonus after.

drifting bear
#

good points. @mellow sigil I didnt like getting 126 after +15 flat and %10 increase either. maybe I should communicate like percents only adds to base in UI? stats are important because there would be items, status effects etc.

#

@cosmic rain could you give an example by numbers?

heady iris
#

Whatever you do, just make sure it's consistent

drifting bear
#

i need to load up some rpg games and equip items that do both I guess.

#

intent is to show player both base and total modifiers (but not types.)

#

item or status effects abilities etc would show percents or flats separately

cosmic rain
drifting bear
#

maybe I should separate what stats can get percents then. because it doesnt really fit my design. for example, 'Speed' stat determines turn order which I'd never modify it by percent. But health or damage may be modified by percent.

#

in that first formula would work better since you get more health or damage (which what player wants anyway.)

#

darkest dungeon does just that, now i've seen modding files.

mighty wing
#

Right now I have it so that it will animate OpenDoor() of a specific GameObject.

[SerializeField] private GameObject bossDoor;
private void Update()
{
    Door door = bossDoor.GetComponent<Door>();
    door.OpenDoor();
}

Is it possible to make it so that I have a list of GameObjects I animate?

[SerializeField] private List<GameObject> bossDoor;
last island
#

Ah, this is super frustrating. I have a sequence that animates when my client opens in Unity. It uses a Unity Animator component to do that.
If I take focus away from the game window while the animation is running and then click back to the game window, the animation clip starts over instead of it keep on going.
How do I help this? I read that you could turn on "Apply Root Motion" on the animator component to fix it, but that didn't change anything.

heady iris
#

I would not expect toggling root motion to have any effect.

last island
#

I don't really know much about the animators inner workings.

#

But I am really running out of ideas on how to help this

heady iris
#

How do you trigger the animation?

#

"when my client opens" is a little ambiguous

#

like, when the game starts?

last island
#

When the client starts up, it sets a trigger on an animator and then enables it.
The trigger is evaluated to run the animation and then it starts going.

heady iris
#

Does this problem happen in the editor, or only in a built game?

last island
#

Editor.

#

In the game I think it works as expected.

heady iris
#

Can you show us the script that sets the trigger?

last island
#

But I need to debug things as I go, and I can't because the animator keeps resetting the last run clip or state

heady iris
#

Oh, I see what you're talking about

#

If you do anything that changes how the animator controller works, the animator gets reset

#

That's my understanding, at least.

last island
#

I can't show everything as it's a commercial project

#

This runs when the client starts up

#

It will transition into the BackgroundAnim state as expected

#

And then if I take focus away from the Game window and refocus the Game Window

#

That animation clip will just start over

#

And this isn't unique behaviour to that clip

#

This is a problem, because I have an editor tool that I need to give focus at times to write some things in and press some buttons

#

And when I give focus back to the Game window, it just reruns whatever animation was last run.

#

Which means there is state I can't actually work with...because the animation resets that state 😅

#

Any ideas?

heady iris
#

I remember seeing this kind of thing when working on my VRChat avatar -- I'm pretty sure hitting undo or redo would always make my animator reset

#

It looks like the default state should be "Holding State", though.

#

Is the transition into BackgroundAnim getting taken?

last island
#

It transitions to the state as I'd expect.

heady iris
#

keep the animator window open while you're doing this (with the parameter list visible, too)

heady iris
last island
#

I have done that. I can make a gif and show you.

heady iris
#

So the problem is that it keeps re-entering the BackgroundAnim state, correct?

last island
#

Here you see what happens to the Anim state as I take away focus and give it back to the Game Window

#

Every time the focus is given back, the anim resets.

heady iris
#

Ah, okay, so it's not what I was expecting -- it's not going through Holding State at all

last island
#

Nope.

#

As soon as it's in there...it just keeps being there.

heady iris
#

Does it happen with every animator?

last island
#

Yep.

#

I can trigger it consistently.

heady iris
#

you can see if the state is being entered, or if the time is just getting reset to 0

#

If the state is being entered, you could get a stack trace by logging something

#

Which might tell you whose fault this is

last island
#

Thing is, I already know it's Unity.
No scripts are being used to do what this Anim does.

#

I can tell that the entire state of the Animator resets, in fact.

last island
#

That flag doesn't exist.

heady iris
#

It was introduced around unity 2021

steady moat
#

What version are you on ?

last island
#

I am using Unity 2021.3

heady iris
#

oh, you were looking at the second property.

steady moat
#

2021.3 should have the flag

heady iris
#

but it's also present in 2021.3 .

steady moat
static matrix
#

missing using statement? I doubt it, but might as well check

heady iris
#

I was surprised that you weren't winding up in the default state. But I'm not too familiar with the gory details of the animator.

steady moat
static matrix
#

ah, fair

somber nacelle
static matrix
#

me?
or wrong reply

#

we are trying to help Mads

steady moat
#

If it is the case, being on an old patch, you might want to update it.

somber nacelle
last island
#

I don't know what part of this is working.

public class AnimatorTest : MonoBehaviour
{
    public void Awake()
    {
        GetComponent<Animator>().keepAnimatorControllerStateOnDisable = true;
    }

    public void OnDisable()
    {
        GetComponent<Animator>().WriteDefaultValues();
    }
}
#

But it seems like it does work

heady iris
#

I never knew about those settings. Sounds useful.

heady iris
last island
#

All I know is that the Animator is kind of archaic compared to most of the other unity systems

#

And that programmatically it's not fun to deal with

steady moat
#

They are working on a new "Animator" as far as I know

#

Because, you know, you want a 3rd system.

last island
#

I've used Animancer some and it's really nice

#

You make your animations into reusable data

#

And can just apply it to anything that can animate

#

No more "recreating the exact same state machine across multiple things"

#

Just use the same animation dataset

static matrix
#

would that work for sprites?

heady iris
#

It also prompted me to start using more state machines

last island
#

As long as you can express the animation as self-contained data, then I don't see why not

#

I seem to have found most of what I'd be looking for. There is a weird quirk going on with an animator I'm not quite sure why, but I can probably figure it out. There are still some animators that, despite the script, still reset when I refocus the game window.
Thanks so far @heady iris @steady moat

heady iris
static matrix
#

ah

heady iris
#

It just plays animation clips at the end of the day.

static matrix
#

oh

heady iris
#

It's fantastic. I'm working on a Soulslike game right now.

last island
#

It has much nicer programmatical access to the animator though

heady iris
#

Each weapon has a moveset. That moveset contains animancer clips.

#

I can play the clips from the weapon on the player and it just ~works~

#

Animancer also has fantastic documentation with both worked examples and plain reference material.

last island
#

Also another wild Unity Moment™️

#

I have an Animator graph where no state is visible.

#

At all

#

You can't even delete the Any State, but yet the animator graph is vacant

heady iris
#

maybe it's just scrolled way off? hitting A will focus the view

last island
#

Nope.

#

All gone

#

But I restarted the Animator window and they reappeared.

#

If you press Ctrl + A while in the Animator window it will focus the states you have within the screen space given

heady iris
#

I found that a bunch of different keys wound up doing that

#

A, F

steady moat
#

Sometimes, the Animator is corrupted

static matrix
#

this is fine

normal arch
#

if two trigger colliders touch does it call on triggerenter 2d?

static matrix
#

I believe so

last island
#

Only if there is at least 1 rigidbody present

static matrix
#

what? really?

last island
#

Trigger to Trigger was removed many versions ago

#

It's too cumbersome to check for

static matrix
#

huh

normal arch
#

also im getting an error in visual studio saying The type or namespace name 'PlayerHeightEntity' could not be found (are you missing a using directive or an assembly reference?). the error isn't appearing in unity so its probs just vsc acting up

last island
#

Try and rebuild in VS

static matrix
#

well
did you define playerheightentity?

normal arch
#

yes

#

its a type

#

it works in other scripts

normal arch
last island
#

Build->Rebuild

normal arch
#

i think i meant to say visual studio code

#

i can't see that setting

heady iris
heady iris
#

it needs to see the new file so that it can update your .csproj files

normal arch
#

ok the error's gone now

#

i just closed the file and reopened from unity

#

it was vsc being weird

#

also about this, i put a rigidbody on one of the objects with a triggercollider but the code doesn't seem to be being reached

#
public void OnTriggerEnter2D(Collider2D other)
    {
        if(other.CompareTag("Platform Checker"))
        {
            Debug.Log("platform checked");
            GetComponentInChildren<PlatformChecker>().onPlatform = true;
        }
  }
#

thats the code

#

not getting reached even though i have something with that tag

prime sinew
#

there's a link for troubleshooting physics messages

normal arch
#

k ty

polar jewel
#

Hello, is there any way I can visualize the FoV of the Camera in Unity? In a multiplayer VR setting, I want to make my FoV visible to other users.

normal arch
#

but now im getting a null reference exception error at this line

GetComponent<PlatformChecker>().onPlatform = true;

even though the only thing with that tag definitely does have a PlatformChecker component on it

somber tapir
simple egret
normal arch
#

yeah im dumb

#

ill try but im doing somthing rn

slate trellis
#

I have a problem with unity... I have my main editior set as VSCode (or so I want). Whenever I open unity, it preselects the editor code.cmd (internal), which is NOT my VS Code. My VS Code editor in the External Script Editor value is Visual Studio Code [1.81.3]. This causes a handful of issues as the "code.cmd" version does not open the project folder, but just the script, resulting in no autocompletio, debugging, or changing my working script from the editor. Example photos:

#

Any help appreciated

hard viper
#

I finally have the first prototype for my new physics engine. >1000 lines of complex code with zero testing. Can’t wait to watch it blow up

slate trellis
#

nvm fixed it after weeks of troubleshooting. Always when you ask for help, the problem magically disappears. Sorry for the trouble

cursive basin
#

Whenever I utilize Application.focusChanged it appears to not register the first focusChanged event.
i.e. I can subscribe to the event, then I would have to unfocus unity and refocus it before it starts reporting the proper focus state.
Is this a "yeah, it has always been like that; work around it" or am I missing something here?

polar marten
#

also, in the editor, focus is complicated

cursive basin
#

Then it starts reporting true/false for every focus change

polar marten
#

i think you should try printing the focus state, wherever it is, before you subscribe

#

so that you can understand what the editor focus state is

#

at least what it's saying it is

#

the player has different behavior than the editor for focus state

#

imo you should not build functionality around focus state

#

really depends on the game. the best thing to do is watch for inputs and if it's been idle for a short period of time, you are unfocused.

cursive basin
#

That's not relevant to the question though. You subscribe to an event then you expect it to fire on changes; not just from the second or third change and on.

#

I agree that you don't make a game based on focus status, but that's besides the point.

heady iris
#

so you're saying the following sequence happens

#
  • subscribe
  • unfocus (no event raised)
  • focus (no event raised)
  • unfocus (event raised)
  • focus (event raised)
#

Is this correct?

cursive basin
#

That's exactly it

#

It might be off by one, but that first unfocus doesn't fire

polar marten
#

like i said you have to print the state

#

before you subscribe

#

so that your mental model of what's going on in the editor matches reality

#

the game may appear to be focused but it's not

#

or vice versa

cursive basin
#

Does it technically change anything or is it just for me to peruse?

polar marten
#

i can't help you if you can't write a debug statement

#

i'm just repeating myself. the editor focus state is complicated. print it before you subscribe

cursive basin
#

I'm subscribing runtime, but you have me intrigued. What's the complicated part?
Not taking the piss btw, I just want to know the quirks

cursive basin
#

Alright, thanks for chiming in. I'll have a look at it

heady iris
cursive basin
#

Client has focus.
Subscribe.
Let it unfocus. No event fires.

heady iris
#

That doesn't answer my question.

#

Do you get an event when you re-focus the application after doing that?

cursive basin
#

That'd be my "off by one" I need to doublecheck.
The first unfocus after subscribing definitely doesn't fire though.

heady iris
#

If the event fires correctly on the first re-focus, that implies the application started out in an unfocused state

#
  • subscribe
  • unfocus (no event raised)
  • focus (event raised)
  • unfocus (event raised)
  • focus (event raised)
cursive basin
#

The weird thing is that I'm subscribing from within the client.
It definitely has focus, per definition.

#

As in, on the windows taskbar the client is highligted as active. And I'm clicking a GUI button.

rocky helm
#

Is there a TransformPoint for rigidbodies? I am currently changing rigidbody positions in fixed update and also need to use TransformPoint at the same time, but
transform.position != rigidbody.position
right after doing rigidbody.position = ...

heady iris
#

Not that I'm aware of. The rigidbody doesn't have its own transform

rocky helm
#

Is there anywhere where I could get the TransformPoint code and re-implement it for the rigidbody?

heady iris
#

I am thinking you could get the Matrix4x4 from the Transform, then modify it to account for the change in position

rocky helm
# heady iris I am thinking you could get the `Matrix4x4` from the Transform, then modify it t...
heady iris
#

You could then just multiply it with your point

#

alternatively, tbh

#

set the transform's position

#

do the math

#

put it back

#

you could also just create an empty object that you parent to yourself, and then set its position to the destination

#

you could do that once in Start and then keep it around

#

I've done something like that before.

static matrix
#

can I serialize an entire gameobject into JSON? and If I can should I because that seems like a very inefficient way to readwrite data to a server and such

static matrix
#

but Json will be faster than using a text file and telling the script to read a specific line I presume

#

not for the entire object of course, but just for some values

knotty sun
#

Json is text plus so probably not. But if you are sending data to a server it should really be in binary

static matrix
#

hmmm
I would think it would be faster
more modular at least

knotty sun
#

why, more bytes == slower speeds

heady iris
#

you're conflating two things

static matrix
#

lets presume im doing the reading in a really, really, tremendously poor way
it'd probably be faster then
(I:E, I only read it once with the Json)

heady iris
#

binary vs. text formats

#

and whether or not the format includes the field names

heady iris
#

or if it's just a big blob of data that you must know a schema for to decode

#

imagine sending a Vector3 as three named floats, versus just packing the three floats into a 12 byte chunk and sending that

static matrix
#

can the CS read and interpret bytes?

knotty sun
#

even csv is going to be faster than json

knotty sun
#

how do you think we write binary serializers?

static matrix
#

fair

#

oh well
ig I'll keep using this method then
and figure something else if it turns out the client runs at tremendously slow speeds

#

on a side note, if I wanted to store a database of some sorts, should I also not use Json for that?

heady iris
#

if this is just a few lists of serializable objects, that sounds fine to me

knotty sun
#

no, definitely not

heady iris
#

but if you really mean a database

#

then json is inappropriate, and you will need to use something like SQLite

static matrix
#

I though SQL was a service not a format

static matrix
#

well technically this sidenote is outside of unity

#

but I just thought I'd ask here because it was topical

knotty sun
#

yep but I bet you want to store things like Vector3's

static matrix
#

I mean it was just going to be strings and ints

#

a small database

#

im not sure how many
but it would probably be ballpark 50-100 strings

knotty sun
#

very small, flat file is easier than database

#

look at csv format

static matrix
#

oh
ig commas are faster than linebreaks then?
or something?

knotty sun
#

commas are faster than parsing field names and in a fixed format commas are all you need

static matrix
#

so why would you ever use JSON then

knotty sun
#

no idea, I dont

#

mainly, I guess, because people just don't know better

static matrix
#

so then one json file is probably also slower than having a different file for each object?

knotty sun
#

most definitely

static matrix
#

cool

rigid island
#

SQL is soo yesterday 😆

knotty sun
fervent furnace
#

json is high level readable language for human and can be used by reflection
but if you want compress and fast way to readwrite then you have to design your own syntax and parser

rigid island
knotty sun
lean sail
rigid island
static matrix
#

I was just thinking that doing more readwrites every frame on text would be slower than doing less readwrites every frame on Json

lean sail
#

You wouldnt be writing to file every frame for anything

static matrix
#

but what if i am

fervent furnace
#

file io will be queued by your OS iirc

lean sail
static matrix
#

fair

fervent furnace
#

if you want to do IO intensive job, off load it from main thread if possible or use buffer temporarily stores the data that is needed to write to disk

lean sail
#

The only real downside to json or plaintext is that the user can fairly easily edit it. If its in something else like binary or a database, its ever so slightly harder to edit that the average person probably wouldnt try editing it

rigid island
#

caching can help with tons of reads

static matrix
#

this may result in some very silly situations where whilst playing this game I go into the database and edit the position of my opponent
but eh
no one is going to play this anywyas

#

any lag may also be from the fact that my school wifi might not like me trying to host a local go server on it 💀

rigid island
static matrix
#

yeah lol

lean sail
static matrix
#

yeah
well it would be multiplayer but like its not going to have an immense playerbase or whatever
I could always have a thing to check if they were edited and then give me the ip or client or whathaveyou

modern creek
#

Is there a way to search in the hierarchy for active objects?

static matrix
#

probably?

rigid island
static matrix
#

I think you could do like isActive:true or smth

rigid island
#

obs you gotta login the user first

main coral
#

thanks!

gray mural
#

I have a list of classes that is serialized in the inspector.

public List<EnumOption> enumOptions = new();

[Serializable]
public class EnumOption
{
    public string name;
    public List<OptionData> options;
            
    public EnumOption(string name, List<OptionData> options)
    {
        this.name = name;
        this.options = options;
    }
}

When I click on the GUI Button in the inspector, one of the things that it does is removing some options from the TMP_Dropdown options.
So it removes previous options to find another, even if they might be the same.
The issue is that it removes them perfectly unless positions of items were changed in the Inspector. For example, when 0 and 1st items were replaced. This way it cannot remove them anymore, because it probably doesn't find the reference? But why?

foreach (OptionData optionData in options)
    dropdown.options.Remove(optionData);
main coral
#

I have implemented Unity Auth System with Username and Password. What is the best way to save the username in the unity dashboard ?

static matrix
#

what is order in layer but from the script?

#

like whats the script name for it

#

spritesortpoint

#

ok

rigid island
main coral
#

But where is it saved ? Cloud Save ?

static matrix
#

no that wasn't it either

#

huh

main coral
#

Or is it possible to save it in the Player details overview ?

static matrix
#

found it, sortingOrder

rigid island
main coral
#

How do I save it ?

rigid island
main coral
#

public string PlayerName() { return AuthenticationService.Instance.PlayerInfo.Username.ToString(); }

#

This is stored in the PlayerInfo but I dont see it in the Dashboard

rigid island
#

well you can't change the dashboard , and idk what priority Unity has for that.
sadly, the only solution at the moment is to use your own dashboard of sort

main coral
#

OK, so when I want have it in the Dashboard I have to save it as Cloud Save or ?

rigid island
#

the best you can do it is storing it as a file / string value inside Cloud save yeah , its a pain in the ass to do it like that too

#

not sure why Unity half assed this one

#

its a fairly easy thing to implement

#

best we can do is keep submitting feature requests

#

if they're gonna give us user accounts, they should at least give us something decent not half assed

main coral
#

Actually, I don't need it in the dashboard at the moment. I'll leave it as it is. But thanks for your help.

#

There is also no email verification. How did you do that ?

rigid island
#

wanna gues?

#

ya can't...yet..

main coral
#

Not at all?

#

How should people change passwords?

rigid island
#

honestly. its crazy..
Lootlocker has that... even
mongodb has that

rigid island
main coral
#

xD

main coral
#

So everyone can change password for everyone ?

#

Or do u have to Sign In to change password ?

rigid island
#

the user must be signed in and you must request the user to enter their current password and new password, then call UpdatePasswordAsync. UpdatePasswordAsync keeps the user's authentication status, but all other signed in devices asks the user to sign back in.

#

its not a password reset feature

#

just changing current pass

main coral
#

ah ok

#

So if the player loose his password the account is gone ?

rigid island
#

hmm good question , I haven't seen anything about that

#

it does says User Accounts is Beta so lets hope it get fleshed out soon...

#

this is more like an Alpha stage

#

I think the idea rn is that mostly you'd want to use proper login/pass systems like Google n such

#

so if you need recovery account you're dealing with google and not unity

main coral
#

yes

#

I have it done with google

#

But I try to work only with Unity Services

#

but its kinda hard

rigid island
# main coral but its kinda hard

agreed. again maybe keep sending feature requests and hope they see interest in it.
its a competitive I assume given the many already established systems like Google or Playfab n such

#

but it does tie in already with Unity perfectly so they have a major potential , hopefully not wasted.

#

also Unity Player Accounts is under MIT license which is nice

#

Code-Link was a nice feature they added though to Auth

main coral
#

@rigid island Do u know is there a way to sign people as admin ?

rigid island
main coral
#

Im using ingame Console. And I want that only people who are admin can acess it

#

what is an easy way ?

spring creek
normal arch
#

hey guys im trying to make stairs that raise the players sprite renderer by a value depending on where they are on the stair but im struggling to figure out the math, can anyone help?

normal arch
#

yes

somber tapir
#

You can add levels to your tilemap by using the Z coordinate, so things appear behind/infront of the player, if that is your problem

normal arch
#

i have a whole fake height system made so im just trying to make it so that if the players is at a certain distance along the platform, the height level is raised by a certain amount based on the steepness of the platform

#

so if a player was halfway up some stairs, their y value would be increased by 0.5 if the steepness was 1

#

but if the the steepness was 2, and the player was halfway up some stairs, the players y value would be increased by 1

#

dont know how i would do that though, thats basically all im asking

#

the thing im having trouble with is detecting where the player is along the stairs

main coral
#

@spring creek Thx

slim flint
#

Does anyone know how the force of the SpringJoint2D is calculated ? I know there is a built in method to get the force but I need to know the math behind it so that I can apply a constant force by changing the frequency depending on the objects mass and distance

broken isle
#

im following a tutorial to make 2d game but my hitboxes arent really working, when i stand on top of the target they work fine but other angle this is the closes i can get.
here is the link to my player code:https://hatebin.com/qlfnapwboh

#

um using the unity spirte editor and i dont know if theres somthing to do with hitboxs in there

#

Here are my box collider settings:

somber nacelle
#

your objects are incredibly small so you are seeing the normal contact offset

#

you need to change the Pixels Per Unit setting on your sprites so that they are correctly sized

broken isle
#

when i click on a spite to change the ppu there are no setting am i clicking the wrong thing?

somber nacelle
#

select the sprite sheet, not the individual sprites

#

since it is one texture sliced into multiple sprites the import settings will be on the texture

broken isle
#

ah tysm it all works now but my player is very slow now, should i try to change my code or is there something else i should do

#

i found anther solution

#

i reverted back to my old settings and added an edge radius

#

not realy shure what it does but i think it acts as a trigger

turbid hazel
#

hey 👋🏽
why would this only fire for the player but not for the npcs?
It can't find the Manager. collider.GetComponent<EntityManager>()
The collider is fine, i handle damage this way all the time. It's on the same gameobject like the Manager.

spring creek
#

Is it both? Only the player? Not sure

turbid hazel
#

the script you see is attached to this gameobject:

leaden ice
turbid hazel
#

but my player gameobject has none

#

oh you mean on the handler

leaden ice
#

If the code is running then one of the objects has one

#

Either one

turbid hazel
leaden ice
#

I mean idk what to say

#

Rigidbody is a requirement

#

It's in the docs

turbid hazel
#

oh most likely it counts the character controller as rigidbody right?

leaden ice
turbid hazel
spring creek
#

But NOT OnCollision

#

Which is replaced with the OnCharacterControllerHit or whatever it's called instead

turbid hazel
#

thanks for clarification, always good here

leaden ice
#

But good to know

#

Can't believe how poorly documented that stuff is

spring creek
leaden ice
#

Well TIL

turbid hazel
spring creek
turbid hazel
#

Your comment implies that OnTrigger only works with character controller? Sorry english is not my native language.

spring creek
#

Oh. Sorry about that. No, I did not mean that

turbid hazel
#

got ya 😄

spring creek
#

It normally works with a Rigidbody. But it CAN work with a CharacterController as well

#

The former is well known, the latter was a surprise to me

latent latch
#

Oh yeah I came upon that at a point and was scratching my head

vague tundra
#

Hey guys, I just updated from Visual Studio 2019 to Visual Studio 2022.
The autocomplete for Unity methods like Awake, Start and Update is not working. Any ideas?
(I have the Game dev with Unity Visual Studio package installed)

tawny elkBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

rigid island
#

go over the steps again

vague tundra
#

Thanks, just did. No luck

rigid island
rotund burrow
#

i'm making an inventory system. I have a basic store - equip scripts that work for player and npcs. Now I need the following:

The items process inputs and display huds differently based on type and whether it is equipped by player or enemy.
For example, a pistol equipped by player shoots on button down, but a charged gun shoots after a while on button up. Ammo count is displayed on screen.
Then for enemy, some ai gives similar instructions and item understands what to do. Ammo count is displayed on top of the enemy in the world.
any advice on this?

latent latch
#

If you have the types how you want it, I'd assume you'd just want to check the type of the item and what entity is using it when equipping.

#

and then change the hud accordingly

proven path
#

I think the the cleanest way to achieve that would be to separate the code for input and the code for the weapons themself. In that way the weapon should only contain information about how the weapon functions, like ammo count, projectile type, cooldown and such stuff, but not about input related information like on which button press it shoots. Then the ai and the player can get different scripts which manage the weapons. For the input of the player you may want to write a general controller class which handles every weapon with the help of a third info class which contains stuff like if the weapon is automatic or semi-automatic or if the weapon shoot on button up or down; or you might use a different player controller class for every weapon.

#

It just would get more tricky with stuff like the charge time, because that would also affect animation of the weapon and in that way should be both present in the weapon for the ai and for the player, so maybe these properties should only be contained in the weapon. Then you might also need different ai controller scripts for different types of weapons.

rotund burrow
#

so enemy equips item, controller class instance is created, ai input related info is passed there, then the controller class calls methods from item class. something like that?

proven path
rotund burrow
#

okay thanks i'll go try to make this

proven path
latent latch
#

Lot could just be stored in the weapon specific SOs. I'd make the firing type the key, and then create a dictionary that maps that key to the specific hud asset for the entity.

#
Dictionary<FiringType, HudAsset> weaponHudDict;

public EquipWeapon(Weapon weapon)
{
  EquipWeaponHud(weaponHudDict[weapon.weaponSO.FiringType]);
}```
ebon wing
#

could anyone help me please ive been stuck for like 30 mins and i dont understand how this isnt correct:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using System;
using Unity.VisualScripting;
using UnityEditor;

public class MushroomManager : MonoBehaviour
{
    public GameObject mush1;
    public GameObject mush2;
    public GameObject mush3;
    public Timer timeScript;
    [SerializeField] public AnimationCurve timeCurve;

    double[] timesArray = new double[18];
    int decayed1 = 0; //mushroom1 (top mushroom) decayed = 0 on start
    public void Start()
    {
        mush1.GetComponent<Animator>().Play("No Decay");
        mush2.GetComponent<Animator>().Play("No Decay");
        mush3.GetComponent<Animator>().Play("No Decay"); //sets all 3 mushrooms to no decay state
        
        double timeCurvePos = timeCurve.Evaluate(0);

        for (int i = 0; i < 18; i ++) // for (numbers 1 to 18)
        {
            timesArray[i] = timeCurve.Evaluate(i * 10);   //timesarray(number) = timecurve.value at number X 10 for example 6 might be 11.4588 seconds 
        }
    }
    public void Update()
    {
        double currentTime = timeScript.currentTime; //currentime = time in double game has been active
        float roundedCurrentTime = (float)Math.Round(currentTime); //currentime = time in float game has been active

        foreach (double timeArrayValue in timesArray)  //for each point (every 10 on x axis) 
        {
            float roundedTimeArrayValue = (float)Math.Round(timeArrayValue);
            if (roundedCurrentTime == roundedTimeArrayValue)
            {
                
                decayed1++;
                break;
            }
        }

        if (decayed1 == 1)
        {
            mush1.GetComponent<Animator>().Play("Slight Decay");
            Debug.Log("mushroom infected");
        }
        if (decayed1 == 2)
        {
            mush1.GetComponent<Animator>().Play("Slight Decay");
        }
        if (decayed1 == 3)
        {
            mush1.GetComponent<Animator>().Play("Slight Decay");
        }


    }
}
#

also im just ignoring mush2/3 for now as i can add those in once mush 1 works

hexed pecan
ebon wing
#

i can show animation curve too if u want

lean sail
#

What's going on in that bottom section, your if statements all seemingly doing the same thing

ebon wing
#

and ik it is the first as the Debug.Log appears

lean sail
# ebon wing and ik it is the first as the Debug.Log appears

Add more debugs then to see why your mush1 is decaying before you think it should. You should step through with the debugger because itll show you all values while you go through line by line. I have absolutely no clue what you are doing with that time array thing (and dont have the time to try deciphering it). I will just say, a lot of this is hardcode and doesnt make sense why it's being done like this

ebon wing
lean sail
ebon wing
lean sail
#

atwhatcost I guarantee you're gonna be having worse issues in the future if you continue with your current structure

vague tundra
ebon wing
lean sail
quasi radish
#

I'm not sure where the problem is?

simple egret
#

!vscode

tawny elkBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

simple egret
#

(this step is required to get help here)

quasi radish
#

I have configured it

#

It completes code for me but doesn't highlight anything red

fervent furnace
#

you vscode is not configured

simple egret
#

You'll have to restart VSC or even your computer for all the changes to apply

quasi radish
#

I had the extension installed long ago

simple egret
#

Configuring it installs the .NET SDK on your computer, which needs at least a reboot to take effect

#

Ensure the SDK is there by running dotnet --list-sdks in a command prompt

quasi radish
#

yes it is installed

simple egret
#

Have you installed the Visual studio Editor package in Unity?
Have you set VSC as Unity's external code editor?

quasi radish
#

I did but uh for some reason now it wasn't

#

Thank you

simple egret
#

It installs the required packages on Unity's side, so Unity can generate a valid project file VSC will be able to read

quasi radish
#

this part of the code is slightly transparent which is giving me errors

simple egret
#

No, the errors will be underlined red

#

These are slightly transparent because they're not used at the moment

#

You're not using anything from System.Collections right now, down below in your code

quasi radish
simple egret
#

Not right now, Entity is probably from your own project

#

It's not in any namespace

quasi radish
#

Oh right I'm stupid I haven't made the entiy class yet

#

and the other problems?

simple egret
#

The ones underlined blue seems like it's your spell checker going off

#

These are not errors, your project will still be able to compile

quasi radish
#

Can somebody help me fix this error?

somber tapir
quasi radish
quartz folio
#

And do you know how camera.main works?

quasi radish
#

No

quartz folio
#

!docs

tawny elkBOT
normal arch
#

does anyone know if you can detect how far a player is along a collider?

rocky helm
limpid oyster
#

hey, i've been looking into how would i make a controller work with my game, now i could use either the old input system (i seriously do not want to, since it has not enough features i need) the new input system (it's overly complicated) or which i do want to use is, since i already have my own input system made, which works basically the same way as unity's old input system, but it doesn't support controllers, is there like a very bare bones something like GetKeyDown() but for controller keys and axes? or maybe i should just use some api's with C# wrappers?

hard viper
#

i would recommend learning new input system tbh

#

new input system is confusing, but it does have all the main features to detect different types of key presses etc and subscribe to them

normal arch
#

i asked chatgpt and it said use a raycast (i decided to use a boxcast instead because a raycast might miss the player)

rocky helm
#

oh

#

so like ona scale from 0-1?

normal arch
#

yeah

rocky helm
#

playerHeight/maxHeight where player height is from 0 to maxHeight

normal arch
#

i dont think thats what i want

rocky helm
normal arch
#

well i have a variable that changes which axis it checks on

rocky helm
#

Okay, so lets say it is on the y axis for now

normal arch
#

yeah

#

so say the collider's center is at 0, 0 and the player's collider's center is at 0, 1 and the colliders size is 10, it should return 0.6

#

thats what i want

rocky helm
#
float bottomBound = colliderObject.position.y - colliderBounds.y/2; //Gets the bottom most y-level of the collider (given that the position is at the middle of the collider)
float upperBound = colliderObject.position.y + colliderBounds.y/2;
if(playerPos.y < bottomBound) value = 0; //The player is below the collider
else if(playerPos.y > upperBound) value = 1; //The player is above the collider
else //The player is on the collider
{
  float value = (playerPos.y-bottomBound)/colliderBounds.y; //Gets how far up the player is on the collider and puts it onto a scale from 0-1 by dividing it by the maximum
}
normal arch
#

btw i should probably say that this is in 2d

rocky helm
normal arch
#

ill try it out ty

lyric atlas
#

If I have a manager script in a hierarchy and I want child gameobjects with their own scripts to listen to certain events from it, what's a good way of referencing the manager in the children's scripts?

It's not a singleton, I know I can just have a public reference in each childs script and manually set them each, or I can search up the hierarchy from the child until I get the manager script and use that. Just wanted to check in case there are any other options which work better

spring creek
normal arch
spring creek
normal arch
#

but its supposed to be a vector2

#

but bounds isn't a vector 2

lyric atlas
normal arch