#archived-code-general

1 messages · Page 458 of 1

prime quarry
#

No matter what I try my rigidbodies seem to occasionally get stuck on each other.
All units have a rigid body component where:
A) The body type is set to RigidbodyType2D.Dynamic
B) The collidionDetectionMode is set to CollisionDetectionMode2D.Continuous

Ive tried:

  1. Adding a material that has no bounce and no friction
  2. Only having their position update in FixedUpdate
    3)Having forces push them apart
steady bobcat
#

using MovePosition() on rigidbody or modifying Transform?

thin aurora
#

<@&502884371011731486>

stoic dagger
#

Anyone knows why I cant get a graph workin in TensorBoard with Unity ML agent running?

somber tapir
#

Annoying error:

Could not update a managed instance value at property path 'managedReferences[1468299178456383489]', with value 'MyName.RectGridSystem MyName.RectGridSystem.Shapes.SquareShape'
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
```I changed the namespace of this class and now it's trying to use the old namespace. I already tried renaming and moving the scripts, renaming the implementation / setting it to private, but the error won't go away.
leaden ice
#

I think SerializeReference stores the class name in your scene or prefab file

somber tapir
#

got it working by deleting a bunch of stuff from the scene file

prime quarry
steady bobcat
# prime quarry Ive tried both

moving via transform will cause issues like this, using MovePosition() should prevent these issues. Are these rigidbody 2ds set to dynamic?

prime quarry
#

Yeah let me try MovePosition again

prime quarry
velvet pewter
#

How do you enable the nullable reference type compiler option in a Unity project? The reference says that you need to put this into your project's configuration:

<Nullable>enable</Nullable>

But I can't find the right file to put it into.

somber nacelle
#

you can't modify the csproj file for unity, you need to use a csc.rsp file to do it. but is there a specific reason you want to enable it?

velvet pewter
vestal arch
#

i don't think it'd really help with unity types anyways since they have fake nulls

somber nacelle
#

i mean, it's just some compile time warnings that encourage you to explicitly declare reference types as nullable. it changes nothing about runtime behavior

thick terrace
#

unity includes the Jetbrains null/non-null annotations which should mix and match just fine with it in most IDEs, so you can still use those where it's not enabled in a file

weary horizon
#

my player just keep falling through the game i made a tile area and added tile collider and all and put rigdbody and capsule collider its a 2d game but my character keeps falling
can anyone guide how can i fix this

#

it just keep falling it dont stand on it

leaden ice
weary horizon
#

on the tile

leaden ice
#

Which tile

#

The brown parts?

weary horizon
#

no the black part

#

the one its standing on if i play the game

#

it just falls through

leaden ice
#

That looks like empty space basically

#

Is this supposed to be a top down game?

weary horizon
#

its a patform with side walls

leaden ice
#

I don't see any platform

weary horizon
#

i want the character to move on that platform

leaden ice
#

It looks to me like you want it to be a top down game

weary horizon
#

u dont see the tiles ?

#

the tiles dude huh

leaden ice
#

In which case you should be setting gravity to 0

weary horizon
#

but i wanna remove tiles later according to the game so player can fall through them

leaden ice
#

I don't understand

weary horizon
#

uh can u come on call something i can show u

leaden ice
#

The player seems to be in the middle of the thing if it's supposed to be a side scroller

weary horizon
leaden ice
#

Can you explain which direction "down" is here?

weary horizon
#

this is a 2d game

leaden ice
#

Is down into the screen

weary horizon
#

i made a tile

leaden ice
#

Yes obviously

#

But is it a top down 2D game or a side scrolling 2D game

#

Looks like top down

weary horizon
#

i just started so i dont understand this terms top down and side scrolling

#

like player can move in that area what i am trying to achieve right now

#

and dont move in walls

leaden ice
#

Top down is like binding of Isaac or Gameboy Zelda games.

Side scrolling is like cup head

#

Your game looks like top down to me

#

So you need to just turn off gravity

#

Because gravity doesn't make sense for a top down game

weary horizon
#

yes yes

#

but in future game what i have decide i want the tile to be removed on specifc and make people fall threw it

#

so then how will i make that possible

#

and do i need collider then on below platform

leaden ice
#

there is no third dimension

#

there's only x and y

#

so you would either fake that part with some depth tricks

#

or you switch to the 3d physics engine

weary horizon
#

we can make it fall in y axis and making it behind the floor for first tile and in fron of behind tile no ?

leaden ice
#

i'm not sure I understand what you mean

weary horizon
#

so like imagine a 2 tiles so when character falls its in front of the tiles which are behind him and behind the tiles wich are in front of him which makes look like he is falling threw the tiles

weary horizon
#

ya so its possible or no do u get what i am trying to say ?

leaden ice
#

everything is possible

#

I just showed you the information on how to sort sprites so things are in front of or behind things

weary horizon
#

so basically i keep the gravity off

#

but when i wanna creat void

#

i will turn it on

#

something like that

leaden ice
#

I still don't really understand what you mean by "void" and "falling" in your top down game

#

maybe find a video or draw a picture explaining what you mean

weary horizon
#

i wanna make character fall threw the floor in further floors i wanna create a void or hole in the floor

#

from which charcater can fall then

#

so he has to basically move safely

#

do u get something from what i trying to say

leaden ice
# weary horizon from which charcater can fall then

DO you mean like the black pits here? https://youtu.be/koxzMjkktdE?si=fGATV6QIfd1p2wdd&t=7760

The Legend of Zelda: Link's Awakening DX full game completed 100%. This includes all heart pieces, weapons, photos and upgrades in the game. This has always been one of my favorite Zelda titles and I am looking forward to the remake on Switch coming out later this week.

This channel features instructional & highly edited video game guides, wa...

▶ Play video
weary horizon
#

yes u can say that

#

if he falls in those pit

#

he dis

#

dies

leaden ice
#

it's just using sprite tricks and scaling to make it look like they "fell"

#

the phyics engine in 2D only works on two axes - x and y

#

Basically all depth tricks you see in 2D top down games are just that - tricks

naive swallow
#

It's literally just a tile that plays a specific animation when you are over it. There's no gravity.

weary horizon
#

i got that but what if we do like this
when he get on that all the tiles below that comes inftont of him basically more in order layer than the character and all the above tiles are back of him basically less in order than the character

naive swallow
#

So, is this a side scroller? I don't really follow at all

brave geyser
#

I think you just need to try what you're talking about and see if it looks right. If you aren't sure how to code it up, just assign stuff in the inspector and move the character around in editor to imagine what it will look like when it's working. Then see if you want to proceed with this idea, which seems a little shaky.

whole wyvern
#
Ray rightRay = new Ray(transform.position, transform.right);
Ray leftRay = new Ray(transform.position, -(transform.right));
Ray[] rays = { forwardRay, rightRay, leftRay };

bool hitForward = Physics.Raycast(forwardRay, movementRaycastDistance * 0.5f);
bool hitRight = Physics.Raycast(rightRay, movementRaycastDistance);
bool hitLeft = Physics.Raycast(leftRay, movementRaycastDistance);
bool[] options = { hitForward, hitRight, hitLeft }; ;

if (hitForward && hitRight || hitForward && hitLeft)
{
    inCorner = true;
}

if (inCorner && hitRight)
{
    // turning left
    chosenRay = leftRay;
} else if (inCorner && hitLeft)
{
    // turning right
    chosenRay = rightRay;
}

if (!inCorner && !hitForward)
{
    // continue forward
    chosenRay = forwardRay;
}

if (hitForward && !hitRight)
{
    chosenRay = rightRay;
}
if (hitForward && !hitLeft)
{
    chosenRay = leftRay;
}
if (hitForward && !hitRight && !hitLeft)
{
    chosenRay = rightRay;
}

transform.forward = chosenRay.direction;
transform.position = (transform.position += transform.forward * Time.deltaTime * 3);
Debug.Log(chosenRay.ToString());```

This code is supposed to make the ai move in only a forward motion, by turning it either left or right before hitting a wall. it works moving forward, however for some reason when hitting a corner it makes the ai move diagonally? is there any reason for this
vestal arch
#

transform.position = (transform.position += transform.forward * Time.deltaTime * 3);
what's with the intermediate assignment here lol

leaden ice
#

Yeah the first part of that line is unnecessary

vestal arch
#

your checks seem quite redundant as well

#

the inCorner checks pretty much do the same thing as 2 of the last set of checks

#

also if inCorner is a class member, you never reset it back to false

#

you don't really need it though, seems to me you could just do:

if !hitForward
  chosenRay = forwardRay
else if !hitRight
  chosenRay = rightRay
else
  chosenRay = leftRay
```in place of all the if checks
ionic grove
#

This is probably something dumb, but I just can't figure it out... Does anyone know why this doesn't enable the ready image gameobject here?

public PlayerInfo AddPlayerCard(string _steamName, bool _isReady = false)
{
    // Instantiate player card and put in player list
    PlayerInfo _pi = Instantiate(playerCardPrefab, playerFieldBox.transform).GetComponent<PlayerInfo>();
    
    // Assign name
    _pi.steamName = _steamName;
    _pi.isReady = _isReady;

    // Make image active based off ready status
    _pi.readyImage.SetActive(_isReady);

    return _pi;
}
#

I have debugged it and ensured that _isReady is equal to true

vestal arch
#

have you tried logging readyImage is the right object? (ie Debug.Log($"setting {_pi.readyImage.name} to isReady = {_isReady}", _pi.readyImage);

#

also you could type playerCardPrefab as a PlayerInfo instead so you don't have to do the GetComponent thing

cursive orbit
ionic grove
hardy mulch
#

In Unity6 is there a replacement for setting a RigidBodies linear velocity? I understand it's UB with physX, however is there a "correct" way to do rb.linearVelocity = velocity;

#

And if there's not, is there at least a way to disable the warning?

stable osprey
hardy mulch
#

But it appears to work anyway, at least in my case, but id like to either do it the correct way or disable the warning

#

That thread discusses various solutions to moving an object, however in my case im doing some custom physics and want to then set the velocity

odd creek
#

Anyone know any good ways/extensions to serialize dictionaries and/or tuples?

#

(Preferably free - I saw one that looks good for $55 and I'd rather not lol)

cosmic rain
odd creek
#

Awesome thanks!

fringe knot
#

Im trying to figure this out

#

im doing the roll-a-ball course

#

I need help with this

violet nymph
tawny elkBOT
#

:teacher: Unity Learn ↗

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

cosmic rain
weary horizon
#

public class ObjectManager : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Key"))
        {
            Destroy(other.gameObject);
        }
        if (other.CompareTag("egg"))
        {
            Destroy(other.gameObject);
        }
    }

}```
#

i made this code for they key to collect and egg to collect

#

but they dont destroy on collision

#

can anyone tell

#

whats wrong in this code

robust dome
#

make sure your OnTriggerEnter is working, use some Debug.Logs

#

did you assign the tags?

weary horizon
#

yes i did

#

i add collider2d on key

#

and put key tag on it

#

and this is trigger on the collider2d too

robust dome
#

use some debug logs

weary horizon
#

its getting trigger

#

but not getting destroy

robust dome
#

how comes

weary horizon
#

idk

#

what the issue

#

wait


public class ObjectManager : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D other)
    {
        Debug.Log(other.gameObject.name);
        if (other.CompareTag("Key"))
        {
            Debug.Log(other.gameObject.name);
            Destroy(other.gameObject);
        }
        if (other.CompareTag("egg"))
        {
            Destroy(other.gameObject);
        }
    }

}```
its just saying player one time so it means its getting trigger with player wth
#

how does that happening

robust dome
#

on which gameObject do you have this script

weary horizon
#

and i have put this script on egg and the key both

robust dome
#

but it doesnt make sense. you are checking for Key and egg so this would make more sense if it was on your player

weary horizon
weary horizon
#

hahahaa

#

thats true

#

cause it didnt had the tag ?

robust dome
#

so if you want you can have the Trigger check on your objects (key and egg) but you need to check for Player tag instead. it is up to you how you do it

weary horizon
#

yeeeee it worked ty for help man

robust dome
#

you are welcome man

weary horizon
#

which would be better

#

to have on player

#

or on object

#

aint both work same way ?

robust dome
#

it is just about organization and keeping things well structured

weary horizon
#

what would be called well structured ?

robust dome
#

i would probably have this on the player

weary horizon
#

ohk ty for help man 🙂

golden wave
#

This feels really stupid, is it? Is there a better way to do this?
I can't have a single capacity variable to combine all resource types because of how the game logic works.
(This is Photon Quantum code, FP is basically a float)

if (plunderTarget.PlunderType == PlunderType.Food)
    capacity = plunderer->FoodCapacity - plunderer->Food;
else if (plunderTarget.PlunderType == PlunderType.Wood)
    capacity = plunderer->WoodCapacity - plunderer->Wood;
else if (plunderTarget.PlunderType == PlunderType.Stone)
    capacity = plunderer->StoneCapacity - plunderer->Stone;
else if (plunderTarget.PlunderType == PlunderType.Magicka)
    capacity = plunderer->MagickaCapacity - plunderer->Magicka;

FP plunderAmount = plunderer->PlunderSpeed * f.DeltaTime;

if (plunderAmount >= capacity)
{
    plunderAmount = capacity;
}

if (plunderTarget.PlunderType == PlunderType.Food)
    plunderer->Food += plunderAmount;
else if (plunderTarget.PlunderType == PlunderType.Wood)
    plunderer->Wood += plunderAmount;
else if (plunderTarget.PlunderType == PlunderType.Stone)
    plunderer->Stone += plunderAmount;
else if (plunderTarget.PlunderType == PlunderType.Magicka)
    plunderer->Magicka += plunderAmount;```
wide dock
golden wave
#

yeah that might be better 🙂

light wraith
#

does for anyone else
unity postprocessing il for assembly csharp editor takes a lot of time?
my code is split into assembly definitions, I just compiled one with only 2 scripts inside it and this step took a minute!
why does unity take so long to compile code? this doesn't make sense to me

#

Iv'e got a new, pretty strong pc, something is wrong with my project, not sure how I can check what

cosmic rain
cosmic rain
vague meadow
#

If i have a central event manager with static events, can I just set them to null on the event manager OnDisable method or do I also have to unsubscribe all subscribers?

leaden ice
vague meadow
light wraith
#

screenshot from google, it doesn't take me 41:05 minutes to reload domain UnityChanSalute

steady bobcat
#

I had an issue a while ago where I tried to unsubscribe from a firebase event in a destructor which would cause domain reloading to never end

leaden ice
odd creek
#

This might be more of a personal preference thing, but what do folks generally prefer - using interfaces or UnityEvents? Like I'm planning out an enemy logic script where it'll do some stuff and then determine when it wants to attack, and then other scripts will handle the implementation of what actually happens when the enemy attacks (whether it shoots, chases the player, etc). I could see two ways to make this work - either holding a list of references to components that can attack(), unified by an interface, and so when the logic controller decides to attack, it iterates over all the references and just calls .attack(); or alternatively, there are no references, and when the logic controller decides to attack, it just invokes a UnityEvent which whatever other attacking scripts are subscribed to. Both approaches seem like they'll work and have the same end result, but my gut tells me the UnityEvent approach is better design-wise. I can't really articulate why though so I'm curious if anyone has any thoughts?

steady bobcat
last quarry
#

Gut feeling says interfaces.

steady bobcat
#

yea its better in the long run id say

#

events should be for "i did a thing, if anyone cares then here ya go"

odd creek
#

Gotcha - what if the things that are subscribing to the attack event just launch off async calls? Then they could do still async or non-async stuff

steady bobcat
#

yea they can but means they cannot be awaited if you ever wished to in future

odd creek
#

I see, I'll keep that in mind

#

I've got a couple areas of the code that follow this pattern so maybe I'll try an interface on one and a unityevent on the other just to see how they both do lol

steady bobcat
#

you can make normal events too if you do not need serialized subscribers:
public event Action<int> MyCoolEvent;

odd creek
#

Ah yea I was hoping to serialize the listeners so I can set them in the editor - what would be the alternative though out of curiosity? That I would assign a reference to the main component in the lister components and have them each add listener to the reference on Start()?

steady bobcat
#

yea you sub in code and that should be preffered for how much slower serialized event subs are

odd creek
#

Ah man that's too bad, I've been trying to serialize as much stuff as possible since it seems easier to make stuff with and debug

steady bobcat
#

well you can find all references for an event in your ide to know whats subscribing to it

#

up to you, if you go with the interface approach this gets solved anyway

odd creek
#

Tru, yeah I guess that's another reason it'd be better

#

Another question, more c# related - is it possible to make a delegate that can be defined with multiple different headers? Like in specific I'm wondering if there's a way to do

delegate MyDelegate<T> // etc

MyDelegate<int> foo = (int input) => {} // valid
MyDelegate<int> bar = () => {} // also valid

foo.Invoke(5);
bar.Invoke(4); // required to pass in int, but gets discarded
#

In typescript this would be super easy but I'm wondering if there's a way to do it in C# (mostly to avoid having to write (int _) => everywhere the second scenario gets used, which would be most of the time)

steady bobcat
#

delegates and therefore events require the subscriber to match the signature

odd creek
#

darn

upper pilot
#

How do I force SO to create new GUID when copy pasting SO?
It did work a second ago using a constructor, but it stopped for some reason.
I am trying to use OnValidate but that doesn't work either.

kindred plume
#

So basically im having problem with the rotation. I put the camera inside a empty gameobject called CameraHolder, and put the CameraHolder outside of all the GameObjects, so basically it's just alone. Then i have the Player GameObject and inside of it there is the Model and in the Player i just put the scripts.
The soure of the problem comes from these lines of code:

private void LateUpdate()
{
    CamMovements();
}

private void CamMovements()
{
    if (!_hasAnimator) return;
    var Mouse_X = _inputManager.Look.x;
    var Mouse_Y = _inputManager.Look.y;
    Camera.position = CameraRoot.position;
    print(CameraRoot.position);
    _xRotation -= Mouse_Y * MouseSensitivity * Time.smoothDeltaTime;
    _xRotation = Mathf.Clamp(_xRotation, UpperLimit, BottomLimit);

    _yRotation += Mouse_X * MouseSensitivity * Time.smoothDeltaTime;

    //Camera.localRotation = Quaternion.Euler(_xRotation, 0, 0);
    Camera.localRotation = Quaternion.Euler(_xRotation, _yRotation, 0);
    //transform.Rotate(Vector3.up, Mouse_X * MouseSensitivity * Time.smoothDeltaTime);
    Model.Rotate(Vector3.up, _yRotation);
    //Geometry.Rotate(Vector3.up, _yRotation);
    Orientation.Rotate(Vector3.up,Mouse_X*MouseSensitivity*Time.smoothDeltaTime);
}

So basically like i said this script is put inside the player GameObject that has "Orientation" as a child.

steady bobcat
#

What are you trying to achieve and why include your commented out code? 😄

rigid island
kindred plume
rigid island
steady bobcat
#

I watched it and I kinda get it. You normally don't have a full model in first person...

kindred plume
kindred plume
rigid island
#

the camera should be like in the middle of the head

#

along with hiding the head in the renderer . keep shadows only

kindred plume
rigid island
kindred plume
#

so hold on, first i want to resolve the pivot problem, how do i check that

kindred plume
rigid island
rigid island
kindred plume
#

alr

rigid island
kindred plume
#

oh sorry

rigid island
#

also why are there 3 transforms in the code ? Model, Orientation and Cam?
generally if camera is child of body you only need to rotate body on Y the rest follows

kindred plume
#

to resolve the camera jittering problem

kindred plume
kindred plume
rigid island
kindred plume
#

Camera is the CameraHolder

#

hold on lemme do another photo

rigid island
kindred plume
rigid island
#

put it in Pivot mode instead of Center

#

make sure the offset if correct after that

kindred plume
#

ok

#

doesnt change nothing

rigid island
#

its not supposed to fix anything, just show you where everything is placed cause clearly Camera aint going where the CameraRoot is

kindred plume
#

oh ok ok sorry

rigid island
#

the camera is like behind the head

kindred plume
#

not always

rigid island
#

yes but it should probably more in the center of its parent aka the head

#

if its so far away from that rotation is gonna also look "wide"

kindred plume
#

when i rotate this way, it goes in the right position

kindred plume
#

so i should put the camera on the center of the head and not render the head, right?

rigid island
#

so when you rotate it without offset it doesnt goo "wide" but rotates in same spot

kindred plume
#

i'll let u know

#

i put the cameraroot on the center of the head but the camera is offset when the player run or strafe left/right

rigid island
#

could be the animation

kindred plume
#

yea

rigid island
#

its been a while since I touched FPS full body but had to do a few things to make it "look right"

kindred plume
#

so do i adjust the animation? What should i do

rigid island
#

basically its a compromise between leaving it at the head Position vs the Head Bone

#

headposition doesnt care about where the body is strafing/moving to cause no bones follow
if its head bone then you have the animation influencing it which is both good and bad

#

like I said its been a while since I touched it, just wanted to see where you set the pivots.. Maybe someone who has more xp on this can chime in

kindred plume
#

maybe i found the problem

#

lemme show u with a vid

#

so my guess is that i should put the animator on Skeleton instead of playerArmature

rigid island
#

looks like now the animation is messing with the positioning

#

so probably Geometry instead of bones

#

like I said its a compromise

kindred plume
rigid island
#

the spheres gizmos are like the humanoid bones I think or IK for animator Avatar , forgot what

kindred plume
#

so it has nothing to do with the rotation problem?

rigid island
#

its like "lagging behind" because of the way head bone moves in animation

#

also did you put the follow code in LateUpdate ?

kindred plume
rigid island
#

but when you rotate standing still its fine and rotates in place

#

that hints at animation / bone position issue whilst running

kindred plume
#

yea

#

i will try to solve this tomorrow, now im too tired it's 1:35 am

rigid island
silk garden
#

hmm something isn't right unity 6 OnMouseDown(); so i only have just one single 2D sprite with a 2D box collider. just one script that just does a debug log.
it does show in the console my start when i start it, but i cannot fire off the event when i click on the 2D gameobject.... makes nosense.

` private void OnMouseDown()
{
Debug.Log("clicked");
}

private void Start()
{
    Debug.Log("started");
}   ` 

i mean its simple code. so confused how it works with unity 5 but not 6

celest drum
#

Helloooo

#

Need some help for a jam

#

I've been trying to script blocks to be moveable in this way:

#

The same way it would in a wood slizing puzzle

#

But collisions don't work because the existing code overrides the physics systems by directly changing the transform

#

And I'm really not understanding the guides online for this

#

`public void OnDrag(PointerEventData eventData)
{
Vector3 currentPosition = transform.position;
currentPosition.x = playerCamera.ScreenToWorldPoint(Input.mousePosition).x;
Debug.Log("Dragging");

  if (currentPosition.x - (Math.Truncate(currentPosition.x)) != 0.5)
  {
      currentPosition.x = Mathf.Round(currentPosition.x * 2f) * 0.5f;
      transform.position = currentPosition;
  }

}`

lean sail
celest drum
#

Okie, thanks! I'll look into it

leaden ice
#

Also Unity 5 is like 10 years old

potent ore
#

hey im very very new but im trying to learn and im trying to make an attacking character its super basic but like i have one script on the player that enables a child object of the player that has a polygon collider then disables it after a second but my script on that childobject isnt working right, itll work but only the first time the player presses attack, it wont deal damage again until the player moves at all, it doesnt matter if the polygon collider stays in the enemys hitbox at all during the movement as long as the player moves, like the enemy could be flushed against a wall against the enemy and move into the wall further and attack and itd work but not if the player didnt move, i would really appreciate the help im very new and have programming experience but not game development, here is my code, if someone could answer me here or dm i would be very appreciative, using UnityEngine;
using System.Collections.Generic;
public class Damaging : MonoBehaviour
{
[SerializeField] private int damage = 10;
private HashSet<Collider2D> damagedEnemies = new HashSet<Collider2D>();
private void OnEnable()
{
damagedEnemies.Clear();

}

private void OnTriggerStay2D(Collider2D collision)
{
    if (collision.CompareTag("Enemy") && !damagedEnemies.Contains(collision))
    {
        var enemyhealth = collision.GetComponent < Health > ();
        if (enemyhealth != null)
        {
            enemyhealth.Damage(damage);
            damagedEnemies.Add(collision);
        }
        
    }
}

}

dusk apex
potent ore
#

how do i do that, sorry like very very new

dusk apex
#

You'd call that after activating the inactive object

potent ore
#

so if im activating it from the player i would need it in the players script and not the damaging script?

soft shard
#

Bit of an odd question, but is there some useful name for "w" in a Quaternion I can use to help give human context to that letter? Its fair to say "x", "y" and "z" represent the "angle" as the human context, and the "w" the... "threshold"? Online explanations (the ones that dont try to sound like university thesis assignments) try to explain it as "how much to rotate the object along the xyz angle" and im using a online "Quaternion playground" to try and understand how the "w" works - its odd to me that a "w" of 0.9 makes a "y" of almost 0.5, but a "w" of 1 makes a "y" of 0 seems like quite a jump so I donno if "threshold" makes sense? - im asking because im trying to make a extension for Quaternion for easier use

cosmic rain
lean sail
# soft shard Bit of an odd question, but is there some useful name for "w" in a Quaternion I ...

are you going to be manually computing quaternions or something? id be surprised if you ever need to know this kind of math, even in your custom tool. Quaternion is already very simple to use given all the premade functions.
if you are doing something manually, you'd really want to look into those university level explanations because this is not a simple topic. I do see the xyz and w values the same way as dlich said above though

soft shard
# lean sail are you going to be manually computing quaternions or something? id be surprised...

Ah, that does sound like a good way to look at it and its possible I could be overengineering my understanding, ill think on that, thanks to both of you - for more context, its both a serializing thing and a wrapper thing, I want to make a custom class to handle serializing a Quaternion type and Vector3 type (which Vectors I already have handled), while also adding some extra functionality to make assigning and using Quaternions more like assigning and using Vectors, so the "w" is more for context (though I guess can be used for manual changes too), personally for myself, I like having names that make sense instead of just letters for formulas, for example its easier to understand "value / max = percent" than "c = a / b" (though I get why letters are used in math)

lean sail
#

I guess I just dont really see what aspect of Quaternion even needs an extension for. Its simple to use in inspector, premade methods do all the math for you, you never need to touch the individual values ever, and stuff like newtonsoft handle writing it to file already

cosmic rain
soft shard
# lean sail i dont really understand what the use case is here. quaternion and vector3 are a...

I dont think they are completely serializable, when I tried to serialize them with Newtonsoft in the past, because they have properties that reference themselves, it cant completely serialize, same for structs like Color so I figured it would be easier to just have a custom class to handle those types - right now the use case is a bit of a experiment to see its practicality, partly for my own curiosity and partly for use in other projects if I decide to change serializers or even want to test code across engines where it might not know what a "UnityEngine.Quaternion" is, my use is mostly through code rather than inspector in this case

cosmic rain
#

And they are definitely serializable by unity serializer. And for other engines, you just need to implement deserialization logic(assuming the implementation is different).

lean sail
#

not trying to stop you from doing this but like, none of this seems needed still

soft shard
#

Thats fair, I think I still want to give this a try anyway, ideally I kinda want to do something like

public class Something
{
public CustomVector3 pos;
public CustomQuaternion rot;

void Save(){this}
void Load() {this = ...;}
}

public class SomeMono : Mono
{
Something data;
void Start()
{
data.Load();
transform.position = data.pos;
transform.rotation = data.rot;
}
void Update()
{
transform.rotation = data.rot.Rotate(30f, Axis.X, 10f); //rotate 30 degrees on X over 10 seconds
}
}

The latter I probably wouldnt ever need "w" but I probably could be over-engineering my use case

night harness
#

You’d just need to save/load angles ye

soft shard
#

Though I may still look into the converters link you sent, it seems equally as useful - thanks for that link as well

lean sail
soft shard
# lean sail i still dont understand why "w" is a concern here. if you want to store a quater...

The "w" is mostly for my own understanding in adding context to what im doing, I just dont like having letters for variable names, I doubt ill ever really actually need to use the w but because its part of what makes Quaternion work, I figure its important to include it, and so I should have an understanding of what that variable exists for (sorry im not the best at explaining things), though I am using some of the utility functions of Quaternion for converting

mellow sigil
#

There's nothing special about the w component compared to the others. The x, y, and z components aren't related to Euler angles in any way so it's a mistake to think of them as a separate thing from the w component. Unfortunately there isn't any practical equivalence in 3D space that you could use to name any of them

#

There's a visualization here: https://quaternions.online/ and if you play with the different components you can see they all behave seemingly the same way (in that you can't really intuitively tell how they influence the rotation)

soft shard
#

Ah, I think that was the same "Quaternion playground" I was messing with earlier, I dont understand how they wouldnt be related though as I understand, the "w" is inter-connected with the other 3 (ie: changing y also changes w, and vice versa) though maybe I should play around with it more in the morning and do some more tests, thanks for the insight on that

mellow sigil
#

The quaternion vector is always normalized so that's why changing one changes the others, but that's a bit of a red herring

#

What I mean is that it would be strange if someone asked "I know what x and y are in Euler angles but what is z" because if you know what x and y do then you "automatically" know what z does, because it's essentially the same thing. In the same way it's not really meaningful to ask what w does in a quaternion because that implies you already know what x, y and z do (which you don't, if you're asking about the w)

soft shard
#

Ah, that context makes sense now, and your right in that I dont fully understand it but I see why it would be a odd question to ask

mellow sigil
#

It's unfortunate that the components are named x, y, z and w because that just leads to confusion with Euler angles. They might as well be a, b, c, and d or 1, 2, 3 and 4

lyric silo
#

Help!

I have a SortedSet (element is a class type) and retrieve its Min, assigning it to a variable.
Afterwards, that variable and the set's .Min property are evaluated to be unequal.

  • And there's the problem. I expect them to be equal, naturally.

  • The contents in the variable are identical to those in Min, however.

  • The comparer I passed to the set specifically returns 0 when two objects are equal,
    i.e. it does take reference semantics into account.

I wrote a c# console app that mimics my game code, and there, everything works as expected.
What am I missing?

cold parrot
weary horizon
#

can some help me make a jump in a top down game i couldnt make it tried several methods and animation it just keep getting bugged or it stuck at animation ot it wont jump

#

or guide me how can i approach it

dim cairn
tawny elkBOT
weary horizon
#

section i have done there

dim cairn
#

dont cross post -_-

unkempt meadow
#

but I think it looks somewhat awkward because it's unnatural to move the fingers only after the hands hit the final position

#

I would need to start moving the fingers before but I can only do the correct raycasts after the hands are in position

#

I'm not quite sure how to handle this problem. I can only think of simulating this before with "ghost hands" and then replicating the finger rotations with "real hands"

#

I saw your deleted comment, we had the same idea haha

dim cairn
#

beat me to it lol

unkempt meadow
leaden ice
unkempt meadow
# leaden ice No I'm asking why you have to wait before raycasting

Because I'm raycasting from the finger position in an arbitrary direction which is mostly downward.

Can't do that if the hand is far away from the position where it ends up eventually. Hence the "ghost hand", or doing that simulation before it happens visually.

If you have a less awkward idea, I'm very open to hearing it cause there probably is a better way

leaden ice
unkempt meadow
leaden ice
#

You don't need another object or manual hard coding

#

You can just take the local positions of the finger roots or whatever they are and calculate where they'll be based on the hand's target position and orientation

unkempt meadow
leaden ice
#

No need for copying GameObjects etc

weary horizon
#

and still no response 🙂

stable osprey
#

Sounds completely unrelated to code tbh:. Are you sure people here will be able to help?

unkempt meadow
leaden ice
#

it's two lines of code involving the matrix

unkempt meadow
vestal arch
#

you know the thing about treating quaternions as a black box?

#

this is kinda a similar thing

unkempt meadow
vestal arch
#

yeah

#

a quaternion can mathematically describe a rotation, this 4x4 matrix can mathematically describe a transformation

unkempt meadow
#

I see what you mean. I will check it out later

leaden ice
#

you can kind of think of it as a Transform without a GameObject

tulip brook
#

how do I remove an object from an array of gameobject[]?
when I remove instead of getting null(none) it just shows "missing game object", stopping me from cleaning the array

vestal arch
#

you can't remove something from an array, an array is statically-sized
you can overwrite it with null/an empty value, but you can't directly remove it

astral relic
#

for the love of god, is there a way to be able to drag drop an interface implementation (script) into inspector. ANYWAY.

public MyScriptable : ScriptableObject
{
    public IGPUPlacerRenderer MyRenderer;
}
public interface IGPUPlacerRenderer : IDisposable
{
    public void Render(PlacementParams @params, 
        NativeArray<GPUPlacer.PlacementResult> results, uint count);
}
#

do i have to buy odin to get this simple thing

tulip brook
#

actually no

I'm trying yo use this but it will still leave empty elements in my array

#

idk what I'm doing wrong

vestal arch
astral relic
#

which is not possible ins criptable objects

vestal arch
vestal arch
astral relic
#

but from the first place, the field for an interface does not show

#

at all

tulip brook
#

i kinda wanna avoid using list bc the array is already baked into my code if possible

astral relic
#

refactor your code

#

use IList<t>

#

you can like that use arrays and lists

#

also the code you posted is fine. you get no results bc everything is null

#

or the input is empty

#

also a destroyed gameobject is not null, just saying.

#

that function itself smells

vestal arch
tulip brook
astral relic
#

refactor everything dude, that is not a good function

#

you will save yourself problems in the future

vestal arch
#

yeah just use a list to begin with

tulip brook
tulip brook
vestal arch
astral relic
#

it means rethink how you are writing your code and how you wrote it, and change it

tulip brook
#

i still wanna make this work bc if I fix this one thing my little project is p much done

astral relic
vestal arch
astral relic
#

cannot serialize parameters

vestal arch
#

wdym by that?

astral relic
#

class lovelyTree : tree { int size }

#

-> can chose tree implementation but cannot change size

vestal arch
#

there aren't any parameters there

#

that's a field, but interfaces can't have public fields, no?

astral relic
vestal arch
#

you drop an implementation

you configure a parameter in it
you just can't do these 2 things together afaik

#

it's either a reference or an instance defined there

astral relic
#

you can in odin apparently

vestal arch
#

🤷 idk odin, i'm just talking about the built-in capabilities

astral relic
#

builtin cant serialize a class reference

#

the dude who wrote that script is serializing its type name

#

never mind

#

you can

#

it seems

#

he wrote the serialization as well. nice

little meadow
#

wait, what are you trying to serialize?

astral relic
#

class ref that implements an interface. with its instancing parameters (public fields values)

little meadow
#

so, a [SerializeReference, SomeTypePickerThing]?

astral relic
#

idk what that means

#

either way my issue is resolved

astral relic
#

ty @vestal arch

little meadow
#

like, [SerializeReference] is Unity's way of serializing a field of interface/abstract class which just works properly no magic behind, the only thing missing is having a picker for the type that you want... any OTHER solution I'd condier worse (if it does its own magical serialization)

astral relic
#

asking to know what to use maybe u have sth beter

little meadow
#

well, I wrote my own like 3 years before that, was just a bit late on making it open source 😄
I honestly haven't checked feature parity lately... mine has an option to override the types and not show all possible ones, but that's like a rarely useful thing

mystic sapphire
#

Hey Im not sure if this is the correct channel to ask this is but I have an issue where I am trying to make armour for my game, but everytime I export it into unity, it either is using the armature from blender so it wont go onto my character or when I import it into unity there isnt a skin mesh renderer for me to set for my current character. I'm not sure what I'm doing wrong as I've watched multiple videos trying to figure it out but nothing seems to work.

Steps I do:

Import my character model into blender using the fbx that is in my game folders

I then move and adjust the armour to fit around the model

I then click on a piece of armour (lets say the chestplate) which covers the chest, shoulder and a bit down the arms and then shift click the armature and press CTRL + P and select With Automatic Weights

Now this is where it all goes wrong

If I export the armour piece and the armature then It wont go onto the character I already have in my game but if I dont export the armature with it then there is no skin meshrenderer to do anything

swift falcon
#

Is it okay to use WaitForEndOfFrame for things besides Post Processing effects?
Like when you need to prevent a certain function from executing all in one frame to prevent freezes

vestal arch
leaden ice
#

I was too slow 🐢

swift falcon
#

Okay thank you both

swift falcon
vestal arch
#

🤔 originally it was paired with the execution cycle diagram, i guess that context has kinda been lost

slim mason
#

i love the code autocompleter cus you can ask it questions in comments and its straight to the point

vestal arch
#

that's not autocomplete, that's intellicode/copilot, it's genAI lol

little meadow
#

So - fancy autocomplete 😝

odd creek
#

Autocomplete for bad people 😛

little meadow
#

Or maybe the opposite 🤔😜

vestal arch
little meadow
#

I was half-trojoking, sorry

vestal arch
#

ah, that makes sense lol

surreal blaze
#

anyone know if theres problems with switching display modes in Unity 6?

I'm confirming the screenmode is windowed through debug.logs but the games not in a window, i'm not sure if this is a Unity 6 issue, or somehow a Windows11 thing

#

its a build BTW

tribal owl
#

Hi im wanting to play a green screened video in my 2d game as a UI element, but im having a lot of trouble getting the background removed, can i get any help please?

surreal blaze
odd creek
#

So I'm implementing like a enemy aggro radius and I can think of two ways to do it, trying to figure out which of the two approaches would be best:
Approach 1:

  • Keep an list of all Entitys in range (Entity is like the script for "thing that can be attacked")
  • Grow and shrink the list from onTriggerEnter/Exit by attempting to fetch for the Entity component
    Approach 2:
  • On Update , find all Entitys within a radius via Physics2D.OverlapCircleAll
  • If no Entitys, revert to idle, otherwise attack and pass in the Entity[]

Neither one seems particularly appealing to me - the first is very stateful and I'm trying to minimize that as much as possible. I'm also not sure how it interacts with gameobjects being disabled/destroyed - I might need to add some additional filtering or conditions in case an enemy ends up attacking a disabled entity. Meanwhile the second seems reasonable since there shouldn't be any mutable state, however possibly could be slow/overkill? Since I'd be calling OverlapCircleAll every frame, along with the attack handlers, which could get kinda messy and it's not very event driven like the first option.

This has got to be a really common thing to make in unity - does anyone have any thoughts on which would be a better option, or possibly if there's a third, even better way to do it?

lucid brook
#

I have a math question about a sin wave, I use one for a headbob effect that works perfectly but I want to add footstep sounds which I thought I could trigger in the headbob math whenever the sin wave is at it's lowest point. So I'm just wondering if there is a way to calculate the lowest possible number Mathf.Sin(Time.time * frequency) * amplitude; will return.

leaden ice
#

because due to the fact the game runs in discrete frames, you will never reach that exact lowest point

#

A sine wave is at its lowest point when the input to the function is 3PI / 2

#

so what you can do is just keep track of what your previous input was in a variable, and then compare the current input to that.
If the previous input was less than 3PI/2 and the curent input is equal to or greater than 3PI/2, you should play the footstep now.

#
float LOWEST = Mathf.PI * 3f / 2f;
float TWOPI = Mathf.PI * 2f;
float lastSineInput = 0;

void Update() {
  float sineInput = (Time.time * frequency) % TWOPI;
  if (sineInput >= LOWEST && lastSineInput < LOWEST) {
    PlaySound();
  }

  // this is the part you use for the normal headbob
  float height = Mathf.Sin(sineInput) * amplitude;

  lastSineInput = sineInput;
}```
Something like this
#

oh you need to modulo 2PI too

#

fixed it

#

(this can fail if you have a bad framerate hitch btw, but should be pretty good)

lean sail
#

with the max delta time too, its possible lag wouldnt even cause it to skip a step but depends on what the period is

vestal arch
fathom geode
#

before Unity 6, if your script didn't have any methods within the Unity lifecycle (like start, or update), the ability to activate/deactivate the component was stripped from the engine's lifecycle updates. It appears this is different in Unity 6.

Does anyone know where I can find more info about this change, and when/why it occured?

leaden ice
#

Oh hey you're right. Looks like they show it no matter what now

fathom geode
#

On a blank URP project with Unity 6 LTS, if I create an empty script with everything removed, it still draws the ability to activate/deactivate the component

I'm not sure if this is a visual-only change

leaden ice
#

It's definitely a visual only change

#

You could always enable/disable a Behaviour no matter what functions it has on it

#

(from script)

fathom geode
#

I found the old behavior really useful for conveying intent -_-
Just wanted to make sure it's just visual only, wasn't sure if there was new component overhead or some other larger change

leaden ice
#

now you can do it from the UI too it seems.

#

It's definitely visual only

#

nothing about the API has changed

leaden ice
#

I would report it and see what they say

#

ChatGPT claims this change was not documented anywhere (take with grain of salt)

steady bobcat
#

to me this is a good change as it lets you use .enabled for things easier even if you dont use some update method

lean sail
#

disabling/enabling a script would have no purpose if you dont use any of the unity messages though
unless this affects GetComponent?

steady bobcat
#

ofc in code you can always read/write enabled but having the checkbox always show is nice

#

you can still read and use it in any way you wish yourself

shell scarab
#

Hey guys, is there anywhere I can find information on what specifically is the 'expensive' part of Debug.Log? Is it writing to a file?

leaden ice
#

also yes writing to a file but that typically would be happening in a separate thread (I hope)

shell scarab
#

or at least asynchronously yea

#

ok thank you

steady bobcat
#

the occasional debug log in prod is fine. printing a few things each Update in prod is a big no no

#

if you can restrict many to DEBUG only:

Debug.Log();
#endif
lucid brook
leaden ice
#

It was just the first thing I thought of

#

I think that logic approximates the same thing I was doing

#

you're checking if the function is currently ascending, but only if the function was descending last frame

lucid brook
#

just more on my level lol

leaden ice
#

I think it's equivalent, so if it makes more sense to you, go for it.

rancid frost
#

Any1 know why the first image (webgl build using react + vite on browser) is blurry compared to the scene view second picture?

leaden ice
rancid frost
#

@leaden ice remarkable, you have been here since the dawn of time. Always a pleasure to have you.

I thought so too, but i cant be

      <Unity
        unityProvider={unityProvider}
        style={{
          aspectRatio: "16 / 9", // Maintain aspect ratio
          width: "100%",         // Full width of the container
        }}
      />
leaden ice
#

I'm not enough of a frontend/web developer to really know how CSS and HTML stuff works at this level unfortunately.

#

Is the game view in Unity also blurry?

rancid frost
#

no, just in browser
scene view and desktop view completely fine

leaden ice
#

I'm not sure that just maintaining the aspect ratio will maintain the resolution

#

in fact I'm pretty certain that will dynamically scale it to the size of the container it's inside

rancid frost
#

well, even setting the resolution to say 1920 x 1080, doesnt help

leaden ice
#

what is the game resolution set to

#

that's the question

#
Debug.Log($"w: {Screen.width} h: {Screen.height}");```
rancid frost
#

in unity or browser?

leaden ice
#

In unity in the browser

#

add that code to a script, run the game in your browser, see what it prints to the browser console

#

(make sure it's a development build)

rancid frost
#

ok, sec i gotta modify and rebuild

steady bobcat
rancid frost
steady bobcat
#

nvm i just realised the whole thing is low res derp

rancid frost
#

yea

leaden ice
#

so yeah the resolution of the canvas element doesn't match the resolution of the game

rancid frost
#

I have a new update
it seems when i click (build and run) the resolution issue is not present

kindred plume
#

why is this happening?
Im rotating on y axis the Model GameObject, the Orientation and the CameraHolder
And for moving the player im using this code:

_currentVelocity.x = Mathf.Lerp(_currentVelocity.x, _inputManager.Move.x * targetSpeed, AnimBlendSpeed * Time.fixedDeltaTime);

_currentVelocity.y = Mathf.Lerp(_currentVelocity.y, _inputManager.Move.y * targetSpeed, AnimBlendSpeed * Time.fixedDeltaTime);

var xVelDifference = _currentVelocity.x - _playerRigidbody.linearVelocity.x;
var zVelDifference = _currentVelocity.y - _playerRigidbody.linearVelocity.z;

_playerRigidbody.AddForce(Orientation.forward * zVelDifference + Orientation.right * xVelDifference, ForceMode.VelocityChange);
rancid frost
kindred plume
rancid frost
#

first is build and run
second is build and then i use react to run it

leaden ice
#

Also if you just want to set the velocity, feel free to just set it

#

calculating the difference and doing a ForceMode.VelocityChange force is just a roundabout way to set the velocity.

#

Another issue here is that it seems you are trying to do some relative velocity handling but when you calculate the x and z diffs you're calculating those against Rigidbody.velocity which is in world space

kindred plume
leaden ice
kindred plume
#

alright lemme put it

leaden ice
#

pretty sure it is

kindred plume
#
private void Move()
{
    if (!_hasAnimator) return;
    Debug.DrawRay(transform.position, Orientation.forward*5f,Color.white,0.1f);
    float targetSpeed = _inputManager.Run ? _runSpeed : _walkSpeed;
    if (_inputManager.Move == Vector2.zero) targetSpeed = 0;
    if (_grounded)
    {
        _currentVelocity.x = Mathf.Lerp(_currentVelocity.x, _inputManager.Move.x * targetSpeed, AnimBlendSpeed * Time.fixedDeltaTime);

        _currentVelocity.y = Mathf.Lerp(_currentVelocity.y, _inputManager.Move.y * targetSpeed, AnimBlendSpeed * Time.fixedDeltaTime);

        var xVelDifference = _currentVelocity.x - _playerRigidbody.linearVelocity.x;
        var zVelDifference = _currentVelocity.y - _playerRigidbody.linearVelocity.z;
        
        _playerRigidbody.AddForce(Orientation.forward * zVelDifference + Orientation.right * xVelDifference, ForceMode.VelocityChange);
    }
}

private void CamMovements()
{
    if (!_hasAnimator) return;
    var Mouse_X = _inputManager.Look.x;
    var Mouse_Y = _inputManager.Look.y;
    Camera.position = CameraRoot.position;
    _xRotation -= Mouse_Y * MouseSensitivity * Time.smoothDeltaTime;
    _xRotation = Mathf.Clamp(_xRotation, UpperLimit, BottomLimit);

    _yRotation += Mouse_X * MouseSensitivity * Time.smoothDeltaTime;

    Camera.rotation = Quaternion.Euler(_xRotation, _yRotation, 0);

    Model.Rotate(Vector3.up, Mouse_X * MouseSensitivity * Time.smoothDeltaTime);

    Orientation.Rotate(Vector3.up,Mouse_X*MouseSensitivity*Time.smoothDeltaTime);
}
leaden ice
#

Perhaps jsut replace this code with:

_currentVelocity.x = Mathf.Lerp(_currentVelocity.x, _inputManager.Move.x * targetSpeed, AnimBlendSpeed * Time.fixedDeltaTime);
_currentVelocity.y = Mathf.Lerp(_currentVelocity.y, _inputManager.Move.y * targetSpeed, AnimBlendSpeed * Time.fixedDeltaTime);

_playerRigidbody.velocity = Orientation.forward * _currentVelocity.y + Orientation.right * _currentVelocity.x;```
#

Pretty sure that will fix it

kindred plume
#

Alright i'll try it, thank you so much

leaden ice
#

(get rid of the diff thing and the AddForce)

kindred plume
#

ok

#

im using unity 6 so it says that using the velocity variable is obsolete

#

should i use linearVelocity?

leaden ice
#

yes

kindred plume
#

ok

#

Yoooo it fixed

#

thank you so muuch

spare island
#

So just to make sure I'm correct on this, Unity simply doesn't provide documentation for C# builtins?

#

no description or anything

#

0 XML docs

surreal blaze
#

hi all, anyone know much about display modes? Im applying Windowed mode here, but for some reason theres no bar and i can't resize it, im running Windows 11, Unity 6000.1.6f1, latest HDRP pipeline

#

i seem to have all the correct settings on for it...

spare island
surreal blaze
surreal blaze
#

i take it Windows has no real way of knowing your app is running in windowed mode?

#

surprised Unity doesnt have it built in to force it to apply one in these circumstances

spare island
#

well "Fullscreen Window" should literally be taking up the whole screen

#

You shouldn't be able to see behind the app

#

unless you press the windows key to show the taskbar

surreal blaze
#

yes

spare island
#

If it's borderless, there's no border

surreal blaze
spare island
surreal blaze
# spare island It didn't but thats what fullscreen window means

bool isWindowed = selectedProperties.selectedDisplayModeIndex == 1;

        if (isWindowed)
        {
            // Reduce size slightly to ensure it's not interpreted as borderless fullscreen
            int windowedWidth = Mathf.Clamp(selectedResolution.width, 800, Screen.currentResolution.width - 120);
            int windowedHeight = Mathf.Clamp(selectedResolution.height, 600, Screen.currentResolution.height - 120);

            Screen.SetResolution(windowedWidth, windowedHeight, FullScreenMode.Windowed, selectedResolution.refreshRate);
        }

this results in no resizable window. even with max window selected as the startup mode.

spare island
#

Especially if you're trying to do custom window styles

upper pond
#

Do you guys think that you should use the VR package for unity(openXR) or just create your own scripts for tracking/inputs? Navigating and reading the openXR package contents is confusing as hell

night harness
#

Doing some weird shit, How can I use a Type in a generic function?

#

Is it not possible because it's not a hard definition?

leaden ice
#

The short answer is "the same way you use it anywhere else"

night harness
#

I've got a class line of inheritence that uses generics and they need a static initialization function to run in the context of the defined generics

I know I cant use RuntimeInitializeOnLoadMethod directly to call this because generics aren't a compile time constant, but generic these classes are type constrained to is a compile type constant, so I wanted to use reflection to find all of those constrained classes and use them to find the static generic class im looking for

leaden ice
night harness
#

This is kind of the vision

            Type contentType = typeof(ExtendedContent);
            foreach (Type type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()))
            {
                if (type.IsSubclassOf(contentType))
                    ExtendedContentManager<type>.CoolStaticFunction();
            }
leaden ice
#

Ok you're trying to use reflection here. Reflection is runtime type resolution. Generics are compile time type resolution

#

You would have to make a version of CoolStaticFunction that takes a Type parameter

#

or you would make a static function that returns one of the generic types given a Type parameter

#

Or you would use Reflection here to resolve the apropriate generic type

night harness
#

oh fuck yeah im being really dumb thank you

#

I can totally just use the type directly, was overthinking this

#

For context I'm doing this so I can make an actual instance of each of these generic managers to avoid all this weirdness

#

so gameobject stuff is happy to take that

#

ty for the knowledge aswell

leaden ice
#

A code generator might be a good solution here too

#

you could write a code generator that loops through all the subtypes and generates code that explicitly calls them all like:

ExtendedContentManager<Apple>.CoolStaticFunction();
ExtendedContentManager<Banana>.CoolStaticFunction();```
night harness
#

This is for a[THING I CAN'T TALK ABOUT HERE] so trying to future proof this in the event some of these classes are implemented outside of the scope of my stuff but I totally get how that may work otherwise

odd creek
#

I have a c# question - is it possible to constrain generic types to delegates for the purpose of using them for events? Like I'm trying to do

class Foo<T> where T : Delegate
{
  event T MyEvent;
}

Is it possible to do this with generics or would reflection be needed?

night harness
# odd creek I have a c# question - is it possible to constrain generic types to delegates fo...

You might want something like this where instead of the event itself being generic you kinda middleman it with a delegate implementation

public delegate void GenericEvent<T>(T param);

public class ExtendedEvent<T>
{
    private event GenericEvent<T> onParamEvent;

    public void AddListener(GenericEvent<T> genericEvent)
    {
        onParamEvent += genericEvent;
    }

    public void Invoke(T param)
    {
        onParamEvent?.Invoke(param);
    }
}
odd creek
#

Ah nice, yeah that's probably fine

#

Thanks!

leaden ice
# odd creek Ah nice, yeah that's probably fine

This is also an option but it gets tricky because we sort of lose compile time checking on the argument types for Invoke:

        class Foo<T> where T : Delegate
        {
            private T _myEvent;

            public void AddListener(T listener) {
                _myEvent = (T)Delegate.Combine(_myEvent, listener);
            }

            public void RemoveListener(T listener) {
                _myEvent = (T)Delegate.Remove(_myEvent, listener);
            }

            void Invoke(params object[] args) {
                _myEvent.DynamicInvoke(args);
            }
        }```
#

Plus you don't get to use the nice +=/-= syntax for adding and removing listeners

night harness
#

didn't know people prefered that

odd creek
#

I'ma give that a try

night harness
#

Not that it's necessary in the context of your question but just a consideration is with these kinda "wrapper" events you can also potentially utilise the constructor to communicate with some static manager that can assist with correctly clearing static usages of these events when you have scene domain reload disabled

#

in the event that's ever relevant to you 😛

odd creek
leaden ice
#

It is not type safe

#

It will give you errors if you pass the wrong arguments, but only at runtime

#

that's what I meant by "losing compile time checking on the argument types for Invoke"

odd creek
#

🤦‍♂️ totally missed that my bad

rancid frost
#

@leaden ice It was the resolution, however, seems webgl react doesnt allow you to mess with it directly,

you have to set a property called devicepixel ratio

    <Unity
      unityProvider={unityProvider}
      style={{ width: "80%", height: "80%" }}
      devicePixelRatio={devicePixelRatio}
    />
sharp juniper
#

I'm trying to make a level editor and I'm trying to use the scene serializer but when I load the scene all the items in the scene loose their mesh and materials. Right now I'm using the basic unity models and materials how can I fix this issue

steady bobcat
sharp juniper
#

all I'm doing right now is just instancing some blocks and then saving them with a key code down. I'm not recording any changes and I'm not setting anything to dirty

steady bobcat
#

When modifying a scene or prefab in edit mode you need to set things as dirty/use undo to ensure the scene is marked as dirty so it can be saved with your changes.

sharp juniper
#

oh I'm saving it in play mode

steady bobcat
#

er that wont do shit

#

you cant "save" a scene at runtime with unity serialization, needs to be manually done yourself

sharp juniper
#

so I jsut set up a list kind of of each objects position, scripts and stuff and then save them in a json script then load them by creating that prefab and give it its variables

steady bobcat
#

If you can correctly store and reload this data is should work fine.
Depends how you record material and restore it later, resources/addressables is the way to go there

sharp juniper
#

So for addressables would it be able to upload stuff during runtime and save it as an addressable or is that out of the question?

steady bobcat
#

not possible you cannot create an asset at all at runtime and make something addressable post build

sharp juniper
#

ok thanks for the help

urban torrent
#

Is there like a Unity programmer expert who can help me with one thing I want to achieve in my game?

Problem

  • I have bunch of humanoids that have their own Animator with states and animations
  • When the battle ends, I want to play 1 random victory animation out of 8 possible ones.

I would love to hop on Google Meet and show you my code and learn how this can be done.

night harness
#

these look like good starting points

urban torrent
#

Oh I just got an idea. Rather than trying to do it all in the script, maybe I can just add all animation clips to Animator with different triggers. And then jus pick the random trigger in the script.

last quarry
hot swallow
#

i just want to have it be able to orient around slopes and rotate where it goes but it aint working as i need it to 💔

mellow sigil
#

Because one script tries to rotate it based on the slope and the other tries to rotate it based on movement and nothing that would combine them or resolve which one to use

hot swallow
#

it is probably the method im using to combine them which causes the problem

hot swallow
#

i figured it out

hardy pasture
#

Can someone on the latest Unity version check what NUnit version is installed?

hot swallow
gentle terrace
modest mantle
#

Hey, does anyone have a good linting extension for C# they use? Feels like I make a bunch of namespace errors all the time, that an extension would catch

somber nacelle
#

!ide

tawny elkBOT
craggy breach
#

hello. lampMaterial.SetFloat("_EmissiveIntensity", 0); its why not work correctly? im change the emissive intensity but its changed only the inspector, the graphics not modified

thin aurora
peak peak
#

I posted my question that is related to both 2d and coding in #🖼️┃2d-tools, is it ok to crosspost here?

rustic prawn
#

Hey guys i have a question about a open world or something like that i did the procedurally generated world but i have no idea how to put a village in the middle.
can anyone tell me an idea how to solve it? :d

little meadow
#

Make the proc gen thing also create villages, then find one and move it to "the center"... oooor after the proc gen is done clear an area in the center and add the village there

limpid cave
#

hello, i have made an miniMax AI algorythm for chess but i have optimisation issue i cant have an depth more than 3 if someone have tips for optimisation or if you see any issue on my code:

https://pastecode.io/s/8difcvhc

ionic grove
#

Hey guys - Does anyone know why this _pi.readyImage doesn't get set to active? I am logging out the activeInHierarchy attribute before and after doing the .SetActive(_isReady) (and _isReady gets set to true), and it shows in the console that it's changing. I've confirmed it's the correct GameObject as well.. Any ideas?

public PlayerInfo AddPlayerCard(string _steamName, bool _isReady = false)
{
    // Instantiate player card and put in player list
    PlayerInfo _pi = Instantiate(playerCardPrefab, playerFieldBox.transform).GetComponent<PlayerInfo>();

    print("PI Ready Image activeness BEFORE: " + _pi.readyImage.activeInHierarchy);
    
    // Assign name
    _pi.steamName = _steamName;
    _pi.isReady = _isReady;

    // Make image active based off ready status
    _pi.readyImage.SetActive(_isReady);
    
    print("PI Ready Image activeness: " + _pi.readyImage.activeInHierarchy);

    return _pi;
}
thick terrace
ionic grove
#

Here is the PlayerInfo object

thick terrace
#

if it's true at the point that log happens, it seems like something else must be changing it back afterwards

ionic grove
vestal arch
soft shard
ionic grove
#

Ahh, nope you're right. I can take that off. Cool, thanks 🙂

somber nacelle
#

no, it returns the type of object you pass as the first parameter. So if you pass a reference to a PlayerInfo component it will clone the gameobject that component is attached to and return a reference to the PlayerInfo component on the newly instantiated gameobject

worldly stirrup
#

Although this works most of the time, in cases like these, where the raycast first touches the slope and the body lerps to that new rotation, the raycasts are still getting new positions, and the body lerps to those rotations as well, causing this jittering.

#

Any way I can fix this?

#
    {
        Debug.DrawRay(_castPosition.position, -pb.transform.up * _raycastDepth, Color.blue);
        RaycastHit2D _terrainHit = Physics2D.Raycast(_castPosition.position, -pb.transform.up,
            _raycastDepth, _terrainLayer);
        if (_terrainHit.collider != null)
        {
            point = _terrainHit.point;
            normal = _terrainHit.normal;
            if (dirWall == 1)
            {
                Debug.Log(normal);
            }
        }
    }``` Raycast function
#

(dirWall part is for logging the normal and documenting this bug)

#
    {
        _currentInput = Input.GetAxis("Horizontal");
        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Vector3.forward, -Vector2.Perpendicular((f1.point - f2.point).normalized)), Time.fixedDeltaTime * rotSpeed);
        transform.position = Vector3.Slerp(transform.position, (f1.point + f2.point) / 2 + -Vector2.Perpendicular((f1.point - f2.point).normalized)* bodOff, Time.fixedDeltaTime * posSpeed);
        _rb.linearVelocity = transform.right * _currentInput * _movementSpeed;
    }``` body rotation and positioning function
granite charm
#

hi i have a question about statemachines. i've noticed that many jump states exit to a fall state, usually when velocity.y < 0, and the fall state is linked to the locomotion state, usually when the player is grounded. however, the issue is when for some reaosn after jumping, the player returns to the ground immediately, such as one jumping up a slope or onto a higher level. In this case, the player never transitions to the fall state and is stuck in the jump state. I was wondering what the workaround for thsi would be?

cosmic rain
granite charm
#

im talking about a fsm in code for a player controller script. the issue i notice when doing that is that the player is still grounded for a couple frames after transitioning into a jump state and will immediately transition into locomotion state.

#

ive thought about setting a timer after jump is entered but that feels kind of spaghetti and surely theres a better way

solid tusk
#

How do I spawn another Same gameobject with same transform after attaching parts. Example I have a Body gameobject, I have parts which is their children I attached them It moves away. Now I want another copy of the body to spawn. Do I use instatiate?

#

ok

cosmic rain
#
  • Have extra "transition states" that signify that the character is in the middle of transition and provide conditions for when the transition is complete. While in transition, prevent initiating new transitions.
brazen nest
#

Hey, I was curious how you guys handle errors well, sometimes I write code for a specific use, and don’t think about every single possible interaction it could have with other pieces of code, if it’s used in multiple ways, and this leads to some errors occasionally.

Just curious how you guys deal with this effectively, try catch blocks, etc.

soft shard
# brazen nest Hey, I was curious how you guys handle errors well, sometimes I write code for a...

Personally for me, unless im doing a "band-aid solution" I try to avoid try-catch blocks as they are more like "I donno how to deal with the problem so im just going to pretend it doesnt exist" (though there are some unavoidable cases like if your getting certain error codes from API server requests you cant control) - though I found using code patterns helps keep consistency with how other scripts could interact with what im building, then I usually just have to code within those patterns, I also try to separate my code with a namespace and a "System/Base" folder (as I like to use inheritance often) and a "Feature/Implementation" folder to minimize what actually needs to know about the specific code to begin with and makes it easier to isolate and test the code in those use cases, then the rest I often bridge with events (though they need to be carefully managed) which lets me also keep track of the order things are happening for logging/debugging in a build, thats just my personal workflow though, many ways to skin a cat

brazen nest
#

I have so many scripts, so much code for pretty basic stuff due to netcode and the interactions sometimes are annoying to deal with, right now I’m creating a developer console so I can print info to console to debug network stuff, and error handling console input is frustrating

night harness
#

Mods can let me know if this isn't okay to suggest but one thing I've found really handy when testing multiplayer builds is a project called UnityExplorer by sinai-dev. It's a runtime based inspector tool that was originally made for modding related stuff but is really handy when your in build and want to quickly and directly check certain fields and values. good debugging implementations help a ton aswell but this has saved me a lot of time

soft shard
night harness
#

If a scriptableobject asset is built to where its exclusively referenced by a scene, you load the scene, reference the SO outside of the scene, unload the scene and load the scene again, does Unity know to re-use the original still in memory reference?

soft shard
little meadow
#

And there are situations with Addressables and Resources where it might also happen to have separate instances of the same SO.

brazen nest
odd creek
#

Is there a way to serialize a reference to an interface? Like I've got a super simple IAttacker interface, and a serializeable IAttacker[] attackers field that I want to populate in the editor - is there any way to set that up? Tried doing [SerializeReference] but it didn't seem to work

night harness
odd creek
#

OO nice perfect!!

night harness
#

Haven't used it before but i've used their dictionary implementation quite often

odd creek
#

Ah that sounds nice, I did a homemade thing to mimick dictionaries by just having an array of a custom serialized tuple class and it is sooooo scuffed lol

night harness
#

yuup

leaden ice
calm silo
#

Is there any format like :N but that shows doubles with "integers" w/o decimals?
Eg, 1 as 1 and not 1.00 but still shows 1.002 as 1.002?

naive swallow
small schooner
#

@calm silo try this format Debug.Log(value2.ToString("0.###"));//Max 3 decimals, no trailing zeroes the # as much as many numbers after dot you want to display

calm silo
simple egret
#

The number you put after the "F" is the number of decimals yep, you can put as much as you want

#

You'll get zeroes if there are less decimals to display, and it'll round if there are more

small schooner
brazen nest
#

Is there anyone in here that has experience creating a large multiplayer game, that could hop in a discord call with me and help me organize my scripts and logical flow.

#

I wouldn’t take much of your time at all

little meadow
#

if you're making a large multiplayer game, I'm sure hiring a consultant would be a non-issue 😛

vagrant blade
#

Large multiplayer and not taking much time are complete ends of the spectrum.

brazen nest
#

Its not large, it's small, but the netcode makes the number of scripts large lol

soft shard
edgy ether
#

small question,
using Unity's Random, is it possible to make an instance of that like System.Random?

plucky aurora
#

am i doing something wron in my script?
using unity 6 URP but the texture won;t assign

cosmic rain
#

It doesn't seem to be unity API. So your question doesn't make sense.

plucky aurora
#

well this is an unity bug u can't assgn normal or ao via script but manually u can

#

i was working on making the script assign materials but only works on height and base

edgy ether
peak peak
#

What is a good way to log stuff so that I can read it when Unity gets stuck after some deadlock or infinite loop and I have to kill it? I want to write to a .txt file or a console, something like that.

leaden ice
#

The code will never do anything other than executing the loop

peak peak
#

but I cant see it because the editor is stuck

#

So the Debug.Log's are useless

leaden ice
#

Indeed

#

The best solution is to simply not have any infinite loops in your code

merry forge
#

this is probably not the right place to ask, but I can't find that place, so:

is there any shortcut in the Scene view to drag an object while simultaneously making a copy of it?

quaint rock
#

not in that exact same way

#

ctrl+d should duplicate the selection then select it, then you can drag that

#

but nothing exactly like the shift+drag 3ds max uses

green dirge
#

Anyone can help me in #🏃┃animation ? Pleaseeee 😭😭😭😭😭 (Sorry for my bad english)

last quarry
#

Which is highly superior anyway (if properly seeded)

#

UnityEngine.Random has a tendency to give the same result 8 times in a row

edgy ether
#

well i was planning to use System.Random since i wanted to separate instances of random without the generations effecting another

#

but i am curious about mathematics.random, i never heard of thisbefore

last quarry
#

It’s from the DOTS mathematics package

novel parrot
#

is there a simple way to modify an existing plane's resolution ? Ive been playing around with modifying the mesh but looking at the wireframe, a hill would look choppy due to the vertices/triangle count. And it looks like the vertexcount is a getter only, not a setter

last quarry
vestal arch
last quarry
#
private void Start() { Debug.Log(Random.Range(0, 10); }

Put this somewhere and run your game a few times 😅

#

It's not the same result every time but it clusters like crazy

#

I now use Mathematics.Random, seeded by DateTime.Now.Ticks which gives good randomization. For some things I serialize the seed so it's deterministic.

vestal arch
mellow sigil
#

also the forum post is unrelated

modern epoch
#

can i have ontriggerenter and oncollisionenter in the same script? because it's not triggering the collisionenter

hexed pecan
modern epoch
#

yes

#

i unchecked trigger in capsule collider

#

and it has a rigidbody

#

he attacks but my player cant attack him

#

his oncollision works but my player's doesnt

hexed pecan
modern epoch
#

ah i think it's my layering

vestal geode
#

I do recall randomness was broken in some version for sure

#

This is 6.0.32

modern epoch
vestal arch
#

you tell us what the issue is lol

#

need some context

modern epoch
#

my boss guy is a non trigger collider

#

my weapon is a trigger

#

the weapon has a script with ontriggerenter/exit2D and oncollisionenter/exit2D

#

i put debug.log in the collisionenter

#

but it never gets there

#

does the pixel layer order matter?

#

all the object layers are on the same layer: foreground

#

if nothing works im gonna rebuild my boss

#

because the normal enemies are working fine

#

perfect

#

when my main char glitched, i had to rebuild him

#

THE BIGGEST pain in the ass but it fixed the issue

vestal arch
modern epoch
#

reeeeeally

#

omg

#

why???

#

i need the weapon to overlap

vestal arch
modern epoch
#

how

vestal arch
#

OnTriggerEnter2D, for example

#

you're already using them

dusk apex
modern epoch
#

ok it triggered

#

so the ontriggerenter is actually referring to the object it's attached to?

hexed pecan
#

If either of the objects have a trigger collider, OnTriggerEnter will be called on both objects

weary horizon
#

i made laval tilemap and i wanted to draintime everysecond he stands still there or he move , but its like when he moves then only time drain can somone help me fix that


public class LavaDamageZone : MonoBehaviour
{
    [SerializeField] private float lavaDrainRate = 3f; // time lost per second

    private void OnTriggerStay2D(Collider2D other)
    {
        if (other.CompareTag("player"))
        {
            GameManager.Instance.ReduceTime(lavaDrainRate * Time.deltaTime);
        }
    }
}```
my current code
dire pelican
#

What's best, that I find prefabs at runtime through Resources.Load() or should I save it as a serializable variable

#

actually in general, what are some guidelines for runtime vs serializable variables?

robust dome
#

Easiest and savest way is to use serialized fields

dire pelican
last quarry
#

Ok and?

dire pelican
# last quarry Ok and?

I'm new to this stuff, I just don't know what's right/wrong yet because I haven't gotten to the point in a project where past me's dumb mistakes are forcing me to rewrite a ton of old stuff ¯_(ツ)_/¯

#

thanks though

soft shard
# dire pelican I'm new to this stuff, I just don't know what's right/wrong yet because I haven'...

Personally, as a beginner I would say not to focus too much on over-optimizing problems you havnt ran into yet - using a serialized field gives you a direct reference to the asset/object which is generally always better, and sometimes scripts will have lots of variables depending on what it does, but sometimes lots of anything can be a sign that you might be over-engineering a problem (ie: using more variables than you might need for the script to work) - also refactoring (rewriting code) is something that will always happen as you learn more and try different ways of solving different problems, at some point using code patterns can help to some degree but youll always be refactoring some part of your game

dire pelican
#

thanks

soft shard
#

One note I see with having a lot of variables (and it does depend what the variables are), is often they can be converted to a collection - say your making a waypoint system with 5 points, its often better to have a list as 1 variable that holds 5 elements instead of having 5 variables for each waypoint

delicate ravine
#

what could be the reason for agent.remainingDistance returing 0 even though the destination is not same as the transform.position

lean sail
# dire pelican What's best, that I find prefabs at runtime through Resources.Load() or should I...

yes serialize fields is better but also resources should just be avoided when possible. consider this, with resources how do you expect to find prefabs?
you would have to do it by string and rely on the prefab being in a very specific folder. How do you know which string to provide from a given script? You would probably serialize this string (might as well serialize the prefab) or hardcode it.
Even a unity learn page says best practice is to not use it https://learn.unity.com/tutorial/assets-resources-and-assetbundles#5c7f8528edbc2a002053b5a7

lean sail
delicate ravine
#

oh, is there any way to check if path has been calculated

lean sail
#

theres a few more related fields on that page too like hasPath, pathStatus, or also just getting the actual path and seeing where it's trying to move. Maybe it cant move anywhere

delicate ravine
#

i thing the path not yet calculated is the reason. will do that check and see if its fixed

ashen remnant
#

public class FoodSystem : MonoBehaviour
{
    public FoodDropoffs food_Script;
    public GameObject[] food_Dropoffs;
    private int currentDropoff;
    private bool AbleToDropFood;
    GameObject FoodDropoffObject;

    // Start is called once before the first execution of Update after the MonoBehaviour is created

    private void Start()
    {
        for (int i = 0; i < food_Dropoffs.Length; i++)
        {
            food_Dropoffs[i].gameObject.SetActive(i == 0);
        }
    }
    public void Food_Dropped()
    {
        if (AbleToDropFood == true)
        {
            Debug.Log("Food has been dropped");
            food_Script.food_Dropped = true;
            Destroy(FoodDropoffObject);
        }
        else
        {
            food_Script.food_Dropped = false;
        }
        
    }

    // Update is called once per frame
    void OnTriggerEnter2D(Collider2D collider)
    {
        if (collider.CompareTag("Food Dropoff"))
        {
            Debug.Log("Able to drop food");
            AbleToDropFood = true;
            FoodDropoffObject = collider.gameObject;
        }
        else
        {
            Debug.Log("Unable to drop food");
            AbleToDropFood=false;
        }
    }

    private void Update()
    {
        if (currentDropoff < food_Dropoffs.Length && food_Script.food_Dropped == true)
        {
            currentDropoff++;
            if (currentDropoff < food_Dropoffs.Length && food_Script.food_Dropped == true)
            {
                food_Dropoffs[currentDropoff].gameObject.SetActive(true);
            }
        }
    }
}
#

Essentially, Im making a script where once you click a ui button at a specific item, it destroys itself and you move on to the next item. problem is i want it one by one but as soon as i destroy the first item, it enables every single other item. any way how i can change that? im stumped on any reason why it happens

mellow sigil
#

You have to set food_Dropped back to false after enabling one item

#

although it would be better to not have that in Update at all but in an event or a function that you call when needed

ashen remnant
#

thank you, will try to implement tomorrow

#

much love

leaden ice
#

What does " make the camera 2.5d" mean?

#

There is no prescribed way a camera should be for a 2.5d game

#

2.5d just means that the gameplay takes place in two dimensions but uses 3d art, like smash Brothers

#

Just looks like an isometric camera

#

Which is just an orthographic camera looking at the game from a 45 or 30 degree angle

#

Forget which

#

Anyway none of this has to do with code

#

So you're in the wrong channel

fair pelican
#

Okay

vestal arch
hardy mulch
#

In unity 6 where did this info panel go? Is there somewhere to view it?

rigid island
hardy mulch
#

Ah, thanks

hardy mulch
#

In Unity6 is there a replacement for setting a RigidBodies linear velocity? I understand it's UB with physX, however is there a "correct" way to do rb.linearVelocity = velocity; And if there's not, is there at least a way to disable this warning?
setting linear velocity of a kinematic body is not supported

Apparently in PhysX this is an outright error/return https://github.com/NVIDIAGameWorks/PhysX/blob/4.1/physx/source/physx/src/NpRigidDynamic.cpp#L230, however unity's PhysX version doesn't have those checks so doesn't throw that error and instead has a warning, according to this https://discussions.unity.com/t/kinematic-rigidbodies-no-longer-holding-velocity-property/868756/8, but it appears to work anyway, at least in my case, but id like to either do it the correct way or disable the warning.

That thread discusses various solutions to moving an object, however in my case im doing some custom physics and want to then set the velocity

leaden ice
#

It will work fine if you make it not kinematic

hardy mulch
rigid island
#

you're stuck with MovePosition + your own wall checks

hardy mulch
#

And that's just the 'correct' solution?

rigid island
leaden ice
cedar sand
#

Hi, i am trying to make a cannon which throw projectile like a arc. From initial point to above and fall to target. I have saw some animation curve examples. Is someone have any trick or idea how can i do this?

soft shard
cedar sand
proper pier
#

do you guys find yourselves using closures often? I don't know if its bad to use them instead of creating a class

lean sail
proper pier
odd creek
#

I'm not a c# or unity expert but I'd generally say closures are kinda messy, having functions which change stuff outside of its scope can be hard to debug, and if you really have to do that then containing it in a separate class could make it a bit cleaner, but honestly if it works it works

proper pier
lean sail
# proper pier In this class: https://hastebin.com/share/emeyicatut.csharp, I'm using closures ...

i see. Does this code actually work as is? Maybe im missing something but you dont seem to new that activeVFX ever.
Definitely make this into its own clas. Your code should be readable at the very least and this is pretty hard to understand at first glance, even while being well aware of how delegates/closures work. Ive never really seen someone intentionally use it like this.
This also does just generate a class for you containing the function and captured variables. So you might as well define it yourself and have it readable for others

proper pier
#

just fixed the new thing yeah thanks

lean sail
# proper pier ok thanks for the feedback

you can put code in sharplab and see how these classes are created for you. You would have to remove the unity stuff though so maybe just test it on a smaller example like this image

#

which is pretty much what your class is going to be

proper pier
#

oh thats cool, I didn't know c# actually generated a hidden class for closures

lean sail
#

Yea that's how it stores the value, because the scope of someValue or walking_VFX in your case ends pretty much immediately

hardy mulch
# leaden ice What are you trying to accomplish

Im running some custom physics on the rb, which includes setting the linear velocity. More generally im updating an old project from a 2020 unity version to unity 6 and this is one of the issues that came up

proper pier
#

I have to say I'm supprised closures aren't more widely used though; they're just so convient and fast to implement compared to defining a class, even though you trade off debugging, structure, and readability

#

maybe its not that suprising lol

soft shard
lean sail
#

overall, 10/10 for the emotional rollercoaster i went through seeing this code

proper pier
proper pier
lean sail
# proper pier just curious because I'm trying to work on writing better code, was this code ha...

At the start i had to read fairly carefully to understand what you were doing. I wouldn't say its hard to understand for me, but its harder than it should've been. I'm used to being able to skim over code and get an idea of what's happening. its not common to write code like this, so i dont see it often and its hard to just skim over it and subconsciously get an idea of what's happening. That's even without the variable capture.
One thing that can be confusing is PlayWalkingVFX. you arent actually playing anything here. Its essentially just declaring that secret class and assigning it to the list

#

If we're talking readability for a small script, I wanna be able to understand it in like 30 seconds max. Especially without trying to remember how variables are captured

proper pier
#

it probably doesnt help that you're looking at one file in a multi part system

odd creek
#

If not, then even using an event listener rather than a list of funcs would be more readable I think

proper pier
#

thats a good idea

lean sail
# proper pier it probably doesnt help that you're looking at one file in a multi part system

True but i was focusing more on activeVFX during my initial readthrough. I also do fully understand the syntax and learned a good amount about delegates.
Part of it could just be experience. I'm sure some advanced people in here would be able to skim through that file and be able to understand exactly what happens faster than me. I'm sure a lot more people would ask u wtf is happening

#

You really dont need a coroutine or async there. A coroutine cant run on this object, its not a monobehaviour. Simply just making a class and keeping everything else the same would be pretty decent code imo

odd creek
#

Ah right, not a coroutine

lean sail
#

The coroutine could be started on another object but really its not needed either way

#

The current way is quite clear in that UpdateFrames method

little meadow
#

I'd also say that if you have 10 things potentially happening at once and managed in one place - those better not be coroutines. Figuring out what weird interaction between them causes a bug would be a nightmare.

proper pier
#

i already have a pipeline in place so i dont really need coroutine tbh

odd creek
proper pier
#

Actually dont worry about it lol, thanks for your time already

#

I think I get what ur talking about. The PlayWalkingVFX is the publicly exposed way to Play the walking vfx, whereas the controller as a whole is responsible for making it happen, which is def confusing at a glance

proper mica
#

Unity Animations Rigging. How can I get a bone's original position when using an IK target?

worn wing
#

I want to make an ImpactManager. The script will spawn a specific effect for a combination of surface and impact type, defined in a scriptable object. For example "Surface: Metal" and "ImpactType: Bullet" will result it "MetalBulletSparks" spawning.

My question is, what would be the best way (simplicity, ease of use and performance wise) to define/read a surface? First I saw a tutorial that somehow got the texture of the object it hit, but that system seems very performance intensive and doesn't make sense to me. Then I thought about using the material on the GameObject it hit, but then I realized sometimes colliders are separate from the visual GameObjects that hold the materials, so I can't always use that.

The only methods I can think of that could work is attaching an identifier to each collider, like a script with scriptable object. I also thought about giving every collider a physics material and use that to identify the type of surface, in that case I only need to get that and not the whole GameObject. But idk if giving every collider a physics material uses up extra resources??

So please let me know what you think is the best way to solve this problem, or are there any other standard ways that are commonly used for this?

little meadow
night harness
#

if your in a scenario were saving the getcomponent is of any real value eg.

worn wing
#

Howw big is GetComponent's impact on performance

little meadow
#

I assuemed that you'll need to get a component anyway... but if not - yeah, may not be completely out of the question, but still I'd rather not.

steady moat
night harness
night harness
worn wing
steady moat
night harness
#

eg. if you use an invisible collider on stairs

steady moat
#

Then you put your UV in the collider.

night harness
#

that seems like a kind of nightmare-ish workflow in a lot of usecases

steady moat
#

It is the most flexible.

#

You can have multiple surface type per object.

worn wing
steady moat
night harness
#

That seems potentially overkill for a lot of games, I guess it depends on the scale of the game

worn wing
steady moat
#

Potentially, I work professionnaly hence you do not have really a choice to have amore complicated workflow to cover every use case.

#

Otherwise you need to restrict yourself.

#

Which people usually are not really keen to do it

worn wing
#

I do love making scripts that are compatible with multiple usecases so I can reuse them in other games.

night harness
#

Forsure, Just with no disrespect at least in the projects i've worked on personally that wouldn't even be a considerable option knowing how tedious that would be

steady moat
#

To be fair, we use two method. GetComponent and UV read.

worn wing
#

I watched LlamAcademy's tutorial on this and I think he also used UV's, but that seemed very complicated, the comments also said this could cause performance issues? I'm making a VR game right now so I need to pay special attention to performance.

steady moat
little meadow
worn wing
worn wing
steady moat
night harness
#

components are a good basic bitch step

steady moat
#

So, you kinda need to already make a choice of if you want to support that or not.

little meadow
#

yeah, you cold make something that initially just works with GetComponent and that compnent knows the type, and later on if necessary you can expand said component to be able to handle the raycast thing (or move it behind an interface or so)

worn wing
steady moat
#

Do not overthink about it and just go for GetComponent

worn wing
#

Alright, thanks for the help guys!

placid summit
#

Anyone done custom cursors in webgl? Seems like you should be able to set to common cursors like hand (on button hover) but Unity just seems to have software cursor options

chilly surge
#

I don't work with Unity WebGL to know how to do interop, but it should be simply setting cursor on the element of interest (or even just the entire body).

drifting grail
#

I'm using unity fishnet and trying to set up some standard UI, my only issue though is whenever i start my server and client the max value of all my sliders shoots to 1e+07. This is really specific and i honestly have no clue what's causing it

#

I've just started working on UI and shouldn't have any methods that would mess with the values like that

rigid island
fathom geode
# leaden ice I would report it and see what they say

Update: I reported this, they got back to me, mentioned the change was first made in Unity 2023, and that it was undocumented but has been the intended behavior for a long time.

I can only assume this was for the sake of consistency across all components

odd creek
simple saffron
#

Anybody know how to make a state machine behaviour execute on every loop?

#

apparently just checking the time of it and setting a flag to false doesn't :/

#

oh, it looks like the normalised time just keeps increasing?

#

I thought normalised time would've reset to 0 after it finished playing but i suppose not

simple saffron
#

i neglected to check the docs for that bit

#

i have now fixed my issue

spare island
#

..\Engine\ManualDocumentCopier.cs(2,7): error: The type or namespace name 'Editor' could not be found (are you missing a using directive or an assembly reference?)

ManualDocumentCopier.cs(2,7) using Editor;

DirectoryCreator.cs: 4 namespace Editor

  • Namespaces match
  • No errors in IDE
  • ?: Unsure if compiled in the same assembly, they should be
  • MDC is in Assets/Editor
  • I've removed all #if UNITY_EDITORs but the problem remains, I've also tried wrapping them in #if UNITY_EDITOR , but that didn't work either.
  • Tried removing emoji name from scripts folder
steady bobcat
#

check the platforms selected for your asm defs

spare island
spare island
steady bobcat
#

Is Editor your own namespace? or did you mean UnityEditor ?

spare island
#

editor is my own namespace

#

I also tried Utilities.Editor

#

I haven't tried using a different name besides editor

steady bobcat
#

if using VS, regenerate your solution and double check if the error appears there too

#

remember that Assembly-Csharp cannot ref Assembly-Editor

spare island
steady bobcat
#

er id remove that emoji char from the folder 😐

spare island
#
Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' ---> System.Exception: Failed to resolve assembly 'Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' in directories: C:\Program 
spare island
#

I'll try renaming it and see

#

ok im not allowed to

steady bobcat
#

close the editor and do it via explorer

#

the compiler should accept unicode chars but sometimes these things go funny

spare island
spare island
little meadow
#

and also for the love of god, even if you're a non-believer
edit: I meant please no emojis in file names 🥲

steady bobcat
#

modern stuff is probably fine but older things will probably break

steady bobcat
# spare island didnt work

close editor, delete Library folder, then re open project (NOTE: will make all assets re import and will take a while!)

spare island
#

Hold on let me figure out how to rebuild solution in rider

spare island
steady bobcat
#

that proves then its something solve-able then

spare island
#

How do I check what assembly a script is in

#

oh wait

steady bobcat
#

Editor/ folder? Assembly-Editor
Any where else? Assembly-Csharp

spare island
#

Ok there we go

#

I moved the script out of the editor folder

steady bobcat
spare island
#

I guess I can't have that be an editor script because I need part of it to be in-build

#

I didn't realize putting a script in a folder named editor changes how its compiled

#

there's not really any indication its treated differently

spare island
#

we love magic features

steady bobcat
#

Its well known

cold parrot
spare island
#

Wait, it's any folder named editor anywhere?

spare island
steady bobcat
#

It only stops when the folder is inside an asm def

#

as there the assembly definition takes over

spare island
#

I assumed if it wasn't in the root it doesn't do anything special

#

I knew that the editor folder was special, I just didn't know that I wouldn't be able to compile if I referenced something in it while I'm in the editor

steady bobcat
#

anyway read the linked pages and it will make sense

spare island
#

even if I use #if UNITY_EDITOR

#

I did

steady bobcat
#

👍 thats it then

spare island
#

It does make sense, I just misunderstood how exactly it treats the folder

whole wyvern
#

this block of code is meant to make an ai move snappily in a either a forward right or left direction, but the ai is moving forwards and backwards extremely quickly, is this because theres no time limit on the loop? how do i go about fixing this

steady bobcat
#

your loop rn just completes so the end transform position set is what you see

whole wyvern
#

surely this isnt ideal

#

do you think i should use triggers on where i want it to turn instead?

#

then it would only need to run once

steady bobcat
#

How do you call this function then? Update()?

whole wyvern
#

yep

steady bobcat
#

you can setup a time delay there or use a coroutine/async func to delay the calls to this

#
float delay;
const float TimeDelay = 0.25f;

void Update()
{
  delay -= Time.deltaTime;
  if(delay <= 0f)
  {
    PassiveMovement();
    delay = TimeDelay;
  }
}
#

example for doing it via Update(). We count down and when the timer is <= 0 we do the thing and reset the timer.

whole wyvern
#

ah i see

steady bobcat
#

An alternative is to record Time.time and check if enough time has passed (often better for input related delays)

whole wyvern
#

cool