#archived-code-general

1 messages · Page 254 of 1

somber nacelle
#

and it is in the build settings?

white jewel
#

yep

#

works in editor but not when the standalone build tests is running

peak grove
#

can anyone help me in this?

somber nacelle
peak grove
#

so i thought it might be okay to ask here caause i sent it earlier

somber nacelle
#

then be patient and stop crossposting all over the place trying to get people to answer in there

white jewel
#

I tried with:

SceneManager.LoadScene(0);

and with


 var gameplaySceneIndex = 0;

 AsyncOperation loadingOperation = SceneManager.LoadSceneAsync(gameplaySceneIndex);

 yield return new WaitUntil(() => loadingOperation.isDone);

both works in editor but not in standalone tests.

somber nacelle
#

have you checked the player !logs to see if there are any errors reported?

tawny elkBOT
#
📝 Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

white jewel
#

everything seems to be okay, no errors, also I saw it's loading the game scene in logs! So context of build scenes seems to be okay too. I guess there is different scene loading handling somehow?

Opening scene 'Assets/Scenes/GameplayScene/GameplayScene.unity'
LightingSettings: switching bake backend from 1 to 2.
Unloading 1 Unused Serialized files (Serialized files now loaded: 0)
Loaded scene 'Assets/Scenes/GameplayScene/GameplayScene.unity'
    Deserialize:            4.469 ms
    Integration:            187.602 ms
    Integration of assets:  0.155 ms
    Thread Wait Time:       0.012 ms
    Total Operation Time:   192.238 ms
Unloading 1 unused Assets / (0.5 KB). Loaded Objects now: 7606.
Memory consumption went from 212.7 MB to 212.7 MB.
Total: 10.490500 ms (FindLiveObjects: 0.579000 ms CreateObjectMapping: 0.420200 ms MarkObjects: 9.464400 ms  DeleteObjects: 0.025900 ms)
#

it's showing for 1s instead my gameplay scene 🙂 so it seems I am simply trying to do something wrong. I will go with editor play mode tests intsead.

earnest gazelle
#

Is it more appropriate and common to pass event args data as snapshot? I mean create a new instance and then pass it to listeners so that they see the event raiser state just in that moment

hidden smelt
#

Hi. I did not find any channel for infra topics tangentially related to Unity. So apologies in advance if there is a more appropriate channel (or other discord server) for this question:
I've been designing/implementing a process for automated VFX and other performance tests using the Unity Test Framework and Performance Testing packages. I am able to run those tests from shell and obtain a results.xml file containing log messages and raw timing data from the performance tests. I could use a custom script to extract the data from that file and insert it into some other database or system to analyze it.
My question: Does anyone know of any good databases or systems designed for ingesting performance/profiler measurements like these, which would allow analysis and monitoring over time for performance improvements or regressions? I'm not sure which keywords to search for.
I stumbled on Prometheus, but that and its kin seems more oriented toward continuously monitoring webservices metrics rather than performance measurements related to one build artifact or batch job, so I'm unsure if it is relevant to my use case. I'm wondering if anyone here has any experience in this area and any recommendations.

worldly hull
#
private void AssignContentCard(GameObject parentObj, Material contentSidemat)
  {
    GameObject ContentSideCard = parentObj.transform.GetChild(0).gameObject;
    //reset shader for urp mat, it  may set in prefab when all game change to urp
    ContentSideCard.GetComponent<MeshRenderer>().material.shader = contentSidemat.shader;
    ContentSideCard.GetComponent<MeshRenderer>().material.mainTexture = GameManager.Instance.GetNoNumber_NumberTextureByNumberTexture(contentSidemat.mainTexture as Texture2D);//get no number card texture

    if (contentSidemat.shader != Shader.Find("Universal Render Pipeline/Lit")) { return; }

    ContentSideCard.GetComponent<MeshRenderer>().material.SetFloat("_AlphaClip", 1);
    ContentSideCard.GetComponent<MeshRenderer>().material.SetFloat("_Cutoff", 0.1f);
  }

  private void AssignBackSideCard(GameObject parentObj, Material backSidemat)
  {
    GameObject BackSideCard = parentObj.transform.GetChild(1).gameObject;
    //reset shader for urp mat, it  may set in prefab when all game change to urp
    BackSideCard.GetComponent<MeshRenderer>().material.shader = backSidemat.shader;
    BackSideCard.GetComponent<MeshRenderer>().material.mainTexture = backSidemat.mainTexture as Texture2D;//get no number card texture

    if (backSidemat.shader != Shader.Find("Universal Render Pipeline/Lit")) { return; }

    BackSideCard.GetComponent<MeshRenderer>().material.SetFloat("_AlphaClip", 1);
    BackSideCard.GetComponent<MeshRenderer>().material.SetFloat("_Cutoff", 0.1f);
  }```

here are two functions that will reassign shader and reconfigure materials of certain gameobject

**it is already proven that the above functions work perfectly for ios/android/windows platform , however, only mac os build contains certain glitch (material is not updated properly)**
#

also, no preprocessor such as

#if UNITY_IOS``` stuff like these included
#

and on built app logs, the code also executed , i can tell from the debug log

#

even if im using mac os, it works well on editor, but glitched when built out as application

west ingot
#

So I'm in the process of trying to make a physics engine what i want to do is detect a left and right input from the mouse and make it so that it stores that value Into a variable does anyone know how one would do that?

amber scroll
worldly hull
#

this is the correct result

#

this is the glitched out result

west ingot
amber scroll
amber scroll
#

You want to get mouse pos, right?

worldly hull
west ingot
placid summit
#

hi which version of C# (and Unity) did this become allowed: List<Vector3> list = new(); //i.e. new() simplified constructor call

amber scroll
placid summit
#

no I can do it no problem - but now I can do new() instead of new List<Vector3>() I am asking when the c# support for that came

west ingot
#

Because that doesn't work straight up

amber scroll
amber scroll
worldly hull
# amber scroll Both of them

background: this project is on built-in renderer pipeline, however, we reconfigured a specific scene to use URP only, and its that scene gone wrong

the code above is actually changing the standard shader from BRP to lit shader to URP ,and then assign a texture as base map to it, it is not good, but works out in all other platforms

amber scroll
placid summit
somber nacelle
amber scroll
placid summit
amber scroll
worldly hull
#

so if i pre-change the shader, all other scene will have problems lol

placid summit
#

well I should have checked manual! I usually ignore new C# features until I realise I can save a load of typing or something!

#

also because VS keeps warning me of what I can do

worldly hull
#

but i think i will keep work on it tmr, thx 👍

west ingot
#

Is unity safe because ive heard about the potential risks

amber scroll
worldly hull
amber scroll
#

And for what

placid summit
amber scroll
#

I personaly dont know xd, but i dont like their tos so im stuck to old version

worldly hull
#

so all the settings and codes are default to renderer pipeline

#

im new to the team, but i think they use code to change it to URP because its fast?

#

like they dont bother to set or create another set of material/shdaer?

amber scroll
#

Just, change each individual material to URP

#

Yes, it will take time, but than you/yourTeam wont have problems

#

And it would be more preformant and smaller game size

worldly hull
#

cant, our team planning on a release in next 1-2 weeks to our boss

amber scroll
#

How much materials are there?

worldly hull
#

its a poker game

#

52

#

with 5-6 background?

amber scroll
#

Change them to URP without any code

worldly hull
#

but were using the same materials on other scene, the same materials are used in both URP and BRP scenes

amber scroll
#

If you keep having problems with type of codes even tho you can manualy change materials, it would take you less time if you do it manualy

worldly hull
#

aight

placid summit
#

I did not think you can mix render pipelines in a project yet - I thought that was on future list

worldly hull
#

i will talk to the team

amber scroll
#

Change all scenes to URP

worldly hull
#

theres one scene that is URP, but all other scene is built-in render

#

idk how they did it, buuuuuut

amber scroll
#

Tham change all to built in renederer

worldly hull
#

ok

amber scroll
#

Keep it simple, dont use 2 renderers

#

And those code for changing materials in runtime, dont do it, it could cause problems and delay the team even more

#

When i need to change the rendered, i change all materials manualy, thats why i keep all materials in seperate folder, so i can do ctrl+a and change them

placid summit
#

If someone decided to add a URP scene and not convert the whole project, well it seems a bad idea in middle of it

amber scroll
#

I guess by break is over and i can continue on engine(combustion) physics

worldly hull
#

either BRP or URP

#

but after our first release lol

amber scroll
#

Np

worldly hull
#

what makes it interesting is the team dont even have an exact answer of why changing a scene to URP in first place lol

amber scroll
#

Xd

trim schooner
#

Debug it.. put logs in various places to figure out what's wrong

#

Log inside the if (distance) and log out the values for current pos and target pos

#

and don't cross post, keep it in begginer

lyric atlas
#

Currently I have a fighting game system where certain events can be fired at points in an attack using frame data, right now I do this in fixed update but that limits me to 50fps (as I don't want to break any physics by changing the fixeddeltatime). I'd like to move over to just doing it in regular update and manually setting the time for 1 frame so it's independent of the actual frame rate but I'm unsure how to handle frame skipping or lag.

If for whatever reason one frame had a high deltatime due to lag, it could cause all of an attacks events to trigger but at the same time, at the end of a move which is undesirable. Is the best way to fix this to somehow set a minimum frame rate so it slows down below a certain target? and if so should this be done with targetFrameRate and is there a way to set this as a lower bound (keep fps uncapped)

The other solution to this is just limit fps to 60 or whatever is desired, however this is a hack and slash game so I'd like to keep the frames uncapped where possible if it is

south saddle
#

I want to steal this naming convention from Godot and use underscore in methods that are only meant to be called in ONE place. In this case by a pooling system. (In Godot they are used for engine methods) Do you guys think it's unnecessary? Bad idea? Good idea?

namespace Game.Core
{
    public class PoolObject : MonoBehaviour
    {
        [AutoAssignFromChildren][SerializeField] private List<ISpawnCallbacksReciever> _spawnCallbacksRecievers;

        public event System.Action OnSpawn;
        public event System.Action OnDespawn;

        public void Awake()
        {
            foreach (var item in _spawnCallbacksRecievers)
            {
                OnSpawn += item.OnSpawn;
                OnDespawn += item.OnDespawn;
            }
        }

        public void _OnDespawn()
        {
            OnDespawn?.Invoke();
        }

        public void _OnSpawn()
        {
            OnSpawn?.Invoke();
        }
    }
}
amber scroll
#

What??

#

You want to have one script that you can call functions/programs from it?

south saddle
#

Yeah, that's why I'm doing a sanity check on this. Initially I did it to avoid conflict between OnSpawn method and OnSpawn event, but now think that there is sth to it. GPT tells me it's a quite common practice..

south saddle
amber scroll
#

Hum

south saddle
#

Reflection would be even more weird. But the point is that there are a lot of classes that are widely accessible that have methods that no one but one system is meant to be calling.

amber scroll
#

So you want to call a code from another script

#

Like an "utilities" script

south saddle
#

Pooling system needs to call poolObject.OnSpawn() and no one else

amber scroll
#

Ah, you are using a pool

south saddle
#

in this case yes, but there are many other cases like this

amber scroll
#

Sadly, idk how is your pool made, so i cant really help you, ya know

#

But from just looking at it, the code looks fine to me

south saddle
#

So I'd appreciate more opinions about this (the underscores) being weird or not 🙂

        public void _OnDespawn()
        {
            OnDespawn?.Invoke();
        }

        public void _OnSpawn()
        {
            OnSpawn?.Invoke();
        }
amber scroll
#

Thats nostly what i would write if i would need to call an function, so the thing you have should be gut

hard viper
#

the underscores should only be used on fields

#

(and usually only backing fields)

#

but never on methods

south saddle
#

I'm well aware that it breaks convention, so the question is: is the new established convention worth it? 🙂

knotty sun
#

Do what ever makes you feel comfortable and sod other peoples conventions, they're generally nonsense anyway

south saddle
#

Basically if method has an underscore, don't touch it, it is called from one single location only.

knotty sun
#

The most important thing is, be consistent

south saddle
south saddle
knotty sun
#

I can tell you, having worked on hundreds of projects, the only ones which followed the same conventions were the ones where I was project lead and I decided what the conventions for the project would be

south saddle
knotty sun
#

That sounds extremely unprofessional. Bear in mind conventions are an agreed lunacy, as long as everyone on the team is equally as mad it does not matter one iota what the actual convention is

scarlet viper
round violet
#

how can I check if a stored ref of a gameobject is enabled ?
without using .enabled

knotty sun
#

gameobjects are not enabled they are active, so activeSelf or isActiveInHeirarchy

#

btw, this is something you could easily look up in the docs, that is why they exist

round violet
fringe ridge
#

What way would you recommend for me to approach flag integration to my game? I have the player region names, so I though i could search for a flag pack that provides sprites of all the flags with letter codes as the sprite name. One thing is that it would require to constantly load the sprites from the files

#

A scriptable object? But to map 160+ flags would be a torture

steady moat
fringe ridge
#

yeah, one time script that generates that scriptable object i guess

knotty sun
fringe ridge
#

you mean as to not have all the 160+ flags sitting in the project

neat forge
#

You could also just load them when you need them and then cache the sprite. Or load them all at startup if on demand loading doesn't work for you

steady moat
#

Addressable is able to handle on demand loading with minimal effort.

knotty sun
steady moat
#

You could even download image if necessary with addressable.

fringe ridge
#

It's not a good idea to download. If leaderboard is populated with 10 different flags it could take some time

#

i mean, the images are 500 bytes each

#

all of them are like 200 kb, not a huge problem to have them in a separate folder extracted

steady moat
#

If you are on mobile, you might need to download your resources beacuse you cannot publish a game with a size higher than 50m I believe on the Goolg Store ?

fringe ridge
#

200

#

currently sitting at 90 something for the apk file. It's almost finished

steady moat
#

The file size limit is now 50MB for APKs that target Android 3.2 and lower (API level 13 or lower)

fringe ridge
#

bro xd api 13 is like 10 years old

#

im targeting 29 +

#

published before 2021 august was 100, now 200

steady moat
#

You are the one that choose. I'm simply giving you the information. Addressable can eventually solve those issue.

fringe ridge
#

thanks, i'd try downloading from addressables if i come into an issue with the flag sizes, but i doubt it

mortal summit
#

i have a problem relating to triggers.
I have a ability shooter where i have a ray ability (I spawn in a collider for 3 seconds) and on trigger enter on that collider i check if the collision is with an enemy and then i trigger damage.
i move the rotation of the ray with

var lookDirection = (_castingPoint.position - target).normalized;
var lookRotation = Quaternion.LookRotation(lookDirection) * Quaternion.Euler(0, 90, 0);
transform.rotation = lookRotation;

and i move the enemy with a navMesh Agent
but for some reason it triggers trigger enter and then immediately trigger exit and then trigger enter and so on even though they are colliding all the time.

i tried making the rb of the enemy kinematic which didnt help.
dose anyone have any ideas on what is wrong / could be wrong?
(first on is the enemy, second one the ray)

fringe ridge
#
 AsyncOperationHandle<IList<IResourceLocation>> handle = Addressables.LoadResourceLocationsAsync("Flags");
 await handle.Task;
 IList<IResourceLocation> locations = handle.Result;
 Debug.LogError(locations.Count);
``` why is this not working? I tried everything at this point, count is always zero
leaden ice
#

you need to wait for the overation to finish before results will be available

fringe ridge
#

isn't await handle.task handling that?

heady iris
#

isn't it looking for things labeled with "Flags"?

fringe ridge
#

i don't understand why it has to be this complicated. All i want to do is load all the addressables in a group. Now i have to load the locations, then iterate through them and get the addressables seperately by the path

fringe ridge
heady iris
#

label them all as "Flags" if you want to load them with a key named "Flags"

#

Groups are uesd to organize your addressable assets

#

Addressable Groups only exist in the Unity Editor. The Addressables runtime code does not use a group concept. However, you can assign a label to the assets in a group if you want to find and load all the assets that were part of that group. See Loading Addressable assets for more information about selecting the assets to load using labels.

#

If all of these are in a folder, you can give the folder itself a label

leaden ice
fringe ridge
#

ah, sorry. Thanks

#

thanks @heady iris that worked. It turns out id rather struggle for an hour than read documentation for 5 minutes :/

unreal sonnet
#

Hi guys, what is the best way of dropping items from an Inventory? Right now i got an inventory system that stores ID's of items. I was thinking i could use those ID's to instantiate them from prefabs, but would that be a good way of doing it?

spring creek
leaden ice
unreal sonnet
#

Oh hellyeah, for some reason i felt like there would be something terrifyingly bad about this approach but i guess not

#

thanks guys

swift falcon
leaden ice
teal delta
#

can anyone tell me why my enemies jitter when they move? im using simple rb.addforce method to move them ( movement is declared in the Update method but when i declared it in FixedUpdate it didnt change anything)

spring creek
teal delta
spring creek
teal delta
spring creek
tawny elkBOT
spring creek
sterile mirage
#

hi! i'm currently making a player movement script and it's working... BUT when rotated based on input, the new rotation is not the new forward, so it's relative to the global forward i presume, is there a way to set the last direction to new forward direction? here's the part of my code

     void Update() {
        HandleMovement();
    }
    private void HandleMovement() {
        Vector2 inputVector = GetMovementVectorNormalized();
        // sets direction based on vector input
        Vector3 moveDir = new Vector3(inputVector.x, 0f, inputVector.y);

        float moveDistance = moveSpeed * Time.deltaTime;
        float playerRadius = .6f;
        float playerHeight = 2f;

        //if nothing collides canMove = true
        bool canMove = !Physics.CapsuleCast(transform.position, transform.position + Vector3.up * playerHeight, playerRadius, moveDir, moveDistance);

        if (canMove) {
            transform.position += moveDir * moveDistance;
        }
        isWalking = moveDir != Vector3.zero;

        if (isWalking == true) {
            playerAnimator.SetBool("isWalking", true);
            Debug.Log("is running");
        } else{
            playerAnimator.SetBool("isWalking", false);
        }

        float rotateSpeed = 10f;
        transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * rotateSpeed);
}

    public Vector2 GetMovementVectorNormalized() { 
Vector2 inputVector = playerInputActions.Player.Move.ReadValue<Vector2>();
        inputVector = inputVector.normalized;
        return inputVector;
    }
teal delta
spring creek
#

The transform is fighting the rigidbody

teal delta
hard viper
#

depends on the rigidbody

#

setting rigidbody.rotation teleports the rb, transform, and all colliders to that orientation immediately, and does NOT respect collisions

#

rigidbody.MoveRotation tells a kinematic RB to move towards that target rotation during the next physics simulation, while respecting collisions

#

rigidbody.AddTorque allows you to add torque to rotate a dynamic RB in a certain direction

teal delta
hard viper
#

it’s really dangerous to use unless you are really teleporting

teal delta
#

alright thank you @spring creek and @hard viper! that was really helpfull

hard viper
#

you can clip into a wall, and it won’t stop you from doing it

#

there is no resistance. you’re just saying “I want you like this, now, and don’t ask questions.”

#

MoveRotation is like moving the object with infinite mass. It will go to that rotation, while plowing anything out of its way, and not being stopped.

teal delta
#

well then how can I set up something simillar to my previous function but with rigidbody? I kinda don't know where to start

hard viper
#

AddTorque just adds force, which applies if you have a rigidbody that is affected by and responds to forces from many thigns

#

depends on how you want something to move

teal delta
hard viper
#

if you have a gameobject with colliders, and it moves, you want to give it a rigidbody, or else unity’s physics system won’t acknowledge its motion

#

colliders in the scene won’t respect its motion during physics simulation

#

first you need to decide how you want it to move

teal delta
#

im moving it with rigidbody.AddForce

hard viper
#

do you want it to push things while never getting pushed back?

#

so it’s dynamic

#

that is tricky

teal delta
hard viper
#

does the shape have rotational symmetry in the axis of rotation

#

eg capsule collider rotating along its long axis

teal delta
#

i have circle collider

hard viper
#

and the rotation is about the center of the circle

#

and there are no colliders attached to it (that are not circle colliders at the same center)?

teal delta
#

here is my enemy setup

#

and its just sprite with this and scripts attached

sterile mirage
hard viper
#

but this sounds like the sprite should rotate, and not the rigidbody

#

eg sprite is on one gameobject that rotates, which is parented to the RB

teal delta
#

i managed to do this

#

rb.MoveRotation(Quaternion.LookRotation(rotation));

#

rotation = target.transform.position - transform.position;

#

and it works very smoothly

hard viper
#

if your rigidbody is dynamic, that is a bad idea

teal delta
#

why

hard viper
#

MoveRotation will override other shit you have going on

teal delta
#

oh

#

well then

hard viper
#

idk if it is different for 3D, as I specialize kn 2D

teal delta
#

thats good coz this game is in 2D

#

could you help me do it with rb.rotation?

hard viper
#

MoveRotation overrides velocity etc

#

at least I know that to be true for translation. not super sure about rotation

teal delta
hard viper
#

if you say velocity = (1,0), and you say MovePosition to a point 2 units up, then the next frame, you’re ass is going directly 2 units up

#

idk if MoveRotation has like a separate channel, since i try to avoid rotation in my game

#

i assume it has a separate channel that then overrides angular velocity, which then makes angular accelleration and torque not apply for that frame

hard viper
teal delta
#

can I use quaternion.lookrotation?

leaden ice
teal delta
#

then I honestly have no idea how to rotate object to its moving direction

leaden ice
teal delta
#

i tried with transform.right, rb.moveRotation and thats basically all im semi famillar

teal delta
#

because transform.right messes with rigidbody or something

leaden ice
#

then something like

var dir = rb.velocity.normalized;
float rotation = Mathf.Rad2Deg * Mathf.Atan2(dir.y, dir.x);
rb.MoveRotation(rotation);```
#

this is assuming it's a Rigidbody2D

teal delta
#

but loup@snoop said that rb.moverotation overrides all my movement calculations. I mean it works fine but im kinda worried that its gonna bit me in the ass in the future

teal delta
teal delta
leaden ice
#

MoveRotation accepts a float in 2D

#

not a Quaternion

#

and that quaternion wouldn't be correct anyway in 2D

teal delta
#

ahh

#

alright i get it now thanks

#

lets see if this will work

teal delta
#

(its called in the update method)

leaden ice
#

It will be interpolated if interpolation is enabled for the RB

teal delta
#

alright its smooth now but its rotation so slowly, like excavator. Why is that?

leaden ice
#

I guess your object is not changing directions very quickly?

teal delta
#

yeah

#

is that drag fault?

leaden ice
#

that would have to do with how your velocity is set, not this code

teal delta
leaden ice
#

then I don't really understand the issue

#

how is the object moving?

#

just gravity?

teal delta
#

yeah, just rb.addForce

leaden ice
#

that's the only thing AddForce does

teal delta
#

oof

#

i forgot

#

Would you like to see my code?

leaden ice
#

I'd like to understand the issue exactly

teal delta
#

ill record you this, wait a sec

#

and his rotation changes when he hits a wall

dusky pelican
#
    {
        Application.targetFrameRate = 60;
        SaveGameManager.LoadGame();
        foreach (var loadable in _saveables)
        {
            loadable.LoadData();
        }
        OfflineManager.instance.OfflineIncome();
    }```

I want to run `OfflineManager.instance.OfflineIncome();`, when foreach loop done. How can i make this?
leaden ice
#

code runs in order from top to bottom

dusky pelican
#

Yeah, i have a race condition problem i think cause it's not working right.

#

When i make like this

    {
        Application.targetFrameRate = 60;
        SaveGameManager.LoadGame();
        foreach (var loadable in _saveables)
        {
            loadable.LoadData();
        }

        await SomeAsyncOperation();
        
        OfflineManager.instance.OfflineIncome();
    }
    
    async Task SomeAsyncOperation()
    {
        await Task.Delay(2000);
    }```
leaden ice
#

is the data loading launching some async thing?

dusky pelican
#

Yes

leaden ice
#

oh well that's a totally different question then

dusky pelican
#

Actually, it's not loading async. Just i want it to make async

#

Should i remake all entire all saving system?

#

Or is there a way to just make sure all LoadData functions done?

leaden ice
#

await their Tasks, assuming they return a Task

low fox
#

does anyone have any suggestion on what should i do if i want to have a laser rotate to the player position(the player will be moving) at a certain speed?
note i have the laser working, i only need to configure the rotation.
thanks :)

somber nacelle
#

Slerp it's rotation

lean sail
low fox
west lotus
#

Did you do a while loop?

low fox
#

Only void update

lean sail
#

Blue screen is probably unrelated to unity.. I'd hope

#

Or I mean unrelated to your code in unity

low fox
#

it is defiantly unity. happened 2 times few seconds after i pressed play

heady iris
#

The first thing that comes to mind is a GPU problem

lean sail
heady iris
#

but that usually just results in your display resetting and windows getting mad

gusty wedge
#

'Item' does not contain a definition for 'Reload' and no accessible extension method 'Reload' accepting a first argument of type 'Item' could be found (are you missing a using directive or an assembly reference?

tawny elkBOT
gusty wedge
#

can i get some help with this ive been working on this for a while, i think the issue is that i need to be getting the gun class from the item but i dont know how

#

mb one sec

rigid island
#

I mean you should probably configure your IDE first..

#

also don't post screenshots of code

simple egret
#

Reload is commented on the base Item class. You do not need to re-declare abstract methods in the inheriting abstract Gun class

gusty wedge
#

i commented it out because i wanted to rework the way i did things to clean it up

#

i didnt want to keep adding functions to the item class when i inevitably add more item types

simple egret
#

items is from what I can see, an Item[] or List<Item> (or any other collection), so it indeed cannot find a Reload() method on the Item class

#

If it was a Gun[], it would pick up the method fine

gusty wedge
#

is there a way i can get the gun class from the item class?

simple egret
#

Yes but that's just not using inheritance properly

#

If you have to type-check whether it's one of the many inheriting classes, you're doing it wrong

heady iris
#

Inventories are a place where downcasting gets really tempting

#

if you just store a big List<Item>

#

"downcasting" is when you cast from Parent to Child

#

"upcasting" is when you cast from Child to Parent

#

an up-cast always works; a down-cast may fail (what if you have a Sword instead of a Gun?)

gusty wedge
#

my solution was that little string itemType

#

what should i be doiung then?

hard viper
#

i will sometimes do that for really small things, in very specific little classes that only handle 1 or 2 items

#

never in an inventory

simple egret
#

You already have Use and Use2 which seem like two methods for implementing some generic action happening on the item, why not use one of these? Or make another?

low fox
gusty wedge
hard viper
#

if you have a collection of objects with different code on them, then use an interface

gusty wedge
#

thanks for the help guys

hard viper
#

like
public interface IHealingItem { public void Heal(); }

(item as IHealingItem)?.Heal();

if (item as IHealingItem healer) {
healer.Heal();
}

#

if item is not an IHealingItem, the as is null, and the ? makes it do nothing.
If it is, then this calls Heal()

simple egret
#

The code you had before the edit looked much better

hard viper
#

there are a few ways tbh

simple egret
#

But this is equivalent to downcasting after all

hard viper
#

if you want to downcast, you want to at least make it smooth, and do it very infrequently

#

downcasting in general is mildly bad juju

#

you might get a few cavities, but your teeth won’t all fall out.

spring flame
#

How do I reliably detect when a game object was changed in hierarchy? (added/removed/moved/renamed)

#

it can be either the child itself or some "root" parent

hard viper
#

i don’t think you can

#

unless you ask the factory, and listen to the creation of everything

spring flame
#

I am gonna mention that I mostly need it in editor, for runtime it's to-be-decided

hard viper
#

which is a bad idea

spring flame
#

i know of at least one idea, and that is unity editor event → hierarchy changed or something

hard viper
#

unity doesn’t believe in useful events for you to use

heady iris
#

I think downcasting feels less "evil" when you can perform a meaningful action with every single possible downcast, and when you cover all possible downcasts

#

...wait

#

that's just a virtual method call

#

🤔

#

I have to do it for the inventory system in one game, since I have a few arrays of presently-equipped items (melee, ranged, consumable) that new items need to be sorted into

neon plank
#

Anyone knows a guide about how to voxelise meshes? With voxelise, I mean construct a boolean array where I mark true/false depending if the cell contains a mesh or is inside one.

spring flame
#

want a proven solution, battle tested and performant? → look for a library that can do that for you
want a simple bruteforce idea? → for AABB of a mesh, for voxel size S, iterate 3d space with increments S (center of cube), check if point is inside mesh (there are libs for that), generate bool array

#

and in unity you can use mesh collider for checking if point is inside/outside the mesh

maiden lake
#

can soem one help me i want to W8 befor seting it true so it is not spaming atack or block i want to stop for some time before randomly desiding which animation to play (its for AI )

leaden ice
maiden lake
leaden ice
#

but also your animation apears to be set to loop

#

and/or doesn't have a proper transition back to idle

maiden lake
#

thx

leaden ice
#

probably should be using Triggers and not Bools

#

and with Trigger you don't ever need to manually set it back to false yourself

dim crypt
#

I'm having an issue with Interfaces where if a function in interface is not being used it doesn't create an error that you can only resolce through implemeting that function.

somber nacelle
dim crypt
#

Thank you that makes complete sense. Am getting the error now which allowed me to implement the function and solved another issue i was having as well. Thanks @somber nacelle

heady iris
#

I'm reevaluating how I use state machines right now. I'm wondering if I've missed the point a little.

Each state has CanEnterState and CanExitState properties. I mostly just explicitly enter states -- if the player pushes the "punch" button, then the player enters the PunchState, and the PunchState tries to re-enter the IdleState after it's done

#

But this falls apart if I introduce a GrappleState that still lets you punch things while in the middle of it

#

now PunchState wants to return to IdleState, which is wrong

#

and ignoring that, even if there's a state like GrappleSlapState, that state still needs to explicitly know about GrappleState

#

so that it can return to it

somber nacelle
#

you could store the previous state and allow states to transition back to that

heady iris
#

That's one thing i've considered: basically a state machine with a stack

#

The tricky thing is that the machine could be interrupted at a weird point

#

like if you get thrown in the middle of GrappleSlapState

leaden ice
#

ehhhh sounds like the punch/grapple thing needs to be a different state than the regular punching

heady iris
#

you should go straight to RagdollState and then eventually get back up into the IdleState

leaden ice
#

even if there's a state like GrappleSlapState, that state still needs to explicitly know about GrappleState
so that it can return to it
Not sure I follow this issue or why it's an issue

heady iris
leaden ice
#

When you say "know about" - you mean have a reference to?

heady iris
#

Right.

leaden ice
#

generally I would use enums or have all the states be accessible from the StateMachine itself or the manager or whatever, which all the states should have access to

heady iris
#

i want the player to be able to do this in a lot of contexts

#

it would be very silly to have a MakeNoiseState and a MakeNoiseWhileSittingState and so on and so forth

leaden ice
#

A "pure" state machine would do that. But for practical reasons yeah it wouldn't be a bad idea to pass in a variable of some kind to the noise state to tell it what to transition back to at the end

heady iris
#

One alternative I played with once was to just have a multiple state machines

#

it kind of maps nicely to different body parts

#

like, if your head state machine is idle, you can whistle even if your body is busy doing something else

#

but that's kind of A Lot

iron pumice
#

Is there any way to get a file from the game directory? I remember we had to use the Resources folder some time ago, but nowadays I'm not sure.

heady iris
#

Resources is used to load Unity objects by name.

#

It's not used to load files

#

You won't be able to load the files that are lying around your Assets folder when you build your game -- the imported data gets packed into a few big archives

iron pumice
#

so for example, I want to load a physics material to set it as default in my code (and not having it public), which technically is a Unity object

heady iris
#

In that case, yes, you can place a Physic Material asset in a Resources folder

#

then load it by name

iron pumice
#

does using Resources still lead the files to be a little exposed? I remember people being worried that the files there weren't as compressed as other files in the game.

heady iris
#

I would expect them to be packed in the same way as the rest of your assets

somber nacelle
heady iris
#

the individual files definitely do not exist on disk, because Unity doesn't actually ship the files in your Assets folder. it interprets them as data Unity can understand and ships that

iron pumice
#

I see, well resources is the way then, thank you for pointing it out

heady iris
#

with the exception of StreamingAssets, which is just copied into the built game

rigid island
iron pumice
iron pumice
rigid island
#

exactly more important just to make the game

heady iris
#

ok but what if I bikeshedded my state machines for another week instead

hard viper
# rigid island exactly more important just to make the game

You only see a small glimpse of the code someone makes. It is reasonable to assume it is their style, and that if the style in this little glimpse is bad, then it's reasonable to assume that the rest of their project also has code that is bad.

#

so it is important to get into the fine details for that little time you have with someone.

rigid island
glacial epoch
#

is anyone using the Unity 2023.3 beta and getting an issue where you can't make a serialised list of a custom serialised class?
want to sanity check before making a bug report

somber nacelle
#

what is happening when you try?

leaden ice
#

Also double check there are no compile errors in the Unity console

glacial epoch
#

Getting this:

NullReferenceException: Object reference not set to an instance of an object
UnityEditor.PropertyHandler.HandleDrawnType (UnityEditor.SerializedProperty property, System.Type drawnType, System.Type propertyType, System.Reflection.FieldInfo field, UnityEngine.PropertyAttribute attribute) (at <3bf9c75f4a524443a2e108b12e2dd503>:0)
UnityEditor.ScriptAttributeUtility.GetHandler (UnityEditor.SerializedProperty property) (at <3bf9c75f4a524443a2e108b12e2dd503>:0)
UnityEditor.UIElements.PropertyField.Reset (UnityEditor.SerializedProperty newProperty) (at <3bf9c75f4a524443a2e108b12e2dd503>:0)
UnityEditor.UIElements.PropertyField.Reset (UnityEditor.UIElements.SerializedPropertyBindEvent evt) (at <3bf9c75f4a524443a2e108b12e2dd503>:0)
UnityEditor.UIElements.PropertyField.HandleEventBubbleUp (UnityEngine.UIElements.EventBase evt) (at <3bf9c75f4a524443a2e108b12e2dd503>:0)
...

from this:

[System.Serializable]
public class SpawnGroup
{
    public string Name;
}

[CreateAssetMenu(fileName = "LevelDefinition", menuName = "Definitions/LevelDefinition", order = 1)]
public class LevelDefinition : ScriptableObject
{
    public List<SpawnGroup> spawnGroups;
    public ILevelCellsProvider levelCellsProvider;
    
    public void GetLevelCells(ref Dictionary<Vector2Int, LevelCell> cells)
    {
        levelCellsProvider?.GetLevelCells(ref cells);
    }
}
leaden ice
#

Any compile errors in console?

glacial epoch
#

Seems it's crashing when doing HandleDrawnType cause it passes it a null attribute, then tries checking attribute.applyToCollection without checking for null first

#

Nah, no compile errors

#

I am getting a persistent memory leak when it's trying to display the serialised data though, I don't think that's me though (nvm, it's not consistently doing that)

odd arrow
#

is there any way I can use my .net 8 library in unity or do i have to revert a crap ton of stuff to fit the older unity .net version

unkempt meadow
#

So one of my zombies is a navmesh agent who uses rootmotion movement. When I pause the game (timescale 0), I get a critical error where his navmesh agent synchronizer returns a ''velocity is nan'' error, probably as a result of division by 0.

What can I do realistically in this situation, other than not make my pause a timescale 0?

somber nacelle
# odd arrow is there any way I can use my .net 8 library in unity or do i have to revert a c...

i'm almost 100% positive that you would not be able to. you likely have to target the same .net API that your unity version is or older.
of course you can always just test it yourself either by trying to use the library in your unity project or by creating a .net standard or .net framework project targeting the same version your unity project targets and see if you can use the library there

odd arrow
#

damn that sucks

somber nacelle
odd arrow
#

i've gotten accustomed to all these new c# 12 features this is gonna be awful

unkempt meadow
somber nacelle
#

and yet it's still the best option

unkempt meadow
#

what else do you suggest

#

other than not pausing the game when pausing the game

somber nacelle
unkempt meadow
somber nacelle
vagrant blade
#

But YouTube said!

unkempt meadow
#

I'm sure it's possible, just with a lot of work involved

reef garnet
#

I need help with SphereCasts, I'm using one to detect the ground and the reason I'm using SphereCasts is because I want to get the nearest point of contact with the ground but I'm running into this weird issue I can't explain where the isGrounded bool flags false when you're near the edge of the mesh as shown in the video

Here is my code:

private void FixedUpdate() 
{
    isGrounded = IsGrounded();
}

public bool IsGrounded()
{
    // Check point of contact with last collider in array
    
    if (useSphereCast)
    {
        return SphereCastGround();
    }

    return OverlapSphereGround();
}

bool SphereCastGround()
{
    Vector3 origin = groundCheckOrigin.position - gravityDirection.normalized * Physics.defaultContactOffset;


    bool groundCast = Physics.SphereCast(origin, segmentRadius - Physics.defaultContactOffset, origin + gravityDirection.normalized, out RaycastHit hit, maxGroundDistance, groundLayers);
    groundPosition = hit.point;

    return groundCast;
}

void SphereCastGizmos()
{
    Vector3 origin = groundCheckOrigin.position - gravityDirection.normalized * Physics.defaultContactOffset;
    Vector3 destination = origin + (gravityDirection.normalized * maxGroundDistance);

    Gizmos.DrawSphere(destination, segmentRadius - Physics.defaultContactOffset);
}```

*the extra gizmos sphere's are just for clarity, only the first red sphere is where the SphereCast goes to*
vagrant blade
#

Well, if hacking is the only solution, don't use 0 timescale, use a very very very small number that is essentially zero.

unkempt meadow
#

I guess that should do it

#

like .001

vagrant blade
#

Even smaller

unkempt meadow
#

but you can't then necessarily pause the game and take a shit

latent latch
#

Mathf.Epsilon

unkempt meadow
#

if even smaller, then yea I guess

vagrant blade
#

That's why it's a hack. Technically someone can leave it running for hours. But that's the assumption you make: that nobody actually will.

odd arrow
#

that sucks now i've gotta rewrite so much 😭

#

my fault for assuming unity wasn't stuck using c# versions from the 1700s

latent latch
#

for spherecasting

somber nacelle
odd arrow
#

i mean yeah ig

somber nacelle
#

i personally can't wait to be able to use those with expressions instead of copying a struct just to change one of its properties and assigning it back. and generic math

reef garnet
odd arrow
#

UNITY IS ON C# 9????

#

HUHHHHH

#

that's not even file scoped namespaces oh my god

#

im gonna cry

somber nacelle
#

yup. it's old lmao

odd arrow
#

how do y'all put up with this

somber nacelle
#

at least you can target .net standard 2.1 in the latest versions of unity instead of still being stuck on .net framework

odd arrow
#

honestly idek how i didnt notice since i used unity for months in early 2023 working on a class project

#

oh it's so over

#

why is it internal 😭

late lion
odd arrow
#

oh lol

heady iris
#

I installed System.Runtime.CompilerServices.Unsafe.6.0.0 with NuGet for Unity because I needed to do some bad things to my data

#

i don't think i actually need that anymore..

late lion
#

Unity has UnsafeUtility which has some, but not all, of the same methods.

odd arrow
latent latch
#

unsafe unsafeutility really unsafe

odd arrow
#

why did i not try this beforehand ughhh

hard viper
#

unity is on C# 7 with support for SOME C#9 features

odd arrow
#

even worse

hard viper
#

i like it. change scares me, and John Riciotello protects me from it

glacial epoch
hard viper
#

when later C# mentioned “we have a way better garbage collector”, my first thought was “Oh no! But muh memory garbage!”

#

but then the Unity devs came to the rescue and said “Not today, foul fiend! We’re staying the same!”

#

and everybody clapped

odd arrow
#

yeah but

#

file scoped namespaces

#

and whatever this thing is that im in love with now

quartz folio
#

collection initializer

#

It's all coming, you will just have to deal with it for now

glacial epoch
#

unity chooses to keep you in the past as you'll be too powerful otherwise

late lion
hard viper
#

typical unity dev

hard viper
#

comes in to work wearing mammoth furs and animal bones under a labcoat

#

||my wife was right that no one would get the reference||

reef garnet
#

I need help with SphereCasts, I'm using one to detect the ground and the reason I'm using SphereCasts is because I want to get the nearest point of contact with the ground but I'm running into this weird issue I can't explain where the isGrounded bool flags false when you're near the edge of the mesh as shown in the video

Here is my code:

private void FixedUpdate() 
{
    isGrounded = IsGrounded();
}

public bool IsGrounded()
{
    // Check point of contact with last collider in array
    
    if (useSphereCast)
    {
        return SphereCastGround();
    }

    return OverlapSphereGround();
}

bool SphereCastGround()
{
    Vector3 origin = groundCheckOrigin.position - gravityDirection.normalized * Physics.defaultContactOffset;


    bool groundCast = Physics.SphereCast(origin, segmentRadius - Physics.defaultContactOffset, origin + gravityDirection.normalized, out RaycastHit hit, maxGroundDistance, groundLayers);
    groundPosition = hit.point;

    return groundCast;
}

void SphereCastGizmos()
{
    Vector3 origin = groundCheckOrigin.position - gravityDirection.normalized * Physics.defaultContactOffset;
    Vector3 destination = origin + (gravityDirection.normalized * maxGroundDistance);

    Gizmos.DrawSphere(destination, segmentRadius - Physics.defaultContactOffset);
}```

*the extra gizmos sphere's are just for clarity, only the first red sphere is where the SphereCast goes to*
quartz folio
#

origin + gravityDirection.normalized is not a reasonable direction to pass

#

You should be using gravityDirection.normalized

odd arrow
#

why does unity actually care ab this stuff

#

like lemme launch my game bro

rigid island
#

show full stack

odd arrow
#

it's fine i just fixed it

#

destroyed this library for unity anyways what's a little more

rigid island
cosmic rain
#

Not to mention that decompiling games isn't really a legal topic here.

odd arrow
#

ah that's my bad

#

sorry y'all

eager creek
#

hey i am using the Quick outline too from the asset store,
it is giving me 2 different results i gamemode view and build
any 1 know why this is happening

latent latch
#

better to ask on the asset store page

neat shard
#

in my webgl slots game, am I benefiting a lot in terms of performance on mobile browsers by avoiding using the Update method? I have most of the game done using events and coroutines

latent latch
#

it depends what you're doing inside of those updates, also coroutines are effectively using update

#

events can help if you are doing a lot of polling but it's such a micro performance unless you've a lot happening

neat shard
#

ah okay, it just some of the things that I had found myself adding to the update method, even though probably trivial, seemed really unnecessary to check every frame given the game is basically "on pause" unless the user clicks the "spin" button

#

of course i'll probably have to use update method sooner or later when i add some small background animations i'm planning on 🙂 . thanks for confirming it wont hurt

latent latch
#

if anything just return early via flag

public Update()
{
  if(paused)
  {
    return;
  }
}```
eager creek
round violet
#

when using Transform.TransformPoint, how does Unity convert the vector3 from local to world ?
from "what" does it take references ?

somber nacelle
#

from "what" does it take references
what do you mean by this? because you call the method on an instance of a transform which naturally has information about its local space

round violet
#

well its perfect

somber nacelle
#

the method is not static so it must be called on an instance

spring creek
round violet
#

can i do a "double" break ?

#

to get out of the 2 switch

somber nacelle
#

ew why are you nesting switch statements like that?

round violet
#

because i have to

#

well ofc there is always another way, but its working great until now and i dont want to remake the part of my system

somber nacelle
#

at the very least extract that inner switch statement into another method

round violet
#

what does this change ?

somber nacelle
#

then your inner switch can do its thing and you just break in the if statement

#

it will also make it significantly better to read the code

west lotus
#

Nested switch statements is a huge code smell

lean sail
round violet
somber nacelle
#

how different is the code inside of the other case that these need to be such huge blocks for each switch case?

round violet
#

No reusability

fervent furnace
#

I sometimes nest switch for performance
You need goto

west lotus
#

For performance ?

latent latch
#

i use goto when I cant bother to fix my logic

#

this is why assembly is the best language

round violet
#

For now i dont need goto

#

But i'll keep this in mind

#

For the machine, whats the difference between nested switchs, and replacing the nested switch by a function with the switch inside ?

#

Im on phone so i can't illustrate my example sorry

fervent furnace
#

If you need to reuse the nested switch then better to put it in other function
I usually just put it inline unless it is too many lines

#

To prevent function call

round violet
#

Well the one in screenshot isnt reused

twilit scaffold
#

woohoo! I wrote my first working Event (in Unity). "It's not much, but it's honest work"

somber nacelle
# round violet Well the one in screenshot isnt reused

it would still benefit from being extracted into another method, purely from a readability standpoint. don't make your code unwieldy and impossible to read in the effort to maximize efficiency for a 0.0001% gain in performance

round violet
#

Its my way of writing code

#

Nw i can read, if i can't anymore, i split it

raven basalt
#

I have a script called SpawnManager.cs which spawns enemies. I have a gameObject with the SpawnManager.cs attached, and when I disable the script duirng runtime (with .enabled=true) while keeping the gameObject (that the script is attached to) active, the gameObject continues to spawn enemies. However, I need to keep the gameObject active, but I want the script to stop spawning enemies. How do I do this?

mellow sigil
#

Make a variable that determines if it should do the spawning or not

knotty sun
#

hmm, .enabled=true does not disable the script

dense swan
#

Hello, what is the purpose of VideoPlayer.waitForFirstFrame? What sort of issue it's trying to avoid?

mellow sigil
#

Did you read its documentation?

worldly swift
#

Hi all, has anyone managed to create an Event bus / EventManager pattern with the new Awaitable methods?

dense swan
#

ah I see. I wonder if it's useful if I didn't use playOnAwake or is it only useful if I use playOnAwake

sonic stirrup
#

Hello everyone, I have a question that I have not found an answer to. my game will be a multiplatform. based on the type of device it will run on I would like to change authentication. I can’t find any method in the system-info that reports what type of device is running my game. the operating system is not enough because different devices could have the same OS. can any of you suggest a way out for me? My has two mater device PC and Oculus

somber nacelle
strange patio
#

so i create a third person character using a character controller, but it wont going down, it can goes up to mountain but cannot go down. i add rigidbody but my movement becoming so weird

somber nacelle
#

CharacterController and rigidbody do not mix. but you also need to show !code

tawny elkBOT
strange patio
#

how to post a code?

somber nacelle
#

you can manually apply gravity to your charactercontroller

somber nacelle
#

there are plenty of examples of how to apply gravity manually if you need a tutorial. you can check out any FPS movement tutorial that uses a charactercontroller to see an example of how to do it

unreal sonnet
#

Does anyone know a consise way to convert 1-9 numpads into ints?

unreal sonnet
#

For reference, i want to choose an inventory slot by pressing one of the numpads

knotty sun
unreal sonnet
#

For me that just returned 256

knotty sun
#

yes, that is an int

unreal sonnet
#

What i meant was that i want to press numpad 5 and that would return int 5

somber nacelle
#

you can then subtract (int)KeyCode.Keypad0 from the int to get the number on they keyboard key

knotty sun
#

well, you should have said

quartz folio
#

then subtract the right amount to get what you want

unreal sonnet
#

Oh i see, thanks

hardy tendon
#

Good morning, I'm doing a project where I have to get on a vehicle, once I get on I update the transform position, and the transform rotation with the seat transform, but this makes the camera shake when I move the vehicle left and right, thanks in advance

#

Does anyone have any idea how I can prevent this from happening?

leaden ice
clear rover
#

Hey I'm having some issues with the (new) input system, I'm following a Brackeys tutorial to get stuff to work but it doesn't seem to be detecting my inputs, here's my code:

#

Then jump simply outputs console text to verify whether it works or not

somber nacelle
#

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

clear rover
#

Yeah the script is attached to my player object

#

But it wouldn't let me drag the input manager object into the InputMaster object

somber nacelle
#

and have you saved the input action asset so it generates the c# class

clear rover
#

so I had to instantitate it from the awake function

#

Yeah it's made a C# class

hardy tendon
somber nacelle
# clear rover

you have saved it after assigning a binding to the jump action, right?

clear rover
#

So I assume so

somber nacelle
#

then congratulations, it works

clear rover
#

It's not outputting anything to the console though

somber nacelle
#

then you've missed one of the steps i have outlined

clear rover
#

I haven't though

#

I've showed a screenshot of each of the steps being done

somber nacelle
#

screenshot the inspector for the object with the component that instantiates your InputMaster class

clear rover
#

Is Debug.Log still the right way to get stuff in the console

somber nacelle
#

yes. otherwise i would have pointed out an issue there

clear rover
#

I'm not sure what the connection here to the active object in the scene was

#

looks like that's probably the issue

#

If this is the master object

#

What component do I attach

clear rover
#

Wait no it is added then

#

"Script PlayerMovement"

#

It should be working then

somber nacelle
#

then start play mode, open the console and try jumping. if it still does not work take a screenshot of the entire unity editor with the console window visible and that inspector visible

somber nacelle
# clear rover

also make sure you unfold the binding here and check that you have bound the correct key(s) to it

clear rover
#

Still nothing!

clear rover
#

Hammering space and nothing is happening

somber nacelle
#

can you post the full class in a bin site

#

for the PlayerMovement component, that is

clear rover
#

Yeah sure, I'll just paste it here since it's really not that long

#

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

public class PlayerMovement : MonoBehaviour
{
    // Reference to the CharacterController GameObject
    public CharacterController controller;
    public InputMaster controls;

    public float speed = 6f;

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

    void Awake()
    {
        ConfigureInputManager();
    }

    /// <summary>
    /// Method assigns delegates for each action mapping in the InputManager system to a specific method that they are supposed to invoke.
    /// </summary>
    private void ConfigureInputManager()
    {
        controls = new InputMaster();
        controls.Player.Jump.performed += _ => Jump();
    }
    private void OnEnable()
    {
        controls.Enable();
    }

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

    /// <summary>
    /// Method handles the logic associated with allowing the player to jump
    /// </summary>
    private void Jump()
    {
        Debug.Log("Jumping now!");
    }

    private void Move(Vector2 direction)
    {
        Debug.Log("Ping" + direction);
    }
}
somber nacelle
#

sprinkle some more logs around and verify that code is actually running. if you have verified it and you have confirmed you are pressing the correct key at runtime then try restarting the editor because there is nothing here that would indicate it shouldn't work

clear rover
#

thanks for your help

leaden ice
clear rover
#

This might be some clue to the problem

somber nacelle
#

yeah you have to actually enable the input system. that should have popped up when you initially installed the package

clear rover
#

I'll see if that rectifies it now it's restarted again - I did check with a debug.log in Awake() and it called immediately

#

Yep it's working!

sharp lantern
#

!code

tawny elkBOT
sharp lantern
#

On the main Thread i have a coroutine that updates the Dictionary<>

cosmic rain
sharp lantern
#

Ok so what can i do?

#

A simple way would be to not add if the Task in running

cosmic rain
#

Nevermind I didn't read properly. Let me have a look again in a min.

#

What line is the error thrown at?

sharp lantern
#

On the foreach

#

i think the problem is that i'm updating the dict while i'm looping through it

cosmic rain
#

I don't see you adding to chunks in it. Unless nearChunks references the same dict.

#

Does it?

sharp lantern
cosmic rain
#

Hmm... Perhaps it is related then. Did you try the concurrent dict yet?

chilly surge
sharp lantern
sharp lantern
chilly surge
#

You don't need to.

#

You are wrapping a task into like, 3 tasks.

sharp lantern
#

When i Run a task how do i know when it has finished to get the results?

#

This is What i still dont understand

proud valley
#

i got a problem with my PlayerInteract script in unity, i dont know if this is the place to ask for help but i dont know where elso to ask, the error message is: Assets\Scripts\PlayerInteract.cs(29,73): error CS1061: 'Interactable' does not contain a definition for 'promptMessage' and no accessible extension method 'promptMessage' accepting a first argument of type 'Interactable' could be found (are you missing a using directive or an assembly reference?)
And the Script is here:

somber nacelle
tawny elkBOT
cosmic rain
chilly surge
#
async Task<int> DoStuff()
{
    var tcs = new TaskCompletionSource<int>();

    await Task.Run(() =>
    {
        tcs.SetResult(42);
    });

    return await tcs.Task;
}

Can be simply rewritten into:

Task<int> DoStuff()
{
    return Task.Run(() =>
    {
        return 42;
    });
}
cosmic rain
#

Or you can set a field taskDone or something and check that.

proud valley
somber nacelle
#

you missed something. but you need to get your ide configured if you want to get help here

proud valley
#

what do you mean by that?

somber nacelle
proud valley
#

the external script editor is now set to "Visual Studio Code"

somber nacelle
#

do you see red underlines in your code now?

proud valley
#

no

somber nacelle
#

then you did not complete all of the steps

sharp lantern
proud valley
#

how do i find the Common7IDE ?

somber nacelle
#

well that's just the wrong set of steps entirely

#

follow the instructions for VS Code which is what you were using

chilly surge
# sharp lantern Thanks it works and the code is more clear ❤️

If you want to understand why, starting from your original code:

async Task<int> DoStuff()
{
    var tcs = new TaskCompletionSource<int>();

    await Task.Run(() =>
    {
        tcs.SetResult(42);
    });

    return await tcs.Task;
}

Notice that because you are awaiting Task.Run(...), by the time that task is done, the result of tsc must have already been set, so awaiting tsc.Task is redundant. So you can instead rewrite it into:

async Task<int> DoStuff()
{
    var result = 0;

    await Task.Run(() =>
    {
        result = 42;
    });

    return result;
}

But notice that Task.Run has an overload that takes Func<T> and returns Task<T>, so you can further rewrite that:

async Task<int> DoStuff()
{
    return await Task.Run(() =>
    {
        return 42;
    });
}

And lastly, a pair of async/await is redundant, so you can remove that, and arriving at the final version of:

Task<int> DoStuff()
{
    return Task.Run(() =>
    {
        return 42;
    });
}

Your original code also has issues with exception handling which will hang the task, but yeah simply use the final version.

#

(A pair of async/await is technically not redundant and removing it will affect stacktrace, but in this case it shouldn't be an issue but you can also keep them)

sharp lantern
#

thank you very much

dawn nebula
#

Have you guys ever needed an object to know some position, but sometimes that position could just be a static Vector3, and other times it could be the transform of a gameobject?

#

Would you create some kind of interface that just returns a vector3, and the implementation can handle the source?
Something like

public interface IPositionGetter
{
    public Vector3 GetPosition();
}

public class TransformPosition : IPositionGetter
{
    public Transform transform;

    public Vector3 GetPosition() => transform.position;
}

public class Vector3Position : IPositionGetter
{
    public Vector3 position;

    public Vector3 GetPosition() => position;
}
#

Or is this just silly, and I should just make sure whatever position I want to track has an associated gameobject?

knotty sun
#

so you can do

Vector3 v3 = ((IPositionGetter)someClass).GetPosition();

yes, makes perfect sense

quartz folio
#

That's a whole programming pattern: wrapper/adapter

knotty sun
#

the beauty of interfaces, the receiver is not bound to the source implementation only the results of it

fluid siren
#

anyone got a good script for animal walking ?

dawn nebula
knotty sun
#

the pattern is valid, only you can decide if it is worth implementing it in your use case

chilly surge
#

Instead of a method of GetPosition(), you can also make it just a property with getter, that will simplify Vector3Position or any implementation that stores the position directly.

#

It's also the reason why the convention is "public properties, private fields" because interfaces can contain properties but not fields, so if you need to refactor by adding/removing interface, you don't need to change your implementation.

#

But in Unity that convention is, kind of being ignored.

dawn nebula
#

Personally I'm not a fan of interfaces with properties.

#

But meh.

chilly surge
#

Interface cannot have fields.

dawn nebula
#

Sorry mistyped.

knotty sun
#

it's a shortcut, technically there is no difference

chilly surge
#

Yeah properties is just "a field + getter/setter generated for you by compiler"

dawn nebula
#

I know, but visually it bothers me.

#

Odd brain tick.

knotty sun
#

I know how you feel, unless used correctly properties are overrated imo

dawn nebula
chilly surge
#

It can.

latent latch
#

you can serialize backing fields

#

but dont

knotty sun
#

real hate how Unity uses properties for structs

dawn nebula
chilly surge
latent latch
#

well, then targeting the backign field with attributes is going to be a hassle

chilly surge
#

It's just [field: SerializeField] though, one extra word.

dawn nebula
latent latch
#

yes, but stuff like [FormerlySerializedAs] and other attributes require directly targeting the backing field

chilly surge
#

Sure, but I feel like that's more of a tradeoff than a simple don't.

knotty sun
#

that might be a concern in App dev, it should not be in Game dev

latent latch
#

Well, that's just a basic example, but if you were going to use one of the many editor supporting attributes

knotty sun
#

then dont use auto backing fields

latent latch
#

I know they make the scripts look cleaner, but you may end up even with more lines of code if you want to integrate any of it

chilly surge
knotty sun
chilly surge
#

Partly they also had to support UnityScript and Boo at the time.

dawn nebula
#

fucking

#

Boo

knotty sun
#

I remember

dawn nebula
knotty sun
#

no it bloody well wasn't

humble pumice
#

Heyhey.
This is how play audio when the curser hovers over a uibutton. If you exit and enter the button really fast, the hole sound becomes more quiet. (The background music too, etc).
I don't know much about sound in unity. What is happening and how do I prevent that?

Code: public void CarryOneShotAudioSource(AudioClip audioClip, float volume) { oneShotAudioSource.PlayOneShot(audioClip, volume); }

maiden lake
hexed pecan
#

You can use an empty container object/parent that you rotate

dreamy matrix
#

Hello,
I have some problems with unity old Input system (for some reasons for now i can't changed it even if I want...).
I have game where controls is with KeyCode.RightAlt, LeftAlt, RightControl, LeftControl
But for some reasons Unity is using RightAlt as LeftControl (Altgr)
Is there a way to prevent it?

leaden ice
dreamy matrix
#

Sadly not. It's not only on my keyboard. Tested by few people.
Related posts i found was:
https://discussions.unity.com/t/why-does-input-getkey-keycode-leftcontrol-returns-true-when-i-press-right-alt/172454

leaden ice
#

And have you seen if the new input system has a similar issue?

dreamy matrix
#

No, like i said, for now i can't use new input system.
I haven't submitted any bug report (i don't think they will resolve it any way, they are working on new input system) yet,
for now i was looking for some information, maybe somebody has similar problem, or information if this is intended behavior.

leaden ice
#

Looks like you found some people with the same problem

#

My recommendation is to submit the bug report, they absolutely still support the old system, and see if the new system can bail you out in the meantime

dreamy matrix
#

Ok, i'll do this. Thank you very much for talk!

steel vortex
#

Hey guys, I have a problem with my game and I'm trying to do the tutorial (https://youtu.be/KqpMOdPj3co?si=mzAWb3PSkehjclJP&t=1376) and from the movement part I have a problem and I use a Unity asset (https://assetstore.unity.com/packages/templates/systems/low-poly-shooter-pack-v4-3-54947) and now I have to somehow recode it so that it becomes exactly as networking as in the video I worked on it for 1 week so 5 days xD and can't do it and I'm so desperate I even tried with ChatGPT but never got anything working out now I want to ask if someone who knows it very well would do it for me would be very happy and very supportive, you can also write me a DM

In this tutorial series I'll show you how to create an online multiplayer first person shooter with Unity and Photon Fusion from scratch. Download complete Unity project 👇
https://www.patreon.com/posts/multiplayer-fps-65725126

📍 Support us on Patreon and help us make more videos like this one ⏩ https://www.patreon.com/prettyflygames

In this ...

▶ Play video

Use Low Poly Shooter Pack v4.3 from Infima Games to elevate your next project. Find this & more Systems and templates on the Unity Asset Store.

heady iris
#

there's no actionable question here

round violet
#

the assembly def takes all files in folder and all files in subfolders (except if those subfolders have their own assembly def) correct ?

round violet
#

weird

#

i have the following:

somefolder /
- main.cs
- assembly definition file
- somesubfolder /
-- otherscript.cs

inside main.cs I can't get the class of otherscript.cs

#

mb i updated

leaden ice
#

and what error you're getting

#

Also is the error only in your IDE or is it also in Unity

round violet
#

maybe its VS ?

leaden ice
#

Yeah Misc files means your VS is not configured

#

That should say the name of the assembly

round violet
#

rebooting VS fixed

#

i wonder why

leaden ice
#

Alternatively regenerate project files in Unity might have helped too

round violet
#

yes

#

well mb i should reload VS before asking here

#

ty for helping

static matrix
#

fibwizzle
I need to make 2d platformer pathfinding
this may be a challenge

#

the left and the right shouldn't bee too hard, but verticality is where the challenge emerges

#

I might just have "jump points" which dictates where creatures can jump and each creature has different types of points they can use

#

actually, I could probably do this without that provided I don't use floating platforms

#

or at least minimize the amount

hard viper
#

you can’t have a platformer without platforms

#

you can, but that is core to the genre for a reason

static matrix
#

nuh uh
actually I can make floating platforms work I just need a trigger below the platform that has the same flags

hard viper
#

can you represent everything with a grid?

static matrix
#

its already on a grid
tilemap
its cool ive figured out how to do it tho, I got this

hard viper
#

good luck

#

btw, if it’s pathfinding, I would recommend having a representation of the level as a grid, as a directed graph

hoary swift
#

anyone knows how to copy a sprite properly in a editor script? since it is made out of 2 assets (main sprite asset and texture2d), just copying the sprite asset keeps the reference to the original texture asset which I also want to copy. also, it turns into a .asset file while the original one has import settings in the meta file

hard viper
#

what do you mean by copy?

#

you want a deep copy, as in a second new sprite asset in a separate file?

hoary swift
#

I used that method, but as I said it just creates a .asset file

leaden ice
#

What's wrong with that?

#

I guess I'm curious why you want/need to copy the original image too

hard viper
#

i would expect the copy of a .asset file to be a .asset file

ashen yoke
hard viper
#

sounds like the machine is doing what you asked it

ashen yoke
#

the "sprite" is simply a rect of the area of the texture

#

it is generated automatically by the importer

hoary swift
#

This is what is inside the .png.meta file

fileFormatVersion: 2
guid: 9b1f67d458d836e4f9528346efccfa50
TextureImporter:
  internalIDToNameTable: []
  externalObjects: {}
  serializedVersion: 11
  mipmaps:
    mipMapMode: 0
    enableMipMap: 1
    sRGBTexture: 1
    linearTexture: 0
    fadeOut: 0
    borderMipMap: 0

I want to copy it as a single file

hard viper
#

well, sprites are sliced from textures

hoary swift
ashen yoke
#

if you want the texture to automatically import as a sprite you can write your own import post processor and flag the texture for reimport as a sprite

#

its not, by default an imported image generates a texture object and a subasset sprite

hard viper
#

i think he might be wanting to make a duplicate texture, and also have a duplicate of the sprite asset targetting the new duplicate texture

#

correct me if i’m wrong

#

but a lot of this is confusing tbh

hoary swift
#

that is what I would do if I have no other choices, but if possible I want to use the texture importer

hard viper
#

well, what is it that you DO want to do

ashen yoke
#

what should your editor script do?

hard viper
#

lets say I have a texture, and a sprite is sliced on it

hoary swift
hard viper
#

uh, why do you want a sprite in a separate single PNG file?

hoary swift
ashen yoke
#

thumbnail as area of the level rendered into an image?

hard viper
#

yeah, that is standard

ashen yoke
#

are we talking unity editor or custom runtime editor?

hoary swift
#

each level has a data folder in the assets folder

#

editor

hard viper
#

i wonder if you need a screenshot tbh

static matrix
#

hmm
CanJump = Physics2D.Raycast(transform.position, GetLookDirect(), 0.0001f, 3);
this seems to always be returning true even when no objects with that layer are anywhere nearby

ashen yoke
#

users use unity editor as an sdk?

hard viper
#

a screenshot might be easier tbh

hoary swift
#

yeah, by using addressables to export levels

static matrix
#

any idea why it is doing that?

ashen yoke
#

ok i wont dig into it myself, what i would do is i would first - check if its possible to grab the sprite sub asset, modify it and see if the asset picks up the changes as is

hoary swift
#

nevermind other people need more help

ashen yoke
#

second i would write a custom post processor that would be told that this next import should be a sprite type

hoary swift
#

it would be better if I just copy both assets

ashen yoke
#

and upon importing the duplicated image it would switch it to sprite

static matrix
#

oh
why tf did it let me assign it to a bool then?????????

hard viper
#

probably casted the int to a bool?

ashen yoke
#

lastly in the same post processor it would just copy the values from reference sprite to the newly created

static matrix
ashen yoke
#

probably with EditorApplication.delayCall after import is complete

hard viper
#

also, you should never ever use physics queries without a proper ContactFilter2D

hoary swift
#

I may try that, thanks

hard viper
#

you can also specify layers, but the query takes longer the more objects of that layer are roughly in the zone of the query

#

so if you don’t specify layers, shit gets really expensive

static matrix
#

yeah i'm just doing layers

#

which will work for me, I don't need to optimize too hard rn

hard viper
#

you did not specify layers

#

you let it be default

static matrix
#

no, I specified layer 3 which is my ground layer

hard viper
#

really?

#

because the layer mask 3 sounds a whole lot like 0000011

static matrix
#

yes
I think so?

hard viper
#

and 00000011 sounds like TWO layers, which have default values

#

layer mask and layer are two different things

static matrix
#

oh huh
ok

hard viper
#

layer 5 would be layer mask 2^5 or something

#

it’s offset by one. i don’t remember exactly right now

static matrix
#

i'll just use a set one then

hard viper
#

but I use the ThunderNerd Layers and Tags plugin so I just have a class with consts defined for layers and layer masks etc

#

then you can call Layers.GROUND_MASK or something like that

#

and it gives you the layer mask for that layer

west lotus
#

Layer 5 would be int mask = 1 << 5

hard viper
#

right, cause 000001 is mask for layer 0

#

point being, since both are easily cast with ints, it’s very easy to forget that you can have a layer vs layer mask

#

layer mask 3 = 0bx0011 means search for layers 0 and 1

west lotus
#

The codegen approach you linked is neat I like it

hard viper
#

thanks. it’s extremely handy

#

I made my own static (non generated) class to accompany it, btw

#

StdContactFilter. It has several public static readonly ContactFilter2D which consolidate specific queries that span multiple layers

west lotus
#

How do you use multiple layers with it ?

#

You still need to | them manually

#

Or feed them one by one into a utility method

hard viper
#

eg public static readonly ContactFilter2D floorToPlayer = new ContactFilter2D() {
layers = Layers.GROUND_MASK + Layers.SOLID_TO_PLAYER_MASK + Layers.SOLID_ENTITY_MASK,
useLayerMask = true,
useTriggers = false
}

#

you also have auto generated layers, like Layers.GROUND would be the (non mask) layer of ground

#

so it gives you the mask or ID representation

#

i forget the exact syntax, but it’s something like that

#

so whenever I add new layers, I can just modify my static class

#

my code references the StdContactFilters, and not the Layers class, usually. To keep it centralized

lavish frigate
#

hey guys. i am trying to make a simple enemy platformer AI. So it basically moves left to right and flips if colission or fall off. However this moving between two points can be reused for flying hazards or such. Any tutorials/advice on how to approach this to make my code reusable in the future?

ashen yoke
#

work from there understanding which dependencies it has, and how to minimize them, minimum dependencies, encapsulation, component being agnostic of its use

lavish frigate
#

Sounds fair

#

would using these "AI" movement classes only to calculate next desired position work? and then just let these hazards or enemies generate an AI for themselves

ashen yoke
#

let these hazards or enemies generate an AI for themselves

lavish frigate
#

create a new non monobehaviour class from within themselves

#

give it parameters such as leftmost bound, rightmost bound and speed

#

and then use that to calculate movement

#

basically i want reusable movement in multiple hazards/enemies

ornate harness
#

Hello, my AI character walks backwards, how can I fix that?

leaden ice
#

Well that's going to depend on the details of how your AI character works and is set up

ashen yoke
# lavish frigate create a new non monobehaviour class from within themselves

its a common thing to do with waypoint systems and the like, but its better not to avoid using components as waypoints for it, makes it easier to work with, however if you really need it you can write a custom inspector with transform handles that allow you to move your waypoints (which are just vector3 serialized in the mono) with a transform gizmo

#

for an example of that you can look at LightProbeGroup built in component

#

or BoxCollider for modifying extents of bounds

#

all those manipulators are done through Handles editor class

ornate harness
leaden ice
ashen yoke
#

problem is that you will have to handle absolute/local coordinates, so if you serialized in local and moved the AI the points would move with it, can be desireable in some cases, may not be in other, a toggle that converts those would do tbh

#

similar toggle is in LineRenderer i think

lavish frigate
#

and how would you advise handling colissions? would these enemies have a rigidbody, or should i give them an interface that the player checks on collissions?

ashen yoke
#

i cant give you a definitive advice on that, any method has pros and cons and its up to you which you prefer, any of them will work

ornate harness
leaden ice
#

I think you have to re-export it with the correct settings

ashen yoke
ornate harness
leaden ice
#

make sure the blue arrow matches with the "forward" direction of the model

#

(when in local rotation mode)

ornate harness
#

I Will check that

#

You are right, it do not manches. The problem is that if I rotate it the animation works backwards.

leaden ice
ornate harness
#

You were right! I have solved it. Thank you very much! 🙂

rigid island
pine carbon
#

oh ok

ornate harness
#

Hello, how can I make a code to detect the closet enemy?

muted lake
#

Hello im kind of new to game programming. i had an idea that im working on more of a challenge and working out an idea that a full game. basically im having an issue with creating a dictionary of assets that are beeing instanciated through a manager script. the issue is each instance game object has a player stat, and I need this to have permanance through scene change. and the game objects are retained when switching back to the scene. im a bit lost with this one.

#

ive tried json serialization and dont destroy on load and not real luck

knotty sun
muted lake
knotty sun
#

yes, but that is required behaviour if you want permanance

muted lake
#

so dont go down the rabbit hole of serialize and deserializing the data?

knotty sun
#

you can but it's unnecessary in this case.
another option is to maintain a set of POCO's in a singleton with DDOL

muted lake
#

what is POCO?

knotty sun
#

Plain Old C# Class

muted lake
#

ah okay

#

should I set up scriptable object or is that not needed either?

knotty sun
#

not needed

muted lake
#

so how do I set up the object to be unloaded on scene change and then loaded back in? not sure if you have a good doument link on this.

#

ive been looking for a bit.

knotty sun
#

lets make a thread and I'll explain

lavish frigate
#

hey all, so i just tried converting to URP. IT worked kind of as expected? except for the fact that my textures did not turn dark, and lighting is not needed to see anything after this conversion. Any tips? i want to add lights to my 2d game

#

I used window -> rendering -> convert built in to URP

#

unity editor 2021.3

thorn silo
#

Hi!
I have like 30 draw calls that draw characters on my scene. The textures are separate files for every part of the outfit. Looking for a way to reduce these draw calls, would having all textures on Sprite Atlas reduce draw calls to like 2?

gentle bison
#

I am using the virtual camera of Cinemachine, but sometimes the camera changes the Position to some weird place and because of the CinemachineBrain I am not able to change this. Simply turning the CinemachineBrain off and on again doesn't work.

steady moat
#

However, you must also have a single skinned mesh renderer if they are skinned.

#

So, yeah, in your case I believe it is not possible to batch them without recreating the mesh data at runtime.

thorn silo
#

hm, all outfit parts are separate

steady moat
#

The alternative, would be to use solution made for that but they are not well supported.

thorn silo
#

okay thanks, I will check that 😄

steady moat
#

Do not lose too much time on that

main coral
#
    public void ChangeLanguage(string localeName)
    {
        var targetLocale = LocalizationSettings.AvailableLocales.Locales.Find(x => x.LocaleName == localeName);

        if (targetLocale != null)
        {
            LocalizationSettings.SelectedLocale = targetLocale;
        }
    }```

Why does this not work for changing language with the Localization package ?
knotty sun
#

at a guess localeName does not match any known LocaleName's. you could try doing some debugging

main coral
#

yes but what is the common code to change language ?

pale marsh
#

Hello!, could someone help me with Firebase Functions? I'm trying to implement Push Notifications in my app, but for some reason, I'm not receiving any messages.

This is the code I use in Unity to receive the messages:
[Link to Unity Code: https://gdl.space/quvefeyula.cs]

This is the code for my Firebase Functions:
[Link to Firebase Functions Code: https://gdl.space/nilapuzogi.coffeescript]

thick cipher
#

Hello everyone, I'm facing a problem and I don't know how to solve it.
I implemented an inventory system in my game. Every time I press a button, I can use the item equipped from the inventory. You can see the workflow right there.

public void OnItemUse(InputAction.CallbackContext context)
{
    if (!context.performed)
        return;

    _currentItemSelected = Instantiate(_currentInventoryItem.ItemPrefab, _itemUsePosition.position, Quaternion.identity, transform).GetComponent<ItemBase>();
    if (_currentItemSelected.GetType().IsSubclassOf(typeof(ThrowableItem)))
    {
        ThrowableItem throwableItem = (ThrowableItem)_currentItemSelected;
        throwableItem.SetFirePoint(_itemUsePosition);
        _inputController.SetupOnItemUseActions(throwableItem.BeforeThrow, throwableItem.Throw);
    }
    else
    {
        _inputController.SetupOnItemUseActions(_currentItemSelected.Use);
    }
    _inventory.Remove(_currentInventoryItem);
}

//
//For context
//
public void SetupOnItemUseActions(Action onPerformed, Action onCanceled = null)
{
    _input.Gameplay.UseItem.performed += ctx => onPerformed();
    _input.Gameplay.UseItem.canceled += ctx => onCanceled();
    _input.Gameplay.UseItem.canceled += ctx => ResetOnItemUseActions(onPerformed, onCanceled);
}

private void ResetOnItemUseActions(Action onPerformed, Action onCanceled = null)
{
    _input.Gameplay.UseItem.performed -= ctx => onPerformed();
    if (onCanceled != null)
        _input.Gameplay.UseItem.canceled -= ctx => onCanceled();
}

The problem is that, when I'm trying to use a throwable item, and I want to throw 2+ items in succession, all the items execute the BeforeThrow and Throw functions.

Here is a recording, demonstrating the problem https://youtu.be/YngQUFxsvtU

mental rover
#

ctx => onPerformed(); you'll need to actually define these delegates so you can remove them later

thick cipher
thick cipher
mental rover
#

e.g

Action myDelegate = ctx => onPerformed();
_input.Gameplay.UseItem.performed += myDelegate; // now myDelegate is subscribed
_input.Gameplay.UseItem.performed -= myDelegate; // now myDelegate is unsubscribed
#

alternatively, actually write your own method for it, e.g (I forgot the exact type ctx is)

void PerformedHandler(InputContext ctx) {
    onPerformed();
}

..
_input.Gameplay.UseItem.performed += PerformedHandler;
..

or even better, change the signature on onPerformed and skip the middleman here

loud wolf
#

Help plz
I'm facing a challenge in my project using Quest 2 and Hand Tracking 2, where manipulated objects pass through others instead of interacting. When trying to move an object towards another, it doesn't stop but goes through. I use Unity and seek guidance to configure realistic collision detection between objects. I appreciate any assistance from the community to enhance this experience.

Best regards,

thick cipher
mental rover
#

yes - the why being that the compiler will generate different internal methods for each anonymous delegate, so you're not actually unsubscribing with the same one

thick cipher
lone turret
#

Hi all, does anyone have recommendations for a Redis client to use in Unity? I've tried adding NRedisStack https://github.com/redis/NRedisStack to my project but the csproj file doesn't allow adding packages via Command Line. Does anyone know of a solution or recommendation for this?

GitHub

Redis Stack .Net client. Contribute to redis/NRedisStack development by creating an account on GitHub.

raven basalt
#

I'm trying to have the purple explosion VFX effects play once the enemy dies. The VFX effect consists of a light appearing briefly and then purple particles coming out. However, when the enemie dies, a shortened version of the VFX effect plays instead, where a light appears briefly, but no purple particles come out. I used manaDeathParticles.Play(); to make the VFX play

raven basalt
lofty crest
rigid island
somber nacelle
lofty crest
orchid gust
#

how could I spawn a prefab using the child of the prefabs position

lofty crest
orchid gust
# orchid gust

I am looking to spawn the prefab using one of the two red squares as its spawn point

#

normal though it just spawns with the middle of the whole thing as the center

somber nacelle
orchid gust
#

I see you can assign a parent but i dont see the part where you can specifiy the prefabs "pivot" point

somber nacelle
#

instantiate has nothing to do with an object's pivot point. you can specify the position it spawns at though

orchid gust
#

would the prefab not spawn at the center of the position I specifiy

somber nacelle
#

why don't you try it and see

#

because it definitely seems like you are confusing an object's position with its pivot point

orchid gust
#

Im trying to spawn several different prefabs using the red squares to be like cells

#

both spawn with an origin of 0,0

somber nacelle
#

if you don't want it to spawn at 0,0 then tell it what position you do want it to spawn at. that's what i've been trying to get through to you

orchid gust
#

Yes I want them to spawn at 0,0. But i am looking for a way to have the red point always be at 0,0 when spawned