#archived-code-general

1 messages · Page 406 of 1

heady iris
#

I would avoid having concepts like "Pistol" in your code at all

gritty jacinth
#

but only like 5 different types so the switch statement will have 5 items

mighty juniper
#

anyone?

heady iris
#

is a pistol genuinely that different from a rifle?

gritty jacinth
heady iris
#

what is offset?

mighty juniper
#

just a vector for how far infront of the camera i want them to be

#

in this case its (0,0,1)

steady bobcat
heady iris
#

instead of being world +Z

dusk apex
#

That's quite a lot.. maybe consider using inheritance if you're not certain as well. You'll be able to add more without having to constantly modifying working scripts (potentially creating more bugs). It's more difficult to imagine (relative to complexity) but can isolate new modifications or reduce the need to modify already working behaviors.. which can improve the debugging process.

mighty juniper
heady iris
#

transform it

#

transform.TransformDirection(offset)

mighty juniper
#

I'll give it a go, thanks

gritty jacinth
steady bobcat
#

if its scriptable objects each "gun" can be a new so with different settings

#

do whatever as long as its not weird switch statement hell

dusk apex
heady iris
#

Every kind of gun does roughly the same thing: fire zero or more of some kind of projectile at some rate.

heady iris
#

If that's only needed so you can put the weapons into different categories, then an enum is okay (I'd prefer a WeaponClass scriptable object, though!)

gritty jacinth
# dusk apex You've ask, folks have critiqued. There isn't a "right" way but having a large s...
public enum WeaponSlot
{
    Fist,
    Melee,
    Handgun,
    SMG,
    Shotgun,
    AssaultRifle,
    Rifle,
    MachineGun,
    Heavy,
    Projectile
}
public enum WeaponType
{
    Melee,
    Gun,
    Projectile
}
public class Weapon : ScriptableObject
{
    public string displayName;
    public WeaponSlot slot;
    public WeaponType type;
    public float dmg;
    public float rate;
    public int animationLayerID;
}

public class WeaponManager
{
    private Weapon currentWeapon;
    public void ExecuteUse()
    {
        switch (currentWeapon.type)
        {
            case WeaponType.Melee:
                MeleeLogic();
                break;

            case WeaponType.Gun:
                GunLogic();
                break;

            case WeaponType.Projectile://Grenades etc
                ProjectileLogic();
                break;
        }
    }

This was my original plan

heady iris
#

you could then put a name, description, and icon into that WeaponClass asset

steady bobcat
#

See why not give Weapon public abstract void DoLogic() and call that 😐

gritty jacinth
#

you can add guns all day and dont need to change code

gritty jacinth
#

there are 3 weapon types

#

not 30

steady bobcat
#

WeaponManager doesnt need to know what the weapon does, only needs to know how to tell any weapon to execute its stuff

heady iris
#

If you have fundamentally different kinds of weapons, that's where different types start making sense

dusk apex
mighty juniper
steady bobcat
#

If its just you and you know whats going to happen in future then so be it.
Its not good when others need to maintain something in future. I have needed to refactor some "strange" code and that takes extra time, effort and creates bugs.

heady iris
#

!code

tawny elkBOT
heady iris
#

what is "followTarget", anyway?

#

does that represent the player?

#

or is it the player's controller?

mighty juniper
heady iris
#

okay, so the target position is:

  • the position of your hand (from actions["Position"]) -- I think that's measured relative to the VR player's playspace?
  • the world space position of the camera
  • the offset, which pushes it forwards away from the camera
#

I suspect the first one is the issue

mighty juniper
heady iris
#

How are you rotating?

#

are you physically turning around in your room here?

#

wait, silly question

#

you are not doing a barrel roll lmao

mighty juniper
#

lol

heady iris
#

That's going to be your problem.

mighty juniper
#

I'm rotating with AddTorque() on the player's rigidbody

heady iris
#

You need to transform that position into world space (correctly including how the player has been moved, rotated, and scaled)

#

hmm...I'm actually not quite sure what to do about that

serene stag
#

Are you using unity 6 for xr rotation.

mighty juniper
mighty juniper
heady iris
#

Actually, if you're moving the entire XR origin around in game, then it's simple

#

transform your position with it

#
whatever.TransformPoint(inputPosition);
serene stag
#

It gives odd results like that try using unity 2022

heady iris
#

i don't think that's very useful advice

mighty juniper
heady iris
#

I guess you could just transform the point with the player's transform, then

#

That will turn it from a local-space point for the Player to a world-space point

serene stag
heady iris
dusk apex
#

You could probably rephrase this question:

Should I use a switch for determining whether a melee or range attack was used or add an additional layer of inheritance to not need this small selection
I had thought the switch held your guns initially. A selection of three is fine.

heady iris
#

If the player walks 3 meters to the right, their hands will also be about 3 meters to the right

mighty juniper
heady iris
#

It would be incorrect to transform [3,0,0] with the player's Transform (which would give you [6,0,0]

heady iris
mighty juniper
#

oh as in transforming it to a relative direction instead?

heady iris
#

No, transforming the point

#

transform.TransformPoint(...) will turn a local-space point for transform into a world-space point

mighty juniper
#

ah right im with you

heady iris
mighty juniper
heady iris
#

the entire XR Origin object moves when your headset moves around? that sounds wrong

mighty juniper
#

yeah i didn't think it did, but i did a quick google that told me otherwise, let me test real quick, i've never seen it moving personally

heady iris
#

The origin represents the center of your playspace, and input tells you where the controllers are relative to that origin

#

Does the player ever move around without actually moving in real life?

mighty juniper
#

yeah it doesn't move, you're right

heady iris
#

e.g. can you float upwards?

mighty juniper
heady iris
#

are Main Camera, Left Hand, and Right Hand being driven by your headset and controllers?

#

I'm trying to figure out which parts are actually moving here

mighty juniper
# heady iris are Main Camera, Left Hand, and Right Hand being driven by your headset and cont...

Camera is moving and rotating using a built in unity script, and when i move/rotate my head in real life, that's the position that gets updated. Hands are using the Vector3 obtained from the input system, which is their relative position to the XR origin. I realise that in moving myself physically my camera can escape from my model, but i plan to fix that later, and i don't believe that's an issue here, but i may be wrong

heady iris
#

I think that ~is~ your issue here

#

The camera doesn't care about whatever is happening to Player

#

It's just trying to position itself relative to the XR origin

#

(moving the XR origin should cause your viewpoint to move around in game)

#

So as you translate and rotate the player, nothing actually happens to the world-space positions of the camera or the hands

mighty juniper
#

RIght, i see what you mean. Should my player model and rigidbody, etc be a child of my camera then instead of the other way around?

heady iris
#

I've only ever dealt with moving the player non-physically, which I achieved by moving the entire origin

#

I'm not quite sure how I'd deal with rotation as well

#

I'd ask about that in #🥽┃virtual-reality . Someone with more experience might have better ideas.

You need to move the camera and hands into the right spot in the world after both translating and rotating the player.

#

I haven't got any clear ideas off the top of my head -- it always winds up getting too complicated to be correct

mighty juniper
heady iris
#

Does the player's movement cause the rigidbody to move and rotate?

heady iris
mighty juniper
#

i suppose, i could have an empty object as a child of XR origin but a parent of everything else that could adjust itself based on my camera's position, and then i wouldn't have to worry about moving the camera itself, and everything else would move along with it, maybe that would work?

swift falcon
#

What is the purpose of == operator when .Equals exist? If i override Equals should i override == too because it is called equality operator?

#

Is there any reason to make them behave differently?

leaden ice
#

If i override Equals should i override == too
Not necessarily, but often, yes.

swift falcon
swift falcon
#

This is weird that c# allows different behaviour for == and equals

leaden ice
#

Well HashCode and Equals are the things that are used for collections like HashSet or Dictionary (by default at least, assuming you don't provide a custom comparator).

I think it's pretty common to define HashCode and Equals for a class so you can use it in collections and then not define a == operator at all because you don't foresee checking equality in your own code ever.

#

== can also be defined differently for different operand types

#

.Equals() always takes an object parameter and therefore there can only be one of them basically.

#

Well you could define a .Equals with a different param type but it wouldn't get used in collections.

quartz folio
#

Surely collections use the typed one you declare with IEquatable<T> IEqualityComparer<T>

swift falcon
leaden ice
#

nah it's quite common

leaden ice
swift falcon
leaden ice
#

of course you could always use object.ReferenceEquals

leaden ice
swift falcon
leaden ice
#

and that's why C# lets us provide custom implementations for these things.

#

In some cases, that may be giving you enough rope to hang yourself, but isn't that part of the fun?

swift falcon
#

Is there a good c# book/source/paper/documentation which provide guidance on == and equals?

cosmic rain
#

The manual perhaps?

swift falcon
cosmic rain
#

For me, == would usually be reference equality and .equals member wise equality if I'm gonna define these myself.

#

Which I wouldn't in 99.9% of cases.

swift falcon
cosmic rain
#

But you can just define separate methods for MemberwiseEquals if you really don't like the idea. As I said, it's a preference/convention.

swift falcon
#

Hmm thanks everyone, in that case i need to make decision on whether i should treat == as equals or reference equals

cosmic rain
#

The simpler you keep it, the better it is.

#

If you can't decide how to treat them, you probably don't need to redefine them anyway.

leaden ice
swift falcon
#

Oh nvm i finally found the guidance about == and equals on microsoft learn

leaden ice
#

Can you share with us? I'm curious what they say.

swift falcon
#

It basically says treat == as equals for value type, and for reference type, in most case don't override the ==

leaden ice
#

sounds about right

#

When I see == I generally assume it's reference equality for reference types

#

If you want value equality on a reference type it's probably best to just make a separate method.

fiery spruce
#

Anyone know a way to pass an arbitrary math formula to compute shaders?

Only way I could think of is interpreting a string but that requires a lot of steps, not impossible just really annoying

leaden ice
fiery spruce
#

Yeah

leaden ice
#

interesting idea.
I have no idea how you'd do that tbh.

fiery spruce
#

Can’t really interpret it in cpu cause variables like x and y would be different in gpu each thread

cosmic rain
#

The only way I can think of is code gen a compute shader around that formula and compile it at runtime.

hexed pecan
#

Maybe you can pass in an array of structs that represent binary operations?

fiery spruce
cosmic rain
fiery spruce
#

Like just make a new file and write to it?

#

Is there a way to compile it if you do that?

leaden ice
cosmic rain
#

If you had access to the unity source code it would be possible to implement it. Wether it would be reasonable or not is a different question.🤔

fiery spruce
#

unity? Open source? Ahaha

cosmic rain
#

You can get it with enterprise license 🤷‍♂️

#

But yeah, I guess what Osmal suggested is the most reasonable way so far.

fiery spruce
empty elm
#

Can someone help me understand the warning:
Co-variant array conversion from CoffeeModifier[] to ButtonDisplayable[] can cause run-time exception on write operation
CoffeeModifier inherits ButtonDisplayable

Does the exception only arise if I write a ButtonDisplayable that is not a CoffeeModifier? Is it fine to leave the warning if I never have to change the array

dusk apex
#

In the example, going from an array of strings to objects would generate the warning.

old linden
#

I'm simple Graphics Raycasting and for the first frame, no objects are detected. In subsequent frames, objects are detected fine. Event system is assigned in Inspector and never disabled. Does anyone know why that could be? Here's my code:

Debug.Log($"Casting at {touchInfo[touchIndex].position}...");

pointerEventData = new PointerEventData(eventSystem);
pointerEventData.position = touchInfo[touchIndex].position;
List<RaycastResult> rayResults = new List<RaycastResult>();
graphicsRaycaster.Raycast(pointerEventData, rayResults);

Debug.Log($"Casting hit {rayResults.Count} objects");

I've attached a shot of the Scene. Thanks

plucky inlet
plucky inlet
#

So you hit play and click somewhere and your casting at debug log is not firing or your rayResults.count is 0?

#

Just checked your console, got it. Your hits are 0 on first click.

old linden
#

Yes. I have also taken out the casting to just update and still doesn't hit anything on the first frame. Rather strange

private void Update()
{
    Debug.Log($"Casting at {touchInfo[0].position}...");

    pointerEventData = new PointerEventData(eventSystem);
    pointerEventData.position = new Vector3(480, 540, 0);
    List<RaycastResult> rayResults = new List<RaycastResult>();
    graphicsRaycaster.Raycast(pointerEventData, rayResults);

    Debug.Log($"Casting hit {rayResults.Count} objects at position {pointerEventData.position}");

    return;

    ProcessTouchType();
    ManageLiveParticles();
}

Edit: Feeding a direct value into the .position property has the same issue

plucky inlet
#

Maybe you have to "wake up" the eventsystem with a "start raycast" to avoid that issue.

cyan ivy
#

Could it be a matter of execution order?

plucky inlet
cosmic rain
old linden
#

Yes. In this part of my script, I fake user input for testing purposes 🙂

old linden
#

I have since created a new scene with the same code as above and the issue is still present, so its nothing in my scene. I have added a delay of 10 frames before I do anything with the script to get around the issue

cosmic rain
#

It seems like the image is empty on start

#

Assuming you assign the image in update(of a different script) as well, there's no guarantee that this happens before the raycast

old linden
#

It doesn't need a Sprite to raycast

cosmic rain
old linden
#

Image is Raycastable regardless of if a Sprite is assigned 🙂

cosmic rain
#

Ah, okay. But the image has 0 size.

old linden
#

It's stretched to the canvas size. I tried that even with standard fixed placement covering full screen and its still not a fan. I think the Graphics Raycast stuff must wait for something from the canvas to be ready

#

Not sure what it is however

cosmic rain
#

Try using late update

#

Or wait 1 frame

novel bough
#

Hi friends, I have one scene with room design and one orthographic camera I want to zoom the camera when I double-click on the particular wall if I click on the wall with a green circle the desired outcome will be like in the next image only selected will appear on camera. So, how do you position the camera via script? Please help! I have tried this function where I pass the "targetObject" as the selected wall create a new orthographic camera and try to put it in front of the wall and look at that wall but it's not working in every direction wall. Please help!

    {
        if (targetObject == null)
        {
            Debug.LogError("Target object is not assigned.");
            return;
        }

        // Create a new GameObject for the camera
        GameObject cameraGameObject = new GameObject("OrthographicCamera");

        // Add a Camera component
        Camera camera = cameraGameObject.AddComponent<Camera>();

        // Set the camera to orthographic mode
        camera.orthographic = true;

        // Set the orthographic size
        camera.orthographicSize = 5;

        // Position the camera with the given offset
        camera.transform.position = targetObject.GetComponent<Collider>().bounds.center + offset;

        // Make the camera look at the target object
        camera.transform.LookAt(targetObject.GetComponent<Collider>().bounds.center);

        // Adjust the rotation so the camera is aligned correctly
        camera.transform.rotation = Quaternion.Euler(0, targetObject.transform.eulerAngles.y, 0);

        Debug.Log("Orthographic camera created and positioned.");
    }```
steady bobcat
novel bough
#

@steady bobcat "offset" is the distance between the wall and the camera I put it at -5, the problem is that the camera does not position correctly for each side of the wall

steady bobcat
#

If you position the camera as you want, what global pos does it actually have?

#

if you just move it -5 on a single axis then the result you got above makes sense (as i presume your room is "axis aligned"), you need to think more carefully what you need to do to maintain the same camera pos + angle.

novel bough
#

@steady bobcat each side wall faces the same side there are no rotations to the walls. That's why I can't know on which axis i should put the offset.

steady bobcat
#

OH do you actually want it showing it "square"

#

you can use the normal of the face to move the camera out in the correct direction easy

#

then look at

novel bough
#

@steady bobcat how can i get normal of the face? is it from mesh?

steady bobcat
#

If you raycasted i think you can grab the hit normal and use that which should be correct depending on the collider used

#

if using input system im not 100% sure if you can get the same data

novel bough
#

oh i used raycast thanks I'll try and let you know.

hushed ocean
#

(I'm making a 2D top down shooter for context)

Anybody know how to interrupt animation states? I'm having some major issues using the animation system trying to fix a bug in my game where the player has multiple weapons and one of them is a boomerang which is animated compared to most of the others.

The problem is that the boomerang has a slight delay from when you start throwing the boomerang to when i actually becomes a projectile. In that little window, if you switch to another weapon, then back to the boomerang, instead of going back to the "boomerang idle" animation, it just plays the "boomerang throw" animation. It's even worse when the player switches to another animated weapon like the RPG after switching to a non-animated weapon after trying to throw the boomerang but switching to a non-animated weapon then the RPG causing the player to throw the boomerang before actually showing the player is holding the RPG.

Sorry if this is hard to read, i'm just really annoyed over this whole problem. The Unity animation system is my least favorite part of Unity.

novel bough
#

@steady bobcat i get these four different normals for four walls how can i use this to place camera and rotation?

cosmic rain
hushed ocean
cosmic rain
hushed ocean
#

i gotta go to class now, hopefully i'll remember when i get back

steady bobcat
merry sierra
#

!code

tawny elkBOT
merry sierra
#

hi, i was making a isometric shooter so i want my character to rotate towards my mouse but im getting wierd offset


private void RotateGraphicsTowardsMouse()
        {
            Vector3 mousePosition = Input.mousePosition;

            Ray ray = mainCamera.ScreenPointToRay(mousePosition);
            Plane groundPlane = new Plane(Vector3.up, Vector3.zero); 
            if (groundPlane.Raycast(ray, out float distance))
            {
                Vector3 worldPosition = ray.GetPoint(distance); 

                Vector3 direction = worldPosition - graphics.position;
                direction.y = 0; 

                if (direction.sqrMagnitude > 0.01f) 
                {
                    Quaternion targetRotation = Quaternion.LookRotation(direction);
                    graphics.rotation = Quaternion.Slerp(graphics.rotation, targetRotation, Time.deltaTime * 10);
                }
            }
        }
steady bobcat
#

if the laser is on the floor plane im guessing it lines up after all

cosmic rain
steady bobcat
#

you can move the plane up by the aim height to make the laser match

#

but i think the rotation will be the same either way 🤔 (maybe? im not sure)

cosmic rain
#

Making the gun aimable on the y axis might help

merry sierra
#

yeah if i put laser on ground it works good

#

i tried putting a little offset but on each quater the offset is different so cant put offset too

trim schooner
#

The difference in the video looks like it's because caused because of the angel of the camera + model. The cursor is aligned with the middle of the body, so it will be below the laser at all angles that aren't 0/ 180

#

It's just an opitcal illusion, imo

merry sierra
#

yup, but it will look wierd when player try to aim

trim schooner
#

have you looked at other games and evaluated how they do it?

trim schooner
astral robin
#

Hi ! I have been wondering if there is a way to call a function that would play from the Entry node of the base layer in the animator ?
like : animator.Play(form the entry state of that layer);

merry sierra
main zenith
#

Hi , does anyone perhaps have some knowledge they can share regarding this error ? I just have a very basic script to display my webcam feed onto a RawImage but for some reason, even though it's worked fine some time ago, it just pops up with this error and refuses to display the webcam in question.

I've tried setting the resolution and fps in script which didn't seem to do anything and also tested with multiple cameras. Any suggestions would be greatly appreciated

heady iris
#

Can you get a list of supported resolutions fort a webcam, maybe?

main zenith
#

I've tried as well, but even if it is on a supported res it just comes back with the same thing

heady iris
#

okay, so the device doesn't have an empty list of resolutions

merry sierra
main zenith
#

If you mean by using device.availableResolutions, it returns null because it's on Windows

heady iris
hushed ocean
# cosmic rain Maybe start with sharing screenshots/videos demonstrating the setup and the issu...

ok, i've recorded the issues. The second clip shows where the actual bug happens. When i try to throw the boomerang, i switch weapon then back to the boomerang to show it just automatically throws it.

and so you can look at the code, here's the boomerang state machine script:

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

public class BoomerangStateMachine : StateMachineBehaviour
{
    // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        if (Shooting.selectedWeapon == 5)
        {
            animator.ResetTrigger("Selected weapon is rpg");
            animator.SetTrigger("Selected weapon is boomerang");
        }
        if (Shooting.selectedWeapon != 5)
        {
            animator.ResetTrigger("Throw boomerang");
        }
    }

    // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
    override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {

        if (Shooting.selectedWeapon == 5 && Input.GetButton("Fire1") && Shooting.canShoot && Boomerang.boomerangCount > 0)
        {
            //animator.SetTrigger("Throw boomerang");
        }
    }

    // OnStateExit is called when a transition ends and the state machine finishes evaluating this state
    override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        animator.SetTrigger("No boomerangs left");

        if (Boomerang.boomerangCount == 0)
        {
            animator.ResetTrigger("Throw boomerang");
            animator.ResetTrigger("Boomerang reaquired");
        }
    }
}

The RPG one is too long to include in this message as well though, i'll send that one after this message.

main zenith
hushed ocean
#

And here's the RPG one. (yes, there's a lot of disabled code, i know.)

using System.Collections;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using UnityEngine;

public class RPG : StateMachineBehaviour
{
    // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {

    }

    // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
    override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        if (Shooting.selectedWeapon == 4)
        {
            animator.SetTrigger("Selected weapon is rpg");
            animator.ResetTrigger("Selected weapon is boomerang");
        }
        if (Shooting.rpgIsReloading)
        {
            //animator.SetTrigger("Rpg reloaded");
            //animator.ResetTrigger("Fire rpg");
            //animator.SetBool("rpg empty", true);
        }
        else
        {
            // animator.SetBool("rpg empty", false);
            animator.SetTrigger("Rpg reloaded");
        }
    }
    // OnStateExit is called when a transition ends and the state machine finishes evaluating this state
    override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        //animator.ResetTrigger("Fire rpg");
        //animator.ResetTrigger("Rpg reloaded");
        //animator.SetBool("rpg empty", false);
    }
}
#

the third script which is a monobehaviour one that's actually attached to the player is straight up too long to send in one message here so uhh..

cyan ivy
#

!code

tawny elkBOT
main zenith
knotty sun
hushed ocean
knotty sun
hushed ocean
#

cuz i'm dumb probably

pine condor
#

how do i use xr interaction manager to snap an object to the players hand when grabbed? it's using a ray and grabbing it with the same offset as when it was picked up. im trying to use direct interactor but it doesn't seem to do anything. im using the default xr origin rig prefab on unity 6.0.27f1 xr interaction toolkit 3.0.7

thin aurora
#

Helps a lot. Often completely useless, until it's not

cosmic rain
#

Because it hard-depends on the actual state of the animator. You want your logic to run independently of the animator. The animator should only handle animations.

vestal arch
#

thonk if you have a singleton as an additive scene, you can't use single-load scenes at all without destroying the singleton then, can't you
unless you ddol it

hushed ocean
heady iris
#

You just have to be conscious of that dependency.

#

Although, thinking about it for more than 5 seconds, I'd rather not put too much of my game logic in there.

#

I'd mostly just want to use them like animation events (but for entering and exiting states)

hushed ocean
cosmic rain
#

When you have that handled, and if the issue still persists, it's probably due to the animator states/transitions setup.

pine condor
heady iris
hushed ocean
cosmic rain
#

Sharing the new code would be helpful too.

hushed ocean
heady iris
#

!code

tawny elkBOT
heady iris
#

use a paste site for that much code

hushed ocean
cyan ivy
heady iris
#

no, like one of the sites linked in the bot message

#

I guess you could use a Gist, though

hushed ocean
regal compass
#

hello everyone, how do I make it so that when an object touches something, music starts playing only when it collides, let's say I have music for 6 seconds

vestal arch
#

when collide, start playing audio clip

#

that's 2 separate parts

#

try researching for those separate parts

hushed ocean
vestal arch
#

"unity how to detect collision", "unity how to trigger audio"

cosmic rain
# hushed ocean ok, i've recorded the issues. The second clip shows where the actual bug happens...

Looking at the videos you shared, your animator setup is a mess. First of all, most of the parameters are logically bools, not triggers. You should not have that many triggers active at the same time. A trigger is like an event. It's meant to be consumed almost immediately. If your parameter defines a long lasting state it should be a bool.
The only params that logically make sense to be triggers are: Swipe, Throw boomerang and Fire RPG.

hushed ocean
#

Swipe is for a scrapped weapon ._."

cosmic rain
#

You should write down the logic that you want to be followed on paper. Ideally, make block schemes. When you have it planned on paper, implement the animator states and then write the code that sets the required parameters.

hushed ocean
lapis otter
#

Thanks man, it helped a lot!

clever lagoon
#

how do I override/take an action on this menu item? I thought this would do it, but no: ```[CreateAssetMenu(fileName = "SOTest", menuName = "GameVersionData/SOTest")]
public class SOTest : ScriptableObject
{

public int anInt;
[ContextMenu("Reset")]
public void Reset()
{ anInt = 69;  Debug.Log("Reset called"); }

}```

#

Do I need to use a different method signature for the Reset button to be enabled?

heady iris
#

Name collision!

#

"Reset" is already a context menu item.

#

which...well, it's supposed to run the Reset method, actually

#

That may be screwing up the menu

clever lagoon
#

That what I thought.. I thought unity used reflection to find a paramtererless void method named Reset

heady iris
#

Do you want Reset to run upon creation of the asset, or should it only run when you pick a specific menu item?

clever lagoon
#

both

heady iris
#

Okay, just get rid of the ContextMenu attribute

clever lagoon
#

but I can make two fuinction names if needed

heady iris
#

see if that makes it happy

clever lagoon
#

tried that first- no go, trying again one sec

#

negative 😦

heady iris
#

Maybe restart the editor?

#

I know that I've had problems with [CreateAssetMenu] items not updating until after a restart

clever lagoon
#

ok, gimme a sec

#

nope :(.. hmm am I trying to Reset() wrong? does that button not do what I thought it does?

#

the other option is "EditScript" which feels.. different than what I need

heady iris
#

Is "SOTest" an asset in your project window?

clever lagoon
#

yep, a script an a single asset

#

(I have the asset selected in above screen shots)

heady iris
#

the Reset item is not grayed out for me

#

and it works as expected

#

(unity 6000.0.24f1)

clever lagoon
#

oh.. using that same scimple script!!? ok, thats a good sanity check thank you Fen

heady iris
#

yeah

#

the Reset function is called upon asset creation, as well as when I click Reset

#

even with the ContextMenu attribute being there

clever lagoon
#

hmm.. ok prolly me and the old ass unity version I'm running, will copy project and try in later version. Thanks again- big help!

heady iris
#

It looks like it completely ignores your ContextMenu attribute if its name is Reset. It does the normal reset operation (setting all serialized fields to their default values) even if "Reset" is supposed to just call that Reset method

#

I dunno what would be causing it to gray out the Reset button

sleek bough
#

Do you have any error in console?

#

Make sure they are not hidden as well

clever lagoon
clever lagoon
heady iris
#

That would be plausible (but that'd have caused a Safe Mode prompt when reloading the editor)

knotty sun
#

pretty sure Context Menu methods need to be static

clever lagoon
#

litteryaly the SECOND you said that

heady iris
#

ContextMenu is for interacting with a specific item in the inspector

heady iris
sleek bough
#

You don't even need context menu for Reset, it's built-in

clever lagoon
#

ah.. it was OTHER stuff in the project (not that TestSO) fixed.. testing now

heady iris
#

Yeah, and we tried removing the attribute already

#

If you just changed major version numbers, obsolete/deprecated code could have gone away entirely and broken the project

#

I know that a few enums got renamed between 2022 and 6

#

had to go in and rewrite those myself

clever lagoon
#

that was it.. the unity8 version- working as expected in 2022

heady iris
#

unity 8 😱

clever lagoon
#

(yes, I tend to lag.. I'm old)

sleek bough
#

Try testing on a fresh SO script and let IDE autocomplete Reset method

clever lagoon
clever lagoon
heady iris
#

either the 2022 or 6 LTS releases

#

(i have no idea what 8 would be :p )

teal anchor
#

When using rider debugger anybody have issue on it not showing variables because they are "out of context"

naive swallow
heady iris
#

e.g. they're locals in a method that you aren't currently inside of

teal anchor
#

Should they be visible inside method that is currently inside local scope. Like show the ones right above the current local scope

#

But still inside method

heady iris
#

by "local scope", are you referring to a block statement?

#

if so, then yes, everything in your enclosing block will still be in-scope, so it'd be weird if the debugger said they were out of context

#
{
  float foo;
  {
    float bar; // bar and foo are visible here
  }
}
teal anchor
#

I will show example quickly once i boot up computer

#

I did it now and it worked like expected. Huh, maybe it will repro later

clever lagoon
#

heh.. ye olde tyme: "turn it off and back on"

teal anchor
#

Its weird cause i have had happen fairly often, but not right now

wintry crescent
#

I have a MyType<T>, and I have a CustomPropertyDrawer(typeof(MyType<>))
How can I access either a static property from MyType inside my Drawer?

#

I have to provide some T to even type it out in a way that the IDE doesn't scream at me

#

but I don't know what's a good "default" T to provide

heady iris
#

You can only access things that are guaranteed to be members of T

#

If T is an unconstrained type parameter, you can access nothing

#

Oh, wait, I see

wintry crescent
#

ok let me show exactly what I'm trying to do

heady iris
#

MyType<T>, not T

wintry crescent
#

how do I access this

#

from my Drawer

heady iris
#

Hmm, I'm not sure what the "nicest" way to do that would be.

wintry crescent
#

optionally - a way to do null.ToString() would be fine lmao

wintry crescent
heady iris
#

you can just pick an arbitrary type, of course

wintry crescent
#

this variable can be const, it can be readonly, anything, I just want a consistent way to get the string in my Drawer

heady iris
#

I feel like it doesn't belong in that type at all

wintry crescent
wintry crescent
heady iris
#

ah!

#
public class Test<T>
{
    public const string NullString = "Null";
}

public void Foo<T>(Test<T> item)
{
    var x = Test<T>.NullString;
}
#

That does work.

chilly surge
heady iris
#

It does feel a bit odd.

wintry crescent
heady iris
#

I forget how the static member even behaves there -- does every parameterization of Test get its own static member?

chilly surge
#

If you just want to turn something that is potentially null, into its string representation, $"{foo}" works.

wintry crescent
#

no - I specifically am looking for the null.ToString() equivalent

somber nacelle
#

I do want to point out that statics on generic types are separate from each other when the generic type parameter is different. Foo<int> could have different values in its static variables than Foo<long>

chilly surge
#

I'm confused why you insist on maybeNull.ToString() when you could do $"{maybeNull}".

wintry crescent
#

that'd solve my problem well enough

somber nacelle
#

what are you actually trying to accomplish with this

heady iris
#

I'm very confused, yes

chilly surge
#

This sounds like a XY problem.

heady iris
#

Show your existing code.

wintry crescent
#

this string

somber nacelle
heady iris
#

Presumably you can just make this a const inside of InspectableTypeDrawer

#

without further context I can't see why it needs to live in another type

wintry crescent
#

I need it in both places

#

for the what am I doing? this, just modifying the script from the first answer

heady iris
#

tbh I would just put it in another static class

#

at that point, it's a constant string that multiple types care about

#

it has no meaningful association with those types

wintry crescent
#

but there's only two types that ever care about it!

#

two classes*

#

xd

heady iris
#

well, InspectableTypeDrawer, plus an infinite family of InspectableType types

wintry crescent
heady iris
#

Importantly, the string has nothing to do with the exact type parameter of InspectableType<T>

wintry crescent
#

since it's just for the inspector

heady iris
wintry crescent
#

although that's not a problem since they, well, derive from it

#

so they'd have easy access if they wanted

#

but they don't

heady iris
wintry crescent
#

only the class itself and its drawer

#

is there a way to do it or do I just live with nothing

heady iris
#

I'd really just make it a const in both types and call it a day. Minor duplication isn't an issue.

#

(and consts go away during compilation)

#

much more reasonable than static members, actually, since those will not go away

wintry crescent
#

switched it to const though you have a good point

heady iris
#

I am working on a package that's almost entirely code. Is there a particular version of Unity I should use to develop it?

#

I'm worried about the serialized data confusing an older version of unity

#

e.g. I install the package on disk into a Unity 6 project

#

this means that Unity is going to start writing .meta files into the package folder

#

which are generated by a very new version of unity

#

nominally, even someone on Unity 6000.0.23f1 would be "downgrading" when installing my package

#

since I'm on 6000.0.24f1

somber nacelle
#

assuming you don't set any of the default references or change anything else in the import settings for the file the meta file should just contain the fileformatversion and guid so it really shouldn't be a problem

heady iris
#

yeah

#

and I imagine that the MonoScript serialization format doesn't change constantly

#

(interestingly, force-serializing it causes some extra stuff to be written...)

#

version 2!!

#

why on earth is information about asset bundles in there

regal compass
#

hello everyone, how do I make it so that when an object touches something, music starts playing only when it collides, let's say I have music for 6 seconds

candid comet
#
void HandleSpannerTwist()
    {
        // Get the distance between the spanner and the camera
        float dist = Vector3.Distance(insertedSpanner.transform.position, Cam.transform.position);

        // Get the mouse position in screen space, then convert to world space
        Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
        Vector3 mouseWorld = Camera.main.ScreenToWorldPoint(mousePos);

        // Get the vector pointing from the spanner to the camera (the "upwards" vector for rotation)
        Vector3 upwards = insertedSpanner.transform.position - Camera.main.transform.position;

        // Calculate the desired rotation of the spanner to face the mouse position
        Quaternion targetRotation = Quaternion.LookRotation(mouseWorld - insertedSpanner.transform.position, upwards);

        // Smoothly rotate the spanner towards the target rotation
        insertedSpanner.transform.rotation = Quaternion.Slerp(insertedSpanner.transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);

        // Additional actions or logic, such as charging the generator, goes here
        ChargeGenerator();

    }

I am trying to make a handcrank (in code spanner) that the player rotates using his first person crosshair to recharge a generator, this is my code so far, my problem is that i want the crank to only rotate in the X-Axis while Y and Z are still 0 how can i do this?

#

Quaternions are not my strength

heady iris
#

ooh we're doing rotations

candid comet
#

I suck at rotations

heady iris
#

You'll want to use Plane here, actually

#

rare Plane moment

candid comet
#

is that a function?

heady iris
#

you will create a plane that pases through the center of the crank and whose surface normal points along the axis of rotation

#

let me make a shitty mockup

leaden ice
#

Planes are super not rare!

candid comet
leaden ice
#

I will defend Planes to the death

quick token
#

(i have never heard of a plane before guh)

heady iris
#

You're going to raycast from the camera onto this plane

#

Conveniently, Plane has a method for that!

candid comet
#

do i need to change my model/hitboxes for the crank?

heady iris
#

No.

#

This will have nothing to do with physics at all

#

You'll use the Raycast method to find where on the plane the player's mouse is positioned

#

Given a point on the plane, you can find a direction from the center of the crank to the point

#

That's the direction the crank should rotate towards

#

Finally, you'll use Quaternion.LookRotation to compute a rotation

#
Plane plane = new Plane(crankAxis.up, crankAxis.position);
Ray ray = Camera.ScreenPointToRay(mousePos);

if (!plane.Raycast(ray, out float distance))
  return; // your mouse didn't hit the plane at all

Vector3 hit = ray.GetPoint(distance);
Vector3 direction = hit - crankAxis.position;

Quaternion rotation = Quaternion.LookRotation(direction, crankAxis.up);

The resulting rotation would make an object's blue handle (the +Z direction) point towards the hit point

#

Its green handle (the +Y direction) would be aligned with the crank axis

#

You may need to adjust this a bit if that doesn't match what you have

candid comet
#

alrighty

#

i will try

#

thank you very much

heady iris
#

This doesn't handle clicking on the crank, mind you

#

You might use physics for that

#

This'll just let you wave the mouse all over the place while turning it

candid comet
#

i already have some code for that which i think should work fine

heady iris
heady iris
#

this would be the crankAxis i used in my code

#

its green arrow should point along the axle

candid comet
heady iris
#

This would be an appropriate setup

#

The blue arrow points in the direction of the handle

candid comet
#

its not exactly at the base

heady iris
#

As long as it's vaguely near the base it'll be fine

candid comet
#

alright

heady iris
#

If you want to visualize how this'll work, create a plane and parent it to that object

#

you can then imagine shooting rays at that plane from the camera

candid comet
#

i will do that

#

again, thank you for explaining this to me with visualised examples and everything

heady iris
#

no prob! (:

#

rotations can be really frustrating; you'll often figure out something that mostly works, but then blows up in a few cases

quick token
#

i think i do see how they can be useful thouhg

candid comet
# heady iris This would be an appropriate setup

i forgot that the crank can be taken off and placed to other places and when i do that the green axis no longer points away from the base meaning the plane is made in the wrong axis, how can i fix this?

heady iris
candid comet
#

yes

heady iris
#

set it to "Local" if so -- check the top left corner

#

that will show you the local directions of the object

#

red is right, green is up, blue is forward

candid comet
#

i changed up to right here
Plane plane = new Plane(insertedSpanner.transform.right, insertedSpanner.transform.position);

heady iris
#

Yep, that'll be the correct move

#

You'll also use transform.right as the second argument to LookRotation

candid comet
#

was just about to ask that

#

alright

#

something weird is happening now

#

the crank rotates in all axis

heady iris
#

Can you show me your code?

candid comet
#
void HandleSpannerTwist()
    {
        float dist = Vector3.Distance(insertedSpanner.transform.position, Cam.transform.position);
        
        Plane plane = new Plane(insertedSpanner.transform.right, insertedSpanner.transform.position);


        Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
        Vector3 mouseWorld = Camera.main.ScreenToWorldPoint(mousePos);

        Ray ray = Camcamera.ScreenPointToRay(mousePos);

        if (!plane.Raycast(ray, out float distance))
        {
            return;
        }

        Vector3 hit = ray.GetPoint(distance);

        Vector3 direction = hit - insertedSpanner.transform.position;

        Vector3 upwards = insertedSpanner.transform.position - Camera.main.transform.position;

        Quaternion targetRotation = Quaternion.LookRotation(direction, insertedSpanner.transform.right);

        insertedSpanner.transform.rotation = Quaternion.Slerp(insertedSpanner.transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);

        ChargeGenerator();

    }
heady iris
#

Oh right, I just realized -- LookRotation will still behave wrongly here

#

It gives you a rotation that aligns your blue arrow with the first direction, using the second direction to decide how to roll around that axis

#

One other issue is that Slerp is going to take the shortest possible path

#

I think that'll make it rotate properly as long as the starting and ending rotations are around a common axis, though

heady iris
candid comet
#

would using slerp cause the crank to get stuck at certain points

heady iris
#

It's generally used to figure out how to orient your camera

#

you look in one direction, using a second direction to decide what should be "up"

#

but we're not using forward and up; we're using forward and right

#

Can you modify the crank so that the green arrow is pointing along the axis? That would make things easier

candid comet
#

do you mean change the model?

heady iris
#

Either that, or by parenting the model to an empty object and then rotating the model

#
  • Root
    • Crank Model
candid comet
#

alright

#

would i need to put the collider and code to the empty parent?

heady iris
#

Yeah, you'd want the component to be on the "Root" object

#

Before you do that, though, there's one other option...

viral cipher
#

How to Disable Script Updating Consent Popup

heady iris
#

actually, lemme test something

candid comet
#

i am almost done with it

#

moved the components of the child to the empty object

heady iris
#

okay, yeah, it works perfectly when the up direction aligns with the axis

candid comet
#

like this?

heady iris
#

Yes, perfect

#

It goes nuts if I use the same code with the red arrow pointing outwards (with transform.right swapped in)

#

I think the issue is that LookRotation wants to make your green arrow (the up direction) agree with the second direction you give it

#

But we want the red arrow to agree with that second direction (so that we spin around the axis)

#

So it's off by 90 degrees and freaks out

candid comet
#

i think it works right now

heady iris
#

One other thing -- you might want Quaternion.RotateTowards instead of Quaternion.Slerp here

#

the former will let you move towards the target angle at a constant rate

#

the latter will be faster when you're further from the target

candid comet
#

alright

#

is there a way of getting how much the player has spun the crank?

heady iris
#

Yeah -- you can measure the angle between the old rotation and the new rotation

#

This will always be positive

candid comet
#

well if the player is going to keep spinning it wouldnt it be...

heady iris
#

If you want to be able to measure going both forwards and backwards, then you might want Vector3.SignedAngle

#
Vector3 one = rot1 * Vector3.right;
Vector2 two = rot2 * Vector3.right;
float delta = Vector3.SignedAngle(one, two, Vector3.up);
#

You need that third vector as a point of reference

#

to decide if the angle is positive or negative

candid comet
#

i think i am going to sleep now

#

thank you for your help

#

i was trying to fix this for like 3 hours

#

have a nice day

heady iris
#

you're welcome (:

visual terrace
#

Hello, I recently updated to unity 6, and I can't seem to get the light2D to be found in scripts. I changed the reference to no longer have the experiential path but it still can't seem to find it. I also tried regenerating the project as well. What else can I do?

#

Nevermind, I just had an idea that is should just add any assembly with the name 2D in it and found the assembly Unity.RenderPipelines.Universal.2D.Runtime to work.

naive swallow
#

!code

tawny elkBOT
tidal moss
naive swallow
tidal moss
#

a reference to a script that handles a procedural animation.

#

thank youuu!!

#

got it

#

called the _recoilAnimation.Stop();

mighty juniper
#

is anyone able to help with this? i never did get it resolved from yesterday and im still completely stuck after spending logner on it today

polar marten
#

this is an interesting mechanic. are you saying you want to "hold" an object and make it appear stationary in screen space, but naturalistically moving in world space?

mighty juniper
polar marten
mighty juniper
#

they track perfectly for movement, just not rotation

polar marten
#

and the objects must be NON kinematic rigidbodies while under the influence of the controller?

mighty juniper
#

yeah

polar marten
#

you actually mean that the objects should be "tracking in relative space to the controller while the button is pressed" right? like you press a button, and now they're "tracking", but they don't fly into an absolute world position and orientation

mighty juniper
#

not on a button press, they need to track all the time

polar marten
#

okay

#

i want you to think deeply about that

#

they're probably not doing that

#

like even at the beginning of the game, yes? they're not in absolute world space

mighty juniper
polar marten
#

are you familiar with physics joints?

#

you "simply" attach (a) joint(s) to the controllers in your scene

#

your choices in how to do that reflect what kind of behavior you want

hexed pecan
#

Sounds to me like you just need to rotate the relative target position by the character's rotation

polar marten
#

you are currently reinventing joints

hexed pecan
#

And apply torque to match the rotation

polar marten
#

so you can use joints, or you can try to author joints from scratch

mighty juniper
polar marten
#

you can start by adding a fixed joint to the hand, then connect it to the object in whichever way makes most sense to you

mighty juniper
#

Sure, mind just letting me finish this game i'm in? I can get back to you then

hexed pecan
#
Quaternion deltaRotation = targetRotation * Quaternion.Inverse(rb.rotation);```
This part might be inverted. Order of operations matters with quaternions
polar marten
#

tracked pose drivers Just Work. it really depends on your gameplay

#

you don't want to reinvent either tracked pose drivers or joints

#

or use a vr interaction package from the asset store

#

since you have to do all the joint stuff at runtime

#

imo, because you don't get physical feedback, you will probably want to use a bunch of springs

#

you can study the asset store assets that do this to see how they make good interactions @mighty juniper

mighty juniper
polar marten
mighty juniper
#

I was using it initially, but its just a pain to use for my use case so i wanted to build it myself

polar marten
#

end users have certain expectations regardless of what you want that have been defined by other games

#

hmm, but correct me: it looks like you just want these objects to behave as though they are grabbed by a hand

#

perhaps without visualizing the hand, but grabbed nonetheless

mighty juniper
#

the cubes are just visualisations of what will eventually be a hand model

#

nothing is being grabbed at this stage

#

they are my hands

mighty juniper
polar marten
#

you want a hand model that is permanently physically interacting?

#

and just behaves "well" around walls and such?

#

so grab a hand model

#

right now you are trying to reinvent grabbing.

hexed pecan
#
Vector3 targetPosition = actions["Position"].ReadValue<Vector3>() + followTarget.position + followTarget.TransformDirection(offset);```
I don't see you rotating thet target position here. (What is offset?)
polar marten
#

your approach is not going to work in any case. it's going to accumulate a lot of fixes as soon as you discover teh bugs

mighty juniper
polar marten
mighty juniper
hexed pecan
#

The second line being the key change here

polar marten
#

i mean it seems pretty cut and dried

#

you just want hands and grabbing

#

you can definitely have this!

mighty juniper
polar marten
#

it exists

#

you don't have to worry about trying to do this yourself

#

the whole approach is wrong

hexed pecan
polar marten
#

you aren't reading the right input actions, and you're not familiar with the VR input system idiosyncracies, and you aren't figuring out the angular velocity correctly either

#

😦

mighty juniper
mighty juniper
polar marten
hexed pecan
#

Not sure if thats the case

mighty juniper
mighty juniper
mighty juniper
#

although i could've sworn i tried applying the rotation like that before, but maybe it was my order of operations that was wrong

polar marten
#

🥺

mighty juniper
# polar marten 🥺

I just would rather stay away from the default framework to be honest as it feels really unreliable at times. And I'd rather have a deeper understanding of exactly what my code is doing, because i wrote it, rather than trying to twist their framework to my needs

modern creek
#

I'm kind of going insane here.. I have a font that I generated two SDFs for textmeshpro. The fonts are identical, but one has an underlay and outline on the material.

The spacing is different between these two fonts and I can't figure out why. They look the same but the glpyh adjustment table is different for a variety of characters.. how would that happen?

#

same font face, same character spacing, just a different material (underlay and outline values)

#

individual glyphs have different adjustment widths but I don't know where these would have been generated from

wide totem
#

Hello, i am working on a random structure generator, and am mostly done with the base of it, however I am occasionally getting this error (image 2)

private void roll()
{
   
   blackList.AddRange(newRoomDirs); // adds already used directions to blacklist (1-4)

   List<int> valid = new List<int> { 1, 2, 3, 4 }; // valid directions
   valid.RemoveAll(v => blackList.Contains(v)); //removes all directions from valid contained in blacklist
   int newDir = UnityEngine.Random.Range(0, valid.Count); //random index
   blackList.Add(valid[newDir]); //adds newDir to blacklist, where error is
   
   StartCoroutine(createRoomSpawner(valid[newDir])); //creates room in chosen direction
}
#

i can provide any more context if needed

chilly surge
#

Do some debugging.

#

Without context, I'm guessing the issue is that you have no valid directions left.

wide totem
#

oh that might be true, let me check

modern creek
#

or if there's 0 items left in the list, newDir = 0 (which doesn't seem to be a valid direction according to your comment), but valid[0] will be index out of range because there are no items in the list (where your code would try to read the "0th" - first - item)

#

or rather, what burrito said - if your blacklist has all the items in the list

wide totem
#

yeah i forgot to check if count was 0, that fixed it! thanks

stiff karma
#

I'm working on a 2d pixel game, and would like the players to be able to change the color of some objects. Unfortunately, Unity's coloring via code looks really faded/washed out. Does anyone know of any assets or anything I can use to improve this? I'd like "Red" to actually look red, rather than a faded pink.

hexed pecan
#

You might also have some post processing effects going on

#

Okay I completely forgot that your game is 2D. Are you using some kind of lighting? Maybe show a screenshot of the issue?

#

And the settings of the sprite renderer and its material

#

I suspect that the "washed out" effect is because by default, the sprite color is multiplied by the base color. So if you have a green sprite and add a red tint to it, it won't be red

stiff karma
#

Someone else is doing the programming on my current project. I just know from past experience (years ago), that this was an issue (and my current programmer brought it up recently)

#

we haven't actually implemented any coloring yet. I was just wondering if there was a better solution

hexed pecan
#

I'd probably use a shader that has a mask texture for which parts of the sprite should be affected by color.
Or if you want to color the whole object, just use a white/grayscale texture. Then the coloring should work as expected

stiff karma
#

all right, I'll try again to convince my programmer 😉

#

thanks!

marble glade
#

https://hastebin.skyra.pw/eyitejonev.csharp I'm struggling with this code, it's almost perfect but it still has problems. The player enters a collider and presses E for an action to occur (the camera changes and text appears) but the player's control is not deactivating in the right way. If I jump or walk while pressing E, the player freezes in the movement, continues walking or stays in the air if I jump, I need him to finish the last action before entering the animation. And another thing, when the camera returns to the player, some commands are disabled, like if I want to run, I need to stop pressing sprint and press it again.

hexed pecan
#

Sounds like you'd want some sort of state machine or queue for the actions

cosmic rain
somber nacelle
#

when the camera returns to the player, some commands are disabled, like if I want to run, I need to stop pressing sprint and press it again
you explicitly set those to false in both DisablePlayerControls and ResetPlayerInputs

inner yarrow
#

Does anyone know what would be causing an error like this? Double clicking on it doesn't bring me to where the error is being thrown, and I haven't touched anything in UnityEditor.Graphs. It started happening after I tried making one script inherit from a different one. There aren't any compile errors.

somber nacelle
#

it's just an editor error, likely caused by the Animator or some other graph editor being open. you can ignore it

#

it's also unrelated to your own code

inner yarrow
#

Ok, sounds good. I'm just confused because it wasn't happening before, but I'll ignore it. Thank you.

somber nacelle
#

close any graph editor windows and it will stop so you can confirm that it isn't your code doing it (though i can assure you that it isn't your code)

fiery spruce
inner yarrow
#

I did that and I still have the error, but the game's running fine, so I'll just leave it.

#

Restarting unity fixed it.

somber nacelle
#

did you make sure to clear the console? exceptions won't just automatically go away on their own from the console until it is cleared

inner yarrow
vital oracle
#

I've never attempted to make a save system, but having a hard time wrapping my head around how I could go about it in my situation.
To keep it simple here's one aspect of my game that I want to save and load.

How would I go about saving a List of Classes which have various values that change during the game (ints, floats). These classes are permanent in the game until the player destroys the item.

I want this List to be exactly the same when the game is loaded. Would I have to save each class in its current state. Then on load create new instances of the class, change the values to what was saved, then add it to the List?

novel bough
#

Hi, I am loading the .glb 3D model at runtime. and getting this error about material "ShaderMissing; Shader Graphs/glTF-pbrMetallicRoughness" How to get this missing shader and fix this issue? i am using URP.

quartz folio
cyan ivy
novel bough
#

@cyan ivy @quartz folio Thanks! I have solved this by transferring shaders from Packages to Assets folder.

azure terrace
#

hey guys, i'm trying to measure the volume of the mic of my vr headset. i've created the needed scripts and when i use the mic of my pc everything works. but as soon as i switch to the mic of my vr headset it just doesn't do what it's supposed to do anymore. it's like it's not picking up the sound of my VR headset mic at all. i'm probably just forgetting a certain setting but i have no clue what. anyone knows whats going wrong?

halcyon temple
halcyon temple
azure terrace
halcyon temple
hollow jackal
#

Pls can someone tell how to bend my character body using third person view without using animation rigging package with out any plugins

#

While aiming

azure terrace
halcyon temple
azure terrace
#

That's a project I downloaded from someone else tho which is why it makes me think i' forgetting a certain setting

halcyon temple
#

@azure terrace this might sound crazy but reboot your computer and don't open discord. see if your VR mic is working then before opening discord....

#

I had an issue where somehow discord was keeping my hdmi audio from working with my headset plugged in. only way to fix it was to reboot the computer....

azure terrace
#

Alright I'll try that next

#

Thanks

halcyon temple
#

some applications take exclusive access of the mic. i think discord is one of them? make sure discord isn't using your vr mic! it could be keeping unity from being able to access it....

#

@azure terrace

wintry crescent
#

I have the most bizzare bug - are there any known bugs around GameObject.InstantiateAsync breaking references inside the instantiated object?

steady bobcat
#

I have tried using it a few times before and i also got strange issues (unity 2022)

wintry crescent
#

maybe it's similar

#

this is my issue: elements test is a freshly created and hand-assembled list, so it's not accessed anywhere at all. First image is the prefab, second is the async instantiated object

#

when playing around with object order/duplication the things that are missing seem to be changing, but I haven't found a consistent pattern yet, even though there does seem to be one

steady bobcat
hexed pecan
#

(And are you doing any custom editor scripting/custom inspectors?)

wintry crescent
wintry crescent
#

I also just verified that a list of ints is unaffected, it's the references that are breaking

hexed pecan
#

Are these missing components on children of the prefab?

wintry crescent
hexed pecan
#

So these are components on the root object

wintry crescent
#

and they are not missing on the children, I can freely just reassign them back onto the list by hand

hexed pecan
#

Ok, that's what I asked previously :p
To be clear, it does seem like a bug to me

wintry crescent
#

Simplest reproduction so far, on a UI prefab:

  1. Create a script on the root of the prefab that has a list of RectTransforms or probably also any other component (tested recttransform, custom script and canvas renderer)
  2. Create a bunch of different children on said object
  3. Fill the list on the root object with components on said children (various different children, that's important, sometimes doesn't happen if there's too little children or the list is too small or there's too many repetitions, hard to find a pattern)
  4. Instantiate the prefab using InstantiateAsync during gameplay
#

I haven't done much testing, if someone here can reproduce this issue it'd be pretty cool to report a bug

#

unity 2022.3.41 for me

steady bobcat
#

kinda wish i rememberd fully what i experienced but at the time i did feel like an engine bug so i decided to stop using it.
A shame as my code uses async a lot so would like to make use of it more.

hard acorn
#

are there no vc channels?

knotty sun
#

no

hard acorn
#

why?

#

that's shit?

wheat spruce
#

no reason for them to exist

#

not in a server like this at least

hard acorn
#

but for extended assistance maybe?

thin aurora
#

🎙️ Voice channels
We will not be adding voice channels. They are difficult to moderate, and also tend to benefit those not willing to put in effort to problem solve and describe their issues. If you are troubleshooting with someone willing to help on voice or video, take it to DMs.

#

If you want extended assistance, make a thread for people to join

wheat spruce
#

it also cuts off the amount of people that could help you, because not everyone has a mic to chat with

hard acorn
#

nah i was just curious

#

i don't do unity

thin aurora
#

So you joined this server just to check if there are voice channels?

knotty sun
#

So, you join a server for a product you dont use and say it's shit for not having voice channels, very strange attitude

thin aurora
#

I think they ask if we think voice channels are shit, not the server for not having them

knotty sun
#

doubt

flint agate
#

hey so can anyone check my script and tell me what's wrong with it? I want an ambulance to come from random direction which tries to passes through the player but before it comes, it should display a waring sign which is blinking for 3 seconds?

knotty sun
#

not if you don't post the !code, no

tawny elkBOT
flint agate
#

can you suggest me any Ai I could use for coding? need it for assissgment

atomic kindle
#

How can I fix this

thin aurora
atomic kindle
#

figured it out

#

shouldnt create square as gameobject but rather as a sprite in the assets folder

flint agate
#

just need it for C#, apparantly my brain is not so smart hahha

wintry crescent
#

brain is a muscle

flint agate
#

I tried, I'm learning but I'm kinda stuck so....

thin aurora
#

Then start basic. Try to follow a tutorial and try to deviate from it a bit with your own approach

flint agate
thin aurora
#

Then, as you go, try adding custom features or playing with the code to see what happends

wintry crescent
#

not AI

thin aurora
#

AI is not going to improve your situation

wintry crescent
#

yeah AI's a trap for programmers lmao

#

it just makes you worse long term

#

anything beyond simple autocomplete is ruining your brain further

knotty sun
tawny elkBOT
flint agate
thin aurora
#

I mean AI is going to severely fuck up your experience with programming in general. You're going to have plenty of unfixable bugs with no way how to debug them

wintry crescent
#

you haven't described an issue

thin aurora
atomic kindle
#

Should you have coding experience like a lot before unity

hard acorn
#

ig?

knotty sun
atomic kindle
#

cuz im legit rawdogging I only got like 3 motnhs of experience

hard acorn
#

i just wanna make a simple superhero game lol

hard acorn
thin aurora
#

If you have a coding question, ask it here

hard acorn
dusk apex
thin aurora
#

Otherwise continuing this is pointless

hard acorn
sage garden
#

Hey, how do I change the anti-aliasing property of a URP Asset?

flint agate
#

I pasted it, can you please check pls

hexed pecan
#

If you used a paste site

knotty sun
hard acorn
hexed pecan
hard acorn
azure terrace
hexed pecan
#

Did you copy the HTML of the paste site??

hard acorn
hexed pecan
#

@flint agate Don't save the whole website. Hit the save button on the site instead 💾

thin aurora
#

Lmfao

hexed pecan
flint agate
#

like this?

plucky inlet
#

!code

tawny elkBOT
wintry crescent
#

hey, you might have missed the proper way to send code here

#

this is really unwieldy to read

hexed pecan
#
  1. Paste your code into paste.ofcode.org
  2. Press "Paste it!"
  3. Copy the URL link from your browser and paste that here
wintry crescent
#

instead of just plainly pasting it

flint agate
hexed pecan
#

There we go

flint agate
#

Sorry I'm not a discord kid

#

sorryyyyyyyyyy

plucky inlet
#

So whats the issue?

hexed pecan
#

It's written below in the paste

// Error is that, the ambulance is not spawing properly and the blinking effect is not working as well and the ambulance should move throgh the player from any direction.///

#

What's wrong with the ambulance spawning?

plucky inlet
#

I was hoping for a bit more structure, as this is not one but three issues 😉

flint agate
#

😭

wintry crescent
#

the code seems... alright? everything should work

#

you have to specify what exactly doesn't

thin aurora
#

I expected way worse code

wintry crescent
#

same

thin aurora
#

This is fine

hexed pecan
#

"ambulance is not spawing properly" doesn't tell much

wintry crescent
#

probably some issues inside the editor...

plucky inlet
#

"properly", "as well", "should" are all words, that need to be explained by you to us, so we know what the meaning/result is, that you desire

flint agate
#

So the ambulance prefab is ready and so is the Warning sign,
So I want the Ambulance to move to the player but before it appears, it should display a warning sign which should blink for 3 seconds rapidly (Like a warning sign)

#

As, it can appear from any random location but with a warning sign before

hexed pecan
#

I can see code that should do all of that.

flint agate
#

For now it is not showing the warning sign, it is not moving or facing towards the player but and that is the problem

hexed pecan
#

Do you have any errors in the console when this code runs?

#

Show the inspector of this AmbulanceSpawner component

flint agate
#

this is the problem, there is error in console but not for this

leaden ice
flint agate
#

this is it

#

but it's not imp

leaden ice
#

That error is causing SpawnAmbulance not to run

flint agate
#

it is for the sound, which is not imp for me at the moment, I just want to fix this error

leaden ice
flint agate
#

how can I fix that?

leaden ice
#

it doesn't matter that it's for the sound

#

you need to fix the error

#

either comment out the sound code entirely or fix it

flint agate
#

I'll remove it

#

can you tell me which line is it please?

leaden ice
leaden ice
#

reading the full error

#

it shows you the files and line numbers involved

#

this is called the "stack trace"

copper oyster
#

Does anyone know how to implement borsh serialization in Unity?

heady iris
leaden ice
copper oyster
#

@leaden ice thanks

heady iris
#

ah, there you go

flint agate
leaden ice
#

if you can't understand the stack trace share it here and we can help you understand it

flint agate
#

okay so the error is but It's still now working

#

error is gone*

hexed pecan
flint agate
#

I got it thanks

wintry crescent
#

Not gonna lie, it's not often that I see an error that I've never seen in my life before
'/data/app/~~-blk_O6i4rRxmfamgpQRpA==/com.mycompany.mygame-vFfy7QH-qOt-Oi7GUr9EzA==/base.apk/assets/bin/Data/resources.assets' is corrupted! Remove it and launch unity again! upon launching a build of my game on an android phone

#

any ideas?

leaden ice
#

Though I guess maybe in this case since it's "resources.assets" it might be something in a Resources folder?

knotty sun
leaden ice
#

I would try just remaking the build to see if it happens again

wintry crescent
#

currently experimenting with a virtual machine

leaden ice
#

If you're able to connect android studio and read logs from your device then yes it's enough

wintry crescent
#

but it also happens on a real device

leaden ice
#

That's the same as the LogCat extension in Unity

knotty sun
wintry crescent
#

I'll see if I can get any specifics from it

#

ok it seems like a Resources.LoadAll call is broken for some reason

knotty sun
#

can you post the exact code
I wonder if that has to do with code stripping

wheat spruce
#

I just accidentally found I can do something that seems quite odd

    for(int i = 0; i < _cells.Length; i++)
    {
      (int x, int y) = Get2DCoord(i);
      _cells[i] = new Cell(x, y);
    }```the Cell is able to read the x,y value in the tuple, even though I havent done something like `(int x, int y) myTuple =` beforehand
wintry crescent
#

that'd save me some headaches

knotty sun
heady iris
knotty sun
wintry crescent
knotty sun
#
[assembly: UnityEngine.Scripting.Preserve]

just add it to one class

wintry crescent
knotty sun
#

odd, because that's exactly what I use

#
#if (!DEBUG)
[assembly: UnityEngine.Scripting.AlwaysLinkAssembly]
[assembly: UnityEngine.Scripting.Preserve]
#endif
heady iris
#

It can't be inside of a namespace, it looks like

knotty sun
#

yes, before namespace

wintry crescent
heady iris
#

I figured it could live anywhere

#

It looks like the "conventional" thing to do is to create a script file whose sole job is to hold assembly attributes

knotty sun
heady iris
#

it would be a bit annoying to have attributes in totally random places in your code

wintry crescent
#

But that didn't seem to have solved the issue...

#

still the same error :/

knotty sun
#

So what is the LoadAll statement which is failing

wintry crescent
#

it worked for a long time, and it works in the editor

knotty sun
#

zenject not my thing

#

at a guess there is a deserialization failure happening somewhere

regal compass
#

Does anyone have a squarerace game?

knotty sun
hexed pecan
#

Not sure if that's a unity question at all

rigid island
heady iris
#

i presume they're talking about this kind of thing -- which is, indeed, not a Unity question

rigid island
#

bro wants a turnkey project

knotty sun
heady iris
#

a turnkey solution ™️

knotty sun
#

sorry, read wants as whats

heady iris
#

(typo was corrected)

knotty sun
#

'Thrilling Racing with Colorful Squares' sounds like something for my 3 y/o grandson

gilded grove
#

dumb question, how do I subscribe to a teleportation event? I 'm trying TeleportationProvider.beginLocomotion += OnMyTeleportBegin and getting an error that 'no overload matches delegate'

rigid island
knotty sun
#

so what are the declarations of the event and the method

#

@regal compass Do NOT DM people without their consent

leaden ice
#

You have to look at how beginLocomotion is defined and make sure OnMyTeleportBegin matches the delegate type

hexed pecan
rigid island
#

lol

knotty sun
hexed pecan
#

I'm just messing around :P

rigid island
#

the turkey solution

gilded grove
#

it's an Action.. I guess I'm misunderstanding the purpose.

knotty sun
#

Turkey is also probably all the code you write, just messin with ya, lol

heady iris
#

System.Action is a delegate type that takes no arguments and returns nothing

#

Therefore, anything you subscribe to this event with must match that.

leaden ice
heady iris
rigid island
#

example

#

unless you have nothing for Action<T>, then don't put nothing

heady iris
gilded grove
#

public event Action<LocomotionSystem> beginLocomotion; in the XRI provided LocomotionProvider.cs
I guess I'm not understanding how to set the signature in OnTeleportBegin to match the LocomotionSystem type

rigid island
leaden ice
gilded grove
#

-_- I've been using a custom event bus and forgot how actions were constructed... thank you!

eager tundra
#

your IDE can also probably generate the correct function if you prompt it

gilded grove
#

gotcha, thanks all

hexed pecan
#

I would probably only set it when something changes, to minimize GPU bandwidth usage. Not sure if that's really an issue tho.

#

I'm pretty unfamiliar with how costly it is to update materials tbh

#

I'd imagine it takes some resources

#

Does it work without issues?

rigid island
#

Note that this is not compatible with SRP Batcher. Using this in the Universal Render Pipeline (URP), High Definition Render Pipeline (HDRP) or a custom render pipeline based on the Scriptable Render Pipeline (SRP) will likely result in a drop in performance.

hexed pecan
#

We don't know where isScaleChanged and isPositionChanged come from, but those are likely false here

#

Place a log there and see if its getting called

#

Do you set the bool(s) to false anywhere else?

#

Do some debugging to see if things are getting called/changed like you expect them to

#

I don't see anything wrong in the code snippets that you showed

#

Maybe the issue is that you are doing two SetPropertyBlock calls?

#

No idea though, just guessing

#

If you comment out the whole if(ísScaleChanged) block, see if the position change works

modern creek
#

I get this error periodically and can't track it down. I suspect(?) it's an editor bug but I'd like to ensure that I don't have any risk of game crashes for something I'm doing.

#

(can't repro this consistently)

#

6000.0.13f1 - so I could probably update my editor version but.. that's a hassle, so if anyone knows a more obvious fix, ❤️

knotty sun
#

Yes, that is an Editor bug however, I would question the attitude of someone who places 'hassle' over getting it right

modern creek
#

Well, if it's a "me" bug, that takes me just a little bit of time to fix. If it's an editor bug then we have to do a coordinated editor update across the project and team.. which isn't something we aren't used to, but it isn't something we want to do often.. ideally just a month or two before we launch a game so we can ensure it's stable.

#

"pragmatic time use" is probably the phrase I'd use

knotty sun
#

you are on 0.13, the current version is 0.33, nothing is gonna break and Unity are notorious for their crappy dev-ops methods

cursive lance
#

i got this weird bug and dunno how to fix it

#

basically it says the enemy has reached the end of its waypoints when it doesn t have reached the end yett and don t know how

modern creek
#

Paste the code that you're trying to delete the object. Seems like you're trying to delete a prefab instead of the object (copy) you made from it

cursive lance
#

yeah also a lot of repition in the code

#

cleaned it up a bit

modern creek
#

Why are you checking if the gameObject.scene.IsValid()? you don't need to do that? just delete the game object