#archived-code-general

1 messages ยท Page 336 of 1

rigid island
#

wdym by lags the audio?

austere solar
# rigid island wdym by lags the audio?

theres a slight stop before the loop is looped. That's what im tryna get rid of. I'll propably have to just make a new, better and longer song, and not switch and loop two 33 second clips.

rigid island
#

is the original even a perfect loop?

austere solar
#

I'm also trying Invoke

// Start is called before the first frame update
void Start()
{
    audioSource = GetComponent<AudioSource>();

    audioSource.loop = false;
    audioSource.clip = track1;
    audioSource.Play();

    Invoke("PlayLoop", track1.length);
}

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

private void PlayLoop()
{
    audioSource.Stop();
    audioSource.loop = true;
    audioSource.clip = track2;
    audioSource.Play();
}
#

nope, and it's even worse with Stop().

rigid island
austere solar
#

I first tried to make this in WPF lamooo i may be good at writing code but aweful at decidions.

rigid island
#

xaml nightmares

vivid halo
#

In general, I notice that Unity's built-in UnityEvent system seems to replace <Func> type in C# as UnityEvents are serializable and play nice with the inspector, while <Func> types seem to lack the same integration into the inspector but are supposed to behave similarly to UnityEvents.

Is this assessment correct?

latent latch
#

UnityEvents are slightly more performative than native c# events which is my take away from a lot of it

leaden ice
spring flame
#

Hey, I need to restructure a part of my project and move a bunch of scripts from Runtime to Editor assets and vice versa, is there any way to move those files without breaking references in the project and with moving to appropriate namespaces after the move?

vivid halo
leaden ice
spring flame
#

what about moving them and renaming/fixing namespaces in Rider though?

leaden ice
#

You run the risk of the meta files not coming along

#

Move in Unity, then do rename in Rider

unique trench
#

how can I get the world position of a UI element?

leaden ice
#

RectTransform.GetWorldCorners

unique trench
#

I tried that, it doesn't seem to match for some reason

First image is the UI element I'm trying to get
The 2nd is where the object is actually being positioned (blue dot)

latent latch
#

tmpro has its own bounding box including the rect

#

oh, I can't see that blue dot on my phone but im assuming it's the thing in the bottom left?

unique trench
#

@latent latch @leaden ice I actually got it, thanks!

I'm not sure why but it seems the value isn't update right at the start;
That is, in Start() I'm starting a coroutine, and the 1st thing I do is calculate that position and use it from here on now.

If on the other hand I keep calculating it again and again rather than use it from the start, it works.

And thanks ๐Ÿ˜„

woeful cargo
#

I have a question. So I set a button up with a certain variable in its onClick listener. How do I read what variable is attached to the listener?

heady iris
#

are you talking about the values you can fill in in the inspector? i don't think you can access those from code

edgy ether
#

Ok so... maybe im not thinking straight right now...
but... im pretty sure i didn't even do anything yet... why am i getting these errors!??

somber nacelle
#

you cannot begin a type name with a number

#

or any identifier for that matter

edgy ether
#

thank you very much

#

i was losing my mind

#

im laughing in sorrow upon realizing that was the issue for me freaking out for 10 minutes

#

imma get a drink..

willow sundial
#

why this dont work?

public void RemoveCharacter(Speaker character)
{
if(dataHolder.charactersOnScene.Contains(character.name))
{
Debug.Log("Se removio el jugador: " + character.name);
dataHolder.charactersOnScene.Remove(character.name);
}
}

#

the debug,log works

#

but the name isnt removed from the list

dusk apex
willow sundial
#

ok wait

#

WTFFF

#

EWHFERIOHDSKJSDHAUVHSDAFIVH

#

I DID THAT AND

#

NOW IT WORKS??

#

WITH THE DEBUG.LOG???? XDD

heady iris
#

that probably did nothing

willow sundial
#

bro wtf unity

#

but i was watching the debugger, and it didnt works and

#

i add the debug.log and now it works

willow sundial
heady iris
#

okay, now remove the log statement and test it again

willow sundial
#

okok

#

IT DIDNT WORK XD

#

with the logs it works XDD

#

and now it didnt work

#

with the logs

#

bro notlikethis

#

wait maybe yes

#

yes it works with the logs XD

#

idk men

hexed pecan
#

I bet something else is changing than just the logs you are adding/removing

willow sundial
#

nonono look

#

with the logs this happen

#

and it works

#

the error is because the list dont have any member to make the log

#

but the game works so i will try to remove the character with a for

#

the for didnt work

#

WITH THE LOG AFTER IT WORKS XD

#

but i have this error, but it dont affect to the game

dusk apex
#

For example: if you've got ten players, you'd have indices 0 to 9.

#

Accessing the tenth element would be at index 9. Index 10 would be the eleventh element and throw an out-of-range exception.

willow sundial
#

i found the error

#

ty bro your debug.log helped a lot โค๏ธ

pastel plover
#

Yo

#

Can somebody please provide me with the link to website to make code smaller

vivid halo
#

Big code vs small code?

#

Zooming out

#

Code obfuscators you mean?

#

var x=3.0f;var abc='abc';foreach(var a in b){};

#

Code compression?

rigid island
buoyant vault
#

remove spacing and change font size to something smaller, you're welcome UnityChanThumbsUp

fervent furnace
#

c# is a compiled language, so you finally have two "codebases" for your c# project (source and il)

turbid spade
#

should I just be creating a regular C# thread then?

novel bough
#

I need to implement a dynamic scroll view, when I scroll down and reach the end of the scroll view I want to populate more items inside the scroll view, and again when I scroll downward and reach the end of the scroll view more items are populated inside the scroll view. so how can I implement this?

lean sail
rigid island
sleek bough
#

ScrollView has vertical scroll bar which tracks scroll progress, you can use that value

novel bough
#

@lean sail Basically, I am fetching data from the server inside the scroll view and I make some logic using the scroll view verticle position when it reaches its end I call the function to load more data.if(!isPopulateDown && content.parent.parent.GetComponent<ScrollRect>().verticalNormalizedPosition < 0.1f) { Debug.Log("here"); if(pageNo != totalpage) { isPopulateDown = true; pageNo++; nextp(); } }

#

this works sometimes but not efficiently

lean sail
rigid island
#

sadly unity doesn't have a built in- virtualization component / function

plucky inlet
#

For user convenience, you can also show a preloading item, like those placeholder items you see these days on websites and apps, when content is not done loading, which will give you another more smooth transition

chilly surge
#

Virtual scroller is pretty easy to implement though, especially since you have known size for each row.

#

You definitely want to implement virtual scrolling if you expect your users to load hundreds of rows, your UI is going to lag to no tomorrow if all of them are loaded, but only ever tens are visible at once.

novel bough
#

@plucky inlet I make the logic when verticalNormalizedPosition < 0.1f it fetch data but after load the data for sometimes verticalNormalizedPosition stays less than 0.1f so i get multiple calls of API

rigid island
#

You should preload the data

lean sail
plucky inlet
#

And as bawsi said. Use a state, do not let guesswork control your flow

novel bough
#

which function I should use to force update scrollview @plucky inlet

plucky inlet
#

Keywords, forceupdate ui unity layout

novel bough
lean sail
novel bough
#

@bawasi Correct!

plucky inlet
#

Yeh, textmeshproui creates meshes which will fail at a certain length

low arrow
#

This is a new file, Rider isn't detecting the serialized field or marking the unity message

#

This is an old file that was parsed correctly before i was having this issue

cosmic rain
tawny elkBOT
low arrow
# cosmic rain Share !code properly. As well as errors

The code isn't actually the issue here. I wanted to share how the syntax highlighting looked in rider, what the code does isn't important. The errors arent anywhere in my code, somewhere the rider extension is throwing an error, but i can't set breakpoints in there and I don't know how to diagnose the issue

cosmic rain
low arrow
#

Ooh, fair

low arrow
# low arrow I can't get Rider to sync with unity. I set the logging to verbose and am gettin...

The first error, it says it's from RiderPlugin https://hastebin.com/share/azarawuqop.vbnet
The second error, it says it's from RiderPackageInterop https://hastebin.com/share/wudogezehe.vbnet
And the error i keep getting on domain reloads. This didn't require me to turn on verbose logging. https://hastebin.com/share/hofezijuke.vbnet

zealous bridge
#

I am on linux, I cannot use VS and vscode has no auto complete. I have been trying to setup vscode but it is so nerve wracking. What script editors are easy to setup with unity auto complete?

chilly surge
#

!ide

tawny elkBOT
chilly surge
#

You can follow the link here.

knotty sun
zealous bridge
#

I use linux because that way I can avoid boring process of setting up or installing something I would struggle as a windows user. I am not willing to go back to windows just because this particular problem. That would mean backup everything and lose time to installing of windows OS. I have 2 unity projects as university assignments and I think I cannot afford that much time to backup everything, install windows again and install all the software manually. Is there some script editor except vs, vscode and rider? I know vscode is much better than monodevelop, but maybe monodevelop is easier to setup? I was trying to setup vscode auto completion for 2 days - lost my nerves and gave up already. Does monodevelop come with auto completion by default? If not, which script editors have that auto completion out of box and easy to setup?

knotty sun
olive bobcat
#

Can I ask some complex question about gizmos? ๐Ÿ˜…

#

I've made a script that takes an array of objects and calculate the average size, to draw a gizmo so the user can have an idea of the volume occupied, the problem is that I can't rotate it on the pivot point.
What I'm missing?

#
{
    float averageHeight = CalculateAverageSizeY();
    Vector3 gizmoPosition = transform.position + new Vector3(0, averageHeight / 2, 0);

    Matrix4x4 cubeTransform = Matrix4x4.TRS(
        transform.position,
        transform.rotation,
        Vector3.one
    );

    if (isSelected)
    {
        Gizmos.matrix = transform.localToWorldMatrix;
        Gizmos.color = gizmoColor;
        Gizmos.DrawCube(transform.worldToLocalMatrix.MultiplyPoint(gizmoPosition), DrawAverageSizeGizmo());
        Gizmos.color = gizmoColor * 2;
        Gizmos.DrawWireCube(transform.worldToLocalMatrix.MultiplyPoint(gizmoPosition), DrawAverageSizeGizmo());
    }
    else
    {
        Gizmos.matrix = cubeTransform;
        Gizmos.color = gizmoColor;
        Gizmos.DrawCube(transform.worldToLocalMatrix.MultiplyPoint(gizmoPosition), DrawAverageSizeGizmo());
        Gizmos.color = gizmoColor * 2;
        Gizmos.DrawWireCube(transform.worldToLocalMatrix.MultiplyPoint(gizmoPosition), DrawAverageSizeGizmo());
    }
}```
#
{
    float volumeSum = 0f;
    foreach (GameObject obj in objects)
    {
        Vector3 objSize = obj.transform.lossyScale;
        float objVolume = objSize.x * objSize.y * objSize.z;
        volumeSum += objVolume;
    }
    averangeSize = volumeSum / objects.Length;
    return averangeSize;
}
#

I think I'm placing the gizmo on the wrong position, but when the corrds are 0,0,0 looks fine.

hexed pecan
zealous bridge
#

Linux is cool because most of software is available through apt or snap (I use ubuntu) but some programs require much more patience when it comes to find commands needed for installation. However, I just look on the internet, find and try out commands, manage to install 99% of software I need. Once I have saved that set of bash commands to a bash script, I can install that complex program just by running the script. (Maybe this is oftopic for the channel, sorry if so, just to finish my thoughts). So basically on linux, most of programs are possible to install with single command(apt, snap)/or script. I also have wget so I can easily download apt unavailable software from internet in programmable way. (Sorry for going too much offtopic - channel should be about unity code)

hexed pecan
#

@olive bobcat If you just set matrix to localToWorld and then use (0, 0, 0) as the position in DrawCube, it will draw on the transform.position

#

(Maybe I'm missing something here - just trying to make sense of it :p)

olive bobcat
#

At a certain point I was coding blinded, not even sure what I was doing, but it works... until I rotate it ๐Ÿ˜…

hexed pecan
hexed pecan
#

I think you want something like this?cs Vector3 gizmoPositionLocal = new Vector3(0, averageHeight / 2, 0); Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawCube(gizmoPositionLocal, ...);

olive bobcat
#

๐Ÿค” Let me test it ๐Ÿ™‚

hexed pecan
#

No need to muiltiply the position with a matrix again, setting the Gizmos.matrix takes care of that

#

And it should rotate with the transform

olive bobcat
#

YEEEA \o/
Thank you so much ๐Ÿป

#

I was banging my head on the keyboard for hours ๐Ÿ˜…

hexed pecan
#

Np ๐Ÿ˜„ You overcomplicated it a bit

olive bobcat
#
 {
     float averageHeight = CalculateAverageSizeY();
     //Vector3 gizmoPosition = transform.position + new Vector3(0, averageHeight / 2, 0);
     Vector3 gizmoPositionLocal = new Vector3(0, averageHeight / 2, 0);

     Matrix4x4 cubeTransform = Matrix4x4.TRS(
         transform.position,
         transform.rotation,
         Vector3.one
     );

     if (isSelected)
     {
         Gizmos.matrix = transform.localToWorldMatrix;
     }
     else
     {
         Matrix4x4 _cubeTransform = Matrix4x4.TRS(
         transform.position,
         transform.rotation,
         Vector3.one
         );

         Gizmos.matrix = cubeTransform;
     }

     Gizmos.color = gizmoColor;
     Gizmos.DrawCube(gizmoPositionLocal, DrawAverageSizeGizmo());
     Gizmos.color = gizmoColor * 2;
     Gizmos.DrawWireCube(gizmoPositionLocal, DrawAverageSizeGizmo());
 }```

And now it looks even better @hexed pecan thank you so much ๐Ÿ˜๐Ÿ‘
hexed pecan
#

Currently to me it looks like: If selected, use pos, rot and scale of the object. If not selected, use pos and rot of the object but a scale of one

#

If that's not the intention, you could just get rid of all this

 Matrix4x4 cubeTransform = Matrix4x4.TRS(
         transform.position,
         transform.rotation,
         Vector3.one
     );

     if (isSelected)
     {
         Gizmos.matrix = transform.localToWorldMatrix;
     }
     else
     {
         Matrix4x4 _cubeTransform = Matrix4x4.TRS(
         transform.position,
         transform.rotation,
         Vector3.one
         );

         Gizmos.matrix = cubeTransform;
     }

And just do Gizmos.matrix = transform.localToWorldMatrix;

olive bobcat
#

umm even better..

        private void OnDrawGizmos()
        {
            if (objects != null && objects.Length > 0)
            {
                CalculateAverageSize();
            }

            DrawGizmo();
        }

        private void OnDrawGizmosSelected()
        {
            DrawGizmo();
        }

        private void DrawGizmo()
        {
            float averageHeight = CalculateAverageSizeY();
            Vector3 gizmoPositionLocal = new Vector3(0, averageHeight / 2, 0);

            Gizmos.matrix = transform.localToWorldMatrix;

            Gizmos.color = gizmoColor;
            Gizmos.DrawCube(gizmoPositionLocal, DrawAverageSizeGizmo());
            Gizmos.color = gizmoColor * 2;
            Gizmos.DrawWireCube(gizmoPositionLocal, DrawAverageSizeGizmo());
        }```
#

xD

hexed pecan
#

There we go, get rid of that extra fluff

olive bobcat
#

Amazing ^_^

#

So now everything is working also scale! ๐Ÿฅณ

#

Here is the complete code: https://pastebin.com/rzuWvvNv
The idea is coming from the Skyrim Creation Kit, which it show a gizmo of random objects.
So you can take different object place it inside the array, and on start it will select just one.
The gizmo shows the average size, so it's important the the size is about the same for all of the prefabs, but for placing bottles, crates, and other props it's really useful ๐Ÿ™‚

olive bobcat
leaden ice
#

Or just use UnityWebRequest

stiff summit
#

how do i add an image to a spriteRenderer via script? (asking here cause i dont wanna cut off a questing in code-beginner)

naive summit
#

Yo guys i got a question
So im making an inventory system for my game and every item has this GrabableObject script. Now the weird part is i got two objects, a basic cube and a OBJ key. Now for some reason the script works completly fine on the Cube so when i press E the cube gets destroyed and goes to the inventory, however the key for some reason doesnt work at all. I got a Debug.Log in the main inventory script and it debugs if the GrabableObject script isnt detected and the weird part is when i click E on the Cube it is detected but when i click e on the key it doesnt. both got a Box Collider, both got the same script. I litreally have no idea what could be the cause.
GrabableObject script :

public class GrabableObject : MonoBehaviour
{
    public int ObjectId;
    public string Name;
    public Sprite Icon;

    public bool isItem = true;

    Inventory inventory;

    // Start is called before the first frame update
    void Awake()
    {
        inventory = GameObject.Find("Human").GetComponent<Inventory>();
    }

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

    public void DestroyItem()
    {
        Destroy(gameObject);
    }

    public void SpawnItem() 
    {

    }



}
#

InventoryScript :

{
    GrabableObject grabableObject;

    public RawImage itemicon;
    public Text itemname;
    public bool isHoldingItem = false;

    public int HoldingItemID = 0;



    // Start is called before the first frame update
    void Awake()
    {
        grabableObject = GameObject.Find("Item").GetComponent<GrabableObject>();
      
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E)) 
        {
            Debug.Log("EClicked!");
            RaycastEvent1();        
        }

        
    }

    public void UpdateItemDetials(string name, Sprite icon) 
    {
        Debug.Log("UpdatedDetails");
        itemname.text = name;
        itemicon.texture = icon.texture;
    }

    public void PickUpItem() 
    {
        Debug.Log("PickUpItem");
        UpdateItemDetials(grabableObject.Name, grabableObject.Icon);
        grabableObject.DestroyItem();
        HoldingItemID = grabableObject.ObjectId;
        isHoldingItem = true;       
    }

    public void DropItem() 
    {

    }

    public void RaycastEvent1()
    {
        Debug.Log("RaycastSent");
        RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.forward, out hit, 100f))
        {
            grabableObject = hit.collider.gameObject.GetComponent<GrabableObject>();
            if (grabableObject != null)
            {
                if(grabableObject.isItem == true) 
                {
                    PickUpItem();
                }
            }
            else 
            {
                Debug.Log("NoGrabAbleObject");
            }
        }
    }



}
tawny elkBOT
turbid spade
heady iris
#

just make sure you don't touch any unity objects from another thread!

craggy pivot
#

Is there a way to have bindings such that I can have the number pressed in the number row as a value in the CallbackContext of the InputAction?

ClientInput.Primary.Hotbar.performed += ctx => Debug.Log(ctx.ReadValue</* ? */>());
heady iris
leaden ice
heady iris
#

see InputAction.CallbackContext.control

#

but yes

#

each hotbar slot should be its own action

craggy pivot
heady iris
#

notably, this will let you bind your hotbars to both the number row and the number pad!

#

You want to avoid thinking about the input bindings as much as possible

leaden ice
#

It will also give you proper rebinding support

heady iris
#

The input system's job is to trigger actions in response to controller input

craggy pivot
#

I suppose this could just be my perception but it feels like I should be compacting it as much as possible

heady iris
#

Each action is a thing you can do in your game.

#

You don't have a single hotbar action that can be triggered in many ways

#

You have many hotbar actions that each have a single way to trigger them

#

if you start peeking at the controller input, you might as well just not use actions at all and directly read UnityEngine.InputSystem.Keyboard.current.digit3Key.isPressed or something

craggy pivot
#

Would you suggest that's a better practice?

heady iris
#

No, I think that's a bad idea!

craggy pivot
#

Ohhh mb

heady iris
#

since it means you can't do rebinding later, and you also can't support any other input device

craggy pivot
#

Right

heady iris
#

you might want to let a controller activate a smaller number of hotbar slots with the face buttons

#

for example

craggy pivot
#

Suppose I use a an action for each of the 10 hotbar slots, (only 3 are shown, I plan for 10), and then when adding controller support I decide to make the hotbar scrollable, like console minecraft. Would that be challenging to implement?

heady iris
#

In that case, you would have separate actions that are only used in the gamepad control scheme

craggy pivot
#

I see, then use those actions to cycle an index or something

knotty sun
# craggy pivot Right

probably not what you want to hear, but I've found it best to completely forget the Unity ActionMap stuff and do everything from scratch

heady iris
#

and why is that?

craggy pivot
knotty sun
#

It's just a damn sight easier and more flexible

knotty sun
heady iris
#

you can manually construct actions, rather than configuring them in an input action asset, yes

#

i would have to see an example of where this is an improvement

craggy pivot
#

Maybe. Something kind of frustrating is how many different ways the new input system can be implemented. I know that's it to be able to support any and all types of input from mobile all the way to VR but it gets annoying. And the docs are still terrible.

craggy pivot
heady iris
#

The newer versions of the docuentation do a better job of introducing the concepts than the older versions did, for sure

#

I found it to be overwhelming at first.

craggy pivot
heady iris
#

well, that's the scripting API

#

but yes, the package documentation

knotty sun
craggy pivot
#

Have i been looking in the wrong place

#

All this time

heady iris
#

just switch to Manual from Scripting API up top

craggy pivot
#

ohhh

heady iris
#

the Manual tab describes how the package works

#

the Scripting API describes every class/method/etc.

craggy pivot
#

Thank you

heady iris
#

I personally use InputActionReference to refer to actions from a single input action asset

#

along with an input manager singleton that turns action maps on and off based on the current game state

craggy pivot
#

My implementation feels so jank

#

I use a class as a sort of singleton and just refer to it from any script that needs to bind a function to an action

heady iris
#

you're using the generated C# class, correct?

craggy pivot
#

Yeah

heady iris
#

Seems reasonable enough.

#

although putting the cursor locking code in there seems weird

craggy pivot
#

The only reason is that those things usually happen at the same time

#

I'm making a multiplayer game and the class is only spawned with the player object when they spawn in the server

kind cloak
#

Hi ! I have an issue with my VR game. I'm working on the Quest 2 in c# , and each time i'm trying to access to a local file (that i've created myself) my app freeze for like 1s and then everything came back to normal. Do you think it's a code error related ? or unity error related ? or Quest 2 error related ?

heady iris
#

if you block on the file read, and the file read takes a while (slow storage, maybe), your game will freeze

kind cloak
#

So, even if i try to do this asynchronously, this will still freeze right ?

heady iris
#

asynchronously reading the file would allow the rest of the game to keep running

#

I'm not sure what the correct way to do this on older versions of unity is, though (i've only used Awaitable in 2023.2.x)

kind cloak
#

i think i know the way but i was wondering if it was really the issue

#

so thanks !

west knot
#

I am trying to get a tangent line on a spline. The tangent should start from the nearest point to my "player". That part works fine.

However when I draw a Gizmo to view the tangent line it is clearly not tangent. I used SplineContainer.EvaluateTangent, which according to the manual should give me a point in World Space.
I have also tried using SplineUtility.EvaluateTangent, then transforming it back into World space butthat gives weird results as well.

I have attached a photo of my gizmo output.

Code: https://hastebin.com/share/vegatocote.csharp

#

Oh the gizmo is in Red and spline is blue

heady iris
#

is that red line perpendicular to the spline?

#

it's impossible to tell from a single screenshot

west knot
#

supposed to be, but isn't

heady iris
#

The tangent is supposed to be along the spline

#

hence it being tangent

#

the up vector is perpendicular to the spline

leaden ice
heady iris
#

and yes

#

you're trying to use a direction vector as a position

#

the tangent and up vectors are directions

leaden ice
#

Your problem is you are doing DrawLine which takes two POSITION vectors and you're passing at least one DIRECTION vector into it

west knot
#

but if i use the start point and the tangent vector that should draw the line tangent to the spline right?

leaden ice
#

DrawRay(startPoint, tangent)

#

ray not line

west knot
#

oh ok

leaden ice
#

if you want to use Line it would be DrawLine(point, point + tangent)

west knot
#

been a long time since i messed with vectors in math

heady iris
#

you'd better get used to them :p

west knot
#

haha yeah, bringing back memories of college ๐Ÿ™‚

heady iris
#

especially with something as fundamental as positions vs. directions

craggy pivot
#

This feels so wrong ๐Ÿ˜ญ ๐Ÿ˜ญ ๐Ÿ˜ญ

#

Absolutely violating DRY principal

west knot
#

i'm going to correct that and see how that works, but first time to take the kid to work

leaden ice
gray thunder
#

ohboy

thin aurora
craggy pivot
#

As delegates?

thin aurora
#

Why have 10 variables that do the same thing, when the only difference is the index

leaden ice
# craggy pivot As delegates?
InputAction[] hotbarActions = new IntputAction[] {
  Hotbar1,
  Hotbar2,
 ...
}

void AssignHotbarListeners() {
  for (int i = 0; i < hotbarActions.Length; i++) {
    int index = i;
    hotbarActions[i].performed += _ => Hotbar(index);
  }
}```
leaden ice
thin aurora
#

Oh great

heady iris
#

It's an awkward case.

heady iris
#

I similarly use a Dictionary<InputAction,System.Action<InputAction.CallbackContext>> to minimize duplicate code when subscribing and unsubscribing

#
            foreach (var actionRef in callbacks.Keys)
            {
                actionRef.action.performed += callbacks[actionRef];
            }

            foreach (var (action, callback) in canceledCallbacks)
            {
                action.canceled += callback;
            }

well, actually, it holds InputActionReference in the first case, but close enough

#

i should make that consistent

#

and i should make the iteration consistent

craggy pivot
knotty sun
heady iris
knotty sun
craggy pivot
heady iris
#

I suppose I could make a list of tuples

knotty sun
heady iris
#

Feel free to tilt at windmills.

thin aurora
#

You don't exactly subscribe/unsubscribe player input often

knotty sun
#

it's a matter of principle

heady iris
#

I would have to be doing something truly catastrophic for there to be a difference.

#

Hundreds of player brains being attached and detached per frame with hundreds of individual actions

placid summit
#

I am loading in models at runtime and want to cache them for re-use like a prefab in the editor! But I think there is no way to do this except to import them to scene and make them invisible before Instantiating a copy when required?

craggy pivot
heady iris
#

These would be equally readable, at least

#

I might even make the change to a tuple list, since that would allow for multiple functions to respond to a single action being performed

leaden ice
knotty sun
heady iris
#

It is not very high on the priority list, though

#

I have much bigger gains to make by memoizing most of the objects my AI system is constructing and then dropping on the floor ๐Ÿ˜‰

placid summit
leaden ice
#

Those can also be part of the prefab, or be applied to the Renderer after spawning

placid summit
naive swallow
knotty sun
naive swallow
stable lintel
#

i can combine any meshes using Mesh.CombineMeshes?

knotty sun
naive swallow
knotty sun
wise kindle
#

Speaking about classes. I've been trying to scout the internet in search for answers, but how can you do things such as using System and using System.Collections at the same time? Wouldn't the global namespace already contain a definition for System? Because when I try doing that I cannot do it

#

My issue is that I want to have a static class called Generic, but I also want to have one called Generic.Timers for example. How could I do that?

placid summit
#

don't conflict namespaces with classes

naive swallow
# wise kindle Speaking about classes. I've been trying to scout the internet in search for ans...

Whenever you do using <something> you can direct access to any specific members of <something>. Without it, you'd need to fully qualify the type name. For example, a List is actually a System.Collections.List. You could use that instead of any using statements and it'd compile. With just using System, you could use Collections.List to reference the list, but you can only do just List with a using System.Collections

leaden ice
wise kindle
#

Alright then, so for example, if I declare a static class inside of another static class, that would work for what I am looking for, yes?

knotty sun
wise kindle
#

Why so?

knotty sun
#

because Generic is not very meaningful and both could be easily confused

dawn nebula
#

Looking to optimize this script. It redefines an Image to only have a clickable region along an arc segment of a specified thickness and arc length in degrees.

    [SerializeField] float innerRadius;
    [SerializeField] float outerRadius;
    [SerializeField] float arcLength;

    public override bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
    {
        bool baseResult = base.IsRaycastLocationValid(screenPoint, eventCamera);

        if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, screenPoint, eventCamera, out Vector2 local))
            return false;

        local /= rectTransform.sizeDelta / 2;

        var centerDistance = local.magnitude;

        bool inRadius = centerDistance >= innerRadius && centerDistance <= outerRadius;

        var angleVector = local.normalized;
        var angleValue = Mathf.Acos(Vector2.Dot(angleVector, Vector2.right));

        bool inAngle = angleValue <= arcLength * Mathf.Deg2Rad / 2;

        return baseResult && inRadius && inAngle;
    }
hexed pecan
#

Why are you looking to optimize it though?

#

Seems like pretty simple math operations already

dawn nebula
#

Just interest. It runs fine.

#

Trig always tends to always have some fun intricacies.

zenith timber
hexed pecan
#

Too many people lately asking for help without asking a question

knotty sun
#

Also, I told you to post your code correctly

spring creek
vivid halo
heady iris
#

I'd try using a logarithmic function with an offset

#

or maybe 1/x

chilly surge
#

Surely you can make exponential function to fit.

latent latch
#

You can use a animation curve then set the gradual increase from sampling the last few points

heady iris
#

e^(-x/100) is almost there; you just need to do something to actually reach zero

chilly surge
#

y = a ^ (x + b) + c, b and c controls the offset in two axis, while a controls how aggressive the curve up is.

heady iris
#

I suppose you could do this

#

The exponent isn't exactly what you're looking for

#

This lerps between e^(-x/100) and zero over the 0..700 range

south saddle
#

No bug report or help forum?

I'm pretty sure I got a Unity bug.

namespace Game.Core
{
    [DefaultExecutionOrder(2)] // Run after systems subscribe to state changes.
    public class GameControllerSystem : ManagedSystem
    {
        private void Start()
        {
            Logger.LogDebug($"GameControllerSystem is starting. Frame: {Time.frameCount}");
            GoToMainMenu();
        }

The script above always starts before the script below

namespace Game.UI
{
    [DefaultExecutionOrder(-1)]
    public class MainMenuSystem : ManagedSystem
    {
        private void Start()
        {
            Logger.LogDebug($"MainMenuSystem is starting. Frame: {Time.frameCount}");

Whyyyyyy?? These are not in sript order settings, and when they are and the GameControllerSystem is on the bottom it still executes first.

latent latch
#

Are they monos?

south saddle
#

yes

heady iris
#

okay, and what's the actual execution order?

south saddle
#

no special logic or anything. They are loaded from addressables, but then spawned normally. Both on frame 1.

latent latch
#

Actually never used the attribute, but no clue why it wouldn't appear in the script ordering settings.

chilly surge
heady iris
#

if you created these components before you added the attribute, then I would expect them to still have the execution order they were originally assigned

south saddle
heady iris
#

I tried it to see if it would fix it, but no

what is "it"?

latent latch
#

Probably has to do with the addressable loading. I'd debug it without loading them first and see if you can manage that.

south saddle
#

They execute correctly ONLY if present in the scene when loading..

south saddle
heady iris
#

otherwise you wouldn't be able to guarantee which frame the operation actually completes on

#

I see that you are logging the frame count. I presume they're both printing a 1

south saddle
#

assetWithLocation.Asset = Addressables.LoadAssetAsync<T>(location).WaitForCompletion(); Synchronously

#

I'll try to just spawn directly

knotty sun
latent latch
#

I'd just make myself my own script at that point and initialize them in the ordering I want after getting them from the addressable

south saddle
#

So.. I spawned them manually. Very interesting..... Their execution order depends on spawn order. The attributes don't apply. I know the Awake should work like that, but I was certain that Satart() is ordered by attributes and settings....

latent latch
#

Start is wonky. Don't depend on it.

knotty sun
#

The only thing you can depend on with Start is it runs after Awake, period

latent latch
#

I'd use Start for general local initialization values. Anything that requires an order of operations should not be included in it.

south saddle
knotty sun
south saddle
#

It does not work for Awake.

#

It DOES work for Start, but only if objects were in the scene already. And it SHOULD work. It is very useful. It is a BUG.

leaden ice
#

Uhh I think this is more a quirk opf how Start works

#

it's not really like other event functions

#

It's more like all the other event functions like Update, FixedUpdate etc all have an:

if (!startHasRun) Start();``` before them
south saddle
#

Start works like Update. Same thing. I'm pretty sure.

leaden ice
#

no - it's quite special

#

depending on where in the scene the object was created, it will run before a different event function

south saddle
#

I was certain that all starts are executed in order before all updates. I'm pretty sure that it's what docs would say. But if there are more bugs, I'm not gonna be too surprised.. sadok

#
        private void Start()
        {
            Invoke(nameof(GoToMainMenu), 0.01f);
        }

๐Ÿคช

leaden ice
#

or:

IEnumerator Start() {
  yield return null;
  GoToMainMenu();
}```
south saddle
#

I hate that syntax ๐Ÿ™‚

#

or:

        async void Start()
        {
            await Task.Yield();
            GoToMainMenu();
        }

purely subjectively it's not ugly XD

#

I could....... Manually read attributes and spawn things in order of the [DefaultExecutionOrder()] Or better custom [SpawnOrder] or [ExecutionOrder].

south saddle
#

Magic ๐Ÿช„

south saddle
#

If Unity fix that bug and [DefaultExecutionOrder] will start working as advertised always, it will break a lot of projects ๐Ÿ˜†

pine carbon
#

public fields coming from upper abstract class doesnt show up in the inspector

south saddle
#

Can you show the code of those fields?

pine carbon
#
public abstract class SurvivalObject : MonoBehaviour {
    public Transform textPosition;
    public string text;
    public abstract void Interact();
}
#
public class ChessBoard : SurvivalObject {

    public override void Interact() {
        Debug.Log("satranรง tahtasฤฑ");
    }
}
```and the upper class
somber nacelle
#

do you perhaps have a custom inspector for the ChessBoard type and just aren't drawing those fields?

south saddle
#

Wel, yeah.. idk wha I expected. Pretty straight forward. Should work..

latent latch
#

make sure ya project is compiling

pine carbon
#

oh wait it showed up rn

#

idk why that happened

#

weird

south saddle
pine carbon
#

sory for takin your time

somber nacelle
silver zealot
#

heyo i've been struggling for a while trying to figure out why my state machine isn't working for a little game i'm making hopefully someone can help me. I have 5 script consisting of State, StateManager, IdleState, ChaseState and AttackState. Watched several tutorials looked up on stack overflow and other places but couldn't figure out a solution. when debuging everyting seems to be fine but the actual enemy never moves and in general skips chase state just goes to attack and sits in one spot. I've had help making the movement component so that shouldn't be a problem.
State.cs --- https://hastebin.com/share/cixuhuvuno.csharp
StateManager.cs --- https://hastebin.com/share/fajefulasa.csharp
IdleState.cs --- https://hastebin.com/share/orawewabud.csharp
ChaseState.cs --- https://hastebin.com/share/xoyujerace.csharp
AttackState.cs --- https://hastebin.com/share/reyolepugo.csharp
i know its a big shout for help but i just dont know what else to do and i don't want to drop this project. Also don't know if this is the channel to ask for help with state machines :))

rigid island
rigid island
silver zealot
#

this is for some insight on how it currently works

silver zealot
rigid island
lean sail
#

Using a coroutine in your states is also kinda suspicious. Your logic should really only be running based on if the state machine calls it to run. And having it return a next state kinda kills any modular code.

#

Coroutines would make more sense if logic actually needed to run outside like some sort of cooldown

silver zealot
lethal vigil
#
    void GenerateMaterialButtons()
    {
        for (int i = 0; i < materials.Length; i++)
        {
            GameObject button = Instantiate(materialButtonPrefab, materialButtonContainer);
            int index = i; // Capture the index for the closure
            button.GetComponent<Button>().onClick.AddListener(() => SelectMaterial(index));

            // Optionally, set a thumbnail or color on the button to represent the material
            button.GetComponentInChildren<Image>().color = materials[i].color;

            materialButtons.Add(button);
        }
    }

    void SelectMaterial(int index)
    {
        selectedMaterialIndex = index;
        Debug.Log("Selected Material Index: " + selectedMaterialIndex);
    }

    void ApplyMaterial()
    {
        if (characterRenderer != null && materials.Length > selectedMaterialIndex)
        {
            Material[] currentMaterials = characterRenderer.sharedMaterials;
            int[] indicesToUpdate = { 0, 1, 3, 4, 7 };

            foreach (int i in indicesToUpdate)
            {
                if (i < currentMaterials.Length)
                {
                    currentMaterials[i] = materials[selectedMaterialIndex];
                }
            }

            characterRenderer.sharedMaterials = currentMaterials;
            Debug.Log("Applied Material Index: " + selectedMaterialIndex + " to specified material slots.");
        }
    }

    void SaveMaterial()
    {
        PlayerPrefs.SetInt("CharacterMaterialIndex", selectedMaterialIndex);
        PlayerPrefs.Save();
        Debug.Log("Saved Material Index: " + selectedMaterialIndex);
    }

    public void LoadMaterial()
    {
        selectedMaterialIndex = PlayerPrefs.GetInt("CharacterMaterialIndex", 0);
        ApplyMaterial(); // Apply the loaded material
        Debug.Log("Loaded Material Index: " + selectedMaterialIndex);
    }
#

This code applies a new material to my player, this works fine when testing it but when on mobile the material wont change even though the debug logs clearly set and save and load the correct material

lean sail
#

I recommend having another script which can decide between what states to enter at least. Or just have a unique way of setting up transitions between states

silver zealot
#

thats what im trying to figure out

#

as for debuging i can see which state its it in the inspector

spark tinsel
#

I'm returning to a project I was about half way through, my second real project.
I didn't know about the c# event when I last worked on it, which I should have been using.
Now I can't help but think what other c# keywords, objects, etc.. I should know

#

I realize that's not really a question lol.
I guess I wonder if there's any sort of "beginner c# unity essentials", "intermediate unity c# essentials", "expert unity c# essentials" anyone's come across?

#

I guess it's always the way. You could do a extensive c# course and know all the things, and wait ages to start on a project and actually practice.
Or you could learn a decent amount, work on your project, get good practice in, and realise later how many wheels you re-invented lol.

#

Or I guess I could not be a silly sausage for once, and actually ask for advice throughout my project lol

#

Anyway, apologies for the ramble, any pointers or advice is appreciated.

knotty sun
spark tinsel
rigid island
spark tinsel
rigid island
#

gives me a good idea for a clickbait video title
"20 Absolutely MUST KNOW Unity C# {insert thing} "

knotty sun
lean sail
spark tinsel
lean sail
#

Of course theres the talk of proper design, but as for actually just getting logic working you dont need much

rigid island
#

at least I didn't make all those "Unity game dev tries Godot for the first time "

knotty sun
fleet gorge
#

manufacture those spam shorts and get a lot of engagement

rigid island
fleet gorge
#

tagging #gamedev will get you views

#

stuff related to unitys UI system helps a lot since there isnt a lot of good guides

rigid island
spark tinsel
fleet gorge
#

make youtube worse

knotty sun
rigid island
#

those actually do very well " 10 Reasons why you will hate gamedev"

#

"10 things I wish I knew before starting gamedev"

naive swallow
#

Do the clickbait title incredibly over the top and constantly make jokes about how dumb and bad it is so you can get the free clicks but also maintain moral integrity

#

(But for real though don't hate the player hate the game do clickbait if it works)

spark tinsel
naive swallow
rigid island
#

too true ๐Ÿ˜ข

spark tinsel
knotty sun
heady iris
rigid island
#

Unity bank transaction simulator

spark tinsel
heady iris
#

i'm well on my way to making an epic bacon video

#

urgh

#

that hurt to type

rigid island
heady iris
spark tinsel
spark tinsel
knotty sun
rigid island
rigid island
knotty sun
spark tinsel
#

Love this

#

It is a struggle between actually taking good advice, and not letting people who don't have the same vision make you feel it won't work.
I mean sometimes they're right, but I guess you have to try and fail, try and fail, before you do what hasn't already been proven to work.

lean sail
rigid island
#

or am i the only one that would break electronics apart just to see how it was all magically working

#

but I guess earlier products were also more friendly to "tinkering" now everything is some bs factory locked/warranty killer
cars are good example of this

#

kid is born into an ipad, doesn't care how it works

swift falcon
#

i just decided today to scrap the particles altogether

knotty sun
#

But don't you think that anyone who does Computer Systems Development, which is what Game Dev is, should at least know how a computer works?

rigid island
#

bringing it back to coding is like using a framework such as Entity Framework to deal with SQL but then if something breaks on the database now you have no clue how SQL works because you meerly interacted through abstraction and cannot fix the raw SQL tables n shit

spark tinsel
#

I recently filled the gaps in my knowledge with a course that went though the whole OSI.
It makes me feel much more complete in some way, to be able to look at tech and know from start-to-finish how the information flows, there's no magic black-box at any step in my brain.

lean sail
spark tinsel
rigid island
spark tinsel
rigid island
#

also we're getting a bit offtopic from unity coding ๐Ÿ˜…

spark tinsel
lethal vigil
#

How can I change / update at material on my player on button click, ATM it only does it when i restart the game

    void SelectMaterial(int index)
    {
        selectedMaterialIndex = index;
        Debug.Log("Selected Material Index: " + selectedMaterialIndex);
    }

void ApplyMaterial()
{
    if (characterRenderer != null && materials.Length > selectedMaterialIndex)
    {
        Material[] currentMaterials = characterRenderer.sharedMaterials;
        int[] indicesToUpdate = { 0, 1, 3, 4, 7 };

        foreach (int i in indicesToUpdate)
        {
            if (i < currentMaterials.Length)
            {
                currentMaterials[i] = materials[selectedMaterialIndex];
            }
        }

        characterRenderer.sharedMaterials = currentMaterials;
        PlayerPrefs.SetInt("CharacterMaterialIndex", selectedMaterialIndex); // Update PlayerPrefs immediately
        PlayerPrefs.Save(); // Save PlayerPrefs immediately
        Debug.Log("Applied Material Index: " + selectedMaterialIndex + " to specified material slots.");
    }
    else
    {
        Debug.LogWarning("CharacterRenderer is null or materials array is empty or selectedMaterialIndex is out of range.");
    }
}


void SaveMaterial()
{
    PlayerPrefs.SetInt("CharacterMaterialIndex", selectedMaterialIndex);
    PlayerPrefs.Save(); // Save PlayerPrefs immediately
    Debug.Log("Saved Material Index: " + selectedMaterialIndex);
}

public void LoadMaterial()
{
    selectedMaterialIndex = PlayerPrefs.GetInt("CharacterMaterialIndex", 0);
    ApplyMaterial(); // Apply the loaded material immediately
    Debug.Log("Loaded Material Index: " + selectedMaterialIndex);
}

heady iris
#

what does clicking the button actually do?

lunar lynx
#

is it possible for Object A to detect if Object B is colliding without attaching a script to Object B?

somber nacelle
#

the only objects that will be sent a message upon collision are the two objects involved in the collision (or their rigidbody if they are a child of a rigidbody)

lunar lynx
#

damn...

#

ok thanks

vivid halo
#

General question โ€” does anybody here feel like they deeply understand quaternions beyond the Unity functions that transform them?

#

I am unsure how deeply of an understanding of quaternions can help when coding them

latent latch
#

they just do

heady iris
#

even less than understanding the math behind transform matrices

west knot
#

does anyone understand quaternions?

leaden ice
west knot
#

I used to have a basic understand, as I needed them for creating a calibration procedure for a magnetic tracking system

heady iris
#

they're just complex-er numbers

#

but I work entirely with Unity's methods

vivid halo
#

I just feel a bit uneasy putting Quaternion.Euler functions in my code, seeing a positive result, and depending on that to remain consistent without a good understanding of how reliable it actually is under the hood

heady iris
#

i mean

#

what would make you confident?

vivid halo
#

I can operate on looks good is good

heady iris
#

what if Vector3.Distance secretly didn't work on Tuesdays?

vivid halo
#

If I were a math wizard and understood the fourth dimension of rotation through and through

heady iris
#

If you are using the methods correctly, you can be confident in what you're doing

#

I don't use Quaternion.Euler much; I mostly use Quaternion.AngleAxis

#

I find it a bit easier to reason about

lean sail
# vivid halo I just feel a bit uneasy putting Quaternion.Euler functions in my code, seeing a...

as long as you're confident in what values you put in, theres really no reason to have doubts. The only operation you really do with quaternion is "adding" your rotation. To answer your question above on if people deeply understand them, id be surprised if more than 10 people here do. Like I know what Quaternion * Quaternion is used for but the actual math behind it is more complicated. Unity simplifies it for you, the actual math is like Q x P x Q^-1.

vivid halo
#

Okay, that makes sense. I heard that very few people understood quaternions and I was uncertain if that was an exaggeration or a shortcoming.

There was one time a few months ago I made a mistake in my camera rotations which was exclusively caused by some Quaternion issue and I was wondering if it was worth learning more in-depth. I suppose not

#

The specific issue was a camera max-pitch min-pitch limit being exceeded when the camera's Z-rotation flipped from -359 to 0, iirc

heady iris
#

that's not really a quaternion issue

#

in that case you're just getting surprised by how euler angles wrap around at 360

lean sail
#

And if you need euler angles, its best usually to keep track of your own euler angles if possible then do logic. Sometimes it isnt possible like if you have some rigidbody which is being knocked around because those values will drastically change while the actual object didnt move much.

vivid halo
low arrow
#

The creation of Packages.Rider.Editor.RiderScriptEditor is failing for some reason, inside CsprojModifier.Editor.Features.InsertAdditionalImportFeature.OnGeneratedCSProject

desert anvil
#

Anyone knows how to fix bullets phasing through walls? sometimes it doesn't sometimes it does

I tried using Continuous collision detection on the bullets but they still phase through the wall. :/

rigid island
#

show move code

desert anvil
#

!code

tawny elkBOT
desert anvil
#

i instantiate the bullet then change the velocity

rigid island
#

is the speed like really high

desert anvil
#

errr

#

i've seen higher

rigid island
#

well most bullets are faked

#

if you want precision

#

the video didn't really answer how much speed are you putting in ? Continuous should be able to help, if not you can try just doing a rb.SweepTest

desert anvil
#

sweeptest? ill go read on that! thanks :3

rigid island
# desert anvil 160

hmm maybe try less speed but instead of setting velocity directly do AddForce, Force.Mode.Impulse maybe

lean sail
#

I would just raycast really, you dont need a rigidbody if you're faking it anyways

rigid island
#

I did hear sometimes setting velocity directly can cause odd behavior

#

rigidbody are easy to deal with when it comes to bullet trails, bullet drop etc.. but painful in these situations

lean sail
#

the literal only difference i can think of, is that this would be set immediately and not during the physics step

rigid island
#

hmm yea something to test for sure, I'll check it out

lean sail
#

that was something i noticed before, with addForce and trying to immediately limit a rigidbodies velocity. the velocity is applied after so limiting it right away does nothing

desert anvil
#

i might just go for raycasting to hit enemies with bullets but still not sure how to make the bullets stop going through walls, even if its fake

rigid island
#

impulse still takes into account deceleration while velocity doesn't

rigid island
#

no way they gon miss lol

#

if you need fancy shite like bullet trails you can easily just lerp from startpos to hitpoint / infinte ray

desert anvil
#

ayo?

grim bay
#

Anyone might be available for reading and criticising my interaction code? I want to improve/optimize it so bad but i have no clue what or how to do so.. thisisfine

rigid island
tawny elkBOT
rigid island
#

imo , ask yourself few things if its working.
1 are you going to extend this script
2 are you able to read it clear, and know what's going on at a glance

If you answer yes then you're good to go

stark fiber
#

Hey guys, quick question for those of you who use Visual Studio, how do I not proceed with a suggestion it offers me? When it thinks it knows how to correct what I'm doing I don't know how to tell it to not proceed with the correction aside from ctrl+z after the fact, a little annoying when it's so obviously off the mark.

cosmic rain
rigid island
#

(don't forget to restart vs ofc) ๐Ÿ˜›

stark fiber
stark fiber
cosmic rain
obsidian oak
#

I want to replicate this curve in my AnimationCurve, is there a way, or do i just need to eyeball it

cosmic rain
obsidian oak
#

oh i dnt know there were functions to edit animation curves

cosmic rain
#

There aren't

#

I mean unrelated to an animation curve

obsidian oak
#

ohhh

#

okok

#

ty

runic nimbus
#
public class Backpack : MonoBehaviour {
    [SerializeField] BoxCollider check;
    Dictionary<GrabInteractable, Action> previous = new();
    
    void Update() {
        List<GrabInteractable> overlap = Physics.OverlapBox(check.transform.TransformPoint(check.center), Vector3.Scale(check.transform.lossyScale, check.size) / 2, check.transform.rotation)
            .Select(x => x.GetComponent<GrabInteractable>())
            .Where(x => x != null)
            .ToList();

        
        foreach (GrabInteractable grab in previous.Keys.ToList()) { // Are you still there?
            if (!overlap.Contains(grab)) {
                grab.onDropped -= previous[grab];
                previous.Remove(grab);
                print($"Removed {grab.name} from previous");
            }
        }

        foreach (GrabInteractable grab in overlap) {
            if (!previous.ContainsKey(grab)) { // Are you new?
                Action droppedAction = () => PutInBackpack(grab);
                grab.onDropped += droppedAction;
                previous.Add(grab, droppedAction);
            }
        }
    }

    void PutInBackpack(GrabInteractable item) {
        item.transform.SetParent(transform);
        item.rb.isKinematic = true;
    }
}```
#

Look at this piece of shit

#

I hate how this works. From the linq to the backwards iteration

#

What's a better way of doing this?

runic nimbus
# runic nimbus ```cs public class Backpack : MonoBehaviour { [SerializeField] BoxCollider c...

to paraphrase

  1. Overlap all grab interactables in the backpack area
  2. Compare the current overlap to the previous one, remove anything that is no longer there and unsubscribe from the OnDropped method (in case you decided to change your mind about putting an item in the backpack)
  3. For every grabbable, subscribe to make sure that when you drop it in, the item is put into the backpack
mossy snow
#

that's going to spew a lot of garbage every frame

runic nimbus
#

Yeah

fervent furnace
#
overlapbox();//use an existing buffer0 (List<Collider>)
buffer1.clear();//List<GrabInteractable> again an exisiting buffer1
for(collider in buffer0)//for or foreach loop
  try get component then add it to buffer1

now you have two lists (sets) ofprevious stored GrabInteractable s and currently overlapping GrabInteractable s
since the number of GrabInteractable s is small, so i think you dont need to use dictionary or hashset, juset iterate and find
#

if the number is large, then ofc use a hashset or dictionary

runic nimbus
#

Your psuedocode is a little bit too psuedo for me, sorry. I'm confused on some parts. Can you elaborate?

lean sail
#

do you even need the anonymous method there, it looks like you can just directly subscribe/unsubscribe

runic nimbus
fervent furnace
#

you can make a pair of <GrabInteractable ,Action>
same as what dictionary does

runic nimbus
#

Tuple?

#

Wdym pair

maiden stone
#

Hello all. I'm wondering if anyone may know of a way to read specific values of variables of a property drawer? I am trying to use a scriptable object with a property drawer to contain a specific set of audio files, and then use a gameobject to reference that (or any given) scriptable object and then call a method which then returns my audio clip. An example of what I'm trying to do (in a completely made up section of code):

ScriptableObject SO;

AudioClip audioclip = SO.ReadAudio(n)

~~~~~~~~~~~~~~~ How this would function inside
ScriptableObject.ReadAudio(int n) => return ScriptableObject.PropertyDrawer.Sections(n).GetValue("AudioClip")
fervent furnace
#
private struct Entry {
  public int hashCode;    // Lower 31 bits of hash code, -1 if unused
  public int next;        // Index of next entry, -1 if last
  public TKey key;           // Key of entry
  public TValue value;         // Value of entry
}
```a custom struct or use tuple a use named method so you dont need an additional field to store your anonymous method
mossy snow
runic nimbus
#

Yeah I can't use a named method. I need to pass in the parameter to PutInBackpack

#

I don't understand what the custom struct would do here

maiden stone
# mossy snow why bother with a property drawer at all? This would be editor only and seems li...

im using it to contain different sections of audio which will all flow into each other. A way to handle dynamic music. I know it seems impractical. Its to contain each section of a song, but then have that section loop until a specific event is triggered, but have the same code run for all of the songs. This would allow me to only need to focus on what song (scriptable object) is being input into my music handler, and it would control which section is played and looped and such. (I'm sorry. I'm not doing a good job at explaining this). If anyone has a better idea for a way to handle my issue, I'm all ears lol.

fervent furnace
#
//in your GrabInteractable.cs
public Action<GrabInteractable> OnDropped(GrabInteractable x)

when invoked:
OnDropped(this)
```idk if this works in your case
#

then you can subscribe it by just

grab.onDropped+=PutInBackpack
runic nimbus
#

Grab interactables shouldn't need to know about the existance of backpacks

graceful egret
#

Not sure if this is the right channel, but I am having some issue with Camera Stacking

What I want:

  • The whole game to be rendered with a post processing effect applied to it
  • Some special sprites that get rendered without post processing (World space UI, but I am not using the UI system. I am just using sprites)

It seemed trivial to do so by using camera stacking, but what happens is that the second camera (world space UI) removes the post processing effect from the base layer

Any idea if this is a bug? Or if I am missing some additional setting somewhere?

The expected result should be a yellow-green square with a white circle over the top of it

fervent furnace
#

Then use a tuple to store the action with the grab interactable

graceful egret
#

Unity 2022.3.5f1 btw

sleek bough
#

post processing is a camera space effect, other camera can't affect post processing of the first one

graceful egret
#

So they are separated correctly in what they are rendering

sleek bough
#

make sure post processing layers setup correctly

graceful egret
#

I will recheck those

#

Ok so my PP is on Default Layer
My main camera is set to volume mask default and PP turned on
My overlay camera is set to volume mask world ui and PP turned off

I dont have any PP for the world UI

It seems like the correct setup to me?

#

If I add a world ui PP volume then it renders both layers with that PP resulting in both layers being blue

One should be yellow and the other blue

sleek bough
dawn nebula
#

I mean it's kind of code related, no?

sleek bough
graceful egret
#

Oh yeah I did not realise there was a channel for this
Thank you

lethal vigil
graceful egret
#

I was able to fix my problem

By setting Stop NaNs on the base camera to true, it magically works lol

In my case I don't intend to have a separate PP effect on the UI layer so its completely acceptable
For people who do want that this won't work for them as any PP on the top layer will also apply to the lower layer too

winter charm
#

I've been working on Interaction Controller and I found myself confused. Is this a good approach to handling interactions? There is base abstract Interactable class that, currently has Activatable and Collectable. I am handling this through **raycast **like this. Is this the best approach I could use in my scenario?

#

Every other way that I tried made confusion. So if someone can help me with forming better structure, I would be really thankful.

rough scaffold
#

bro what. this honestly doesnt make sense, even AI is saying something is wrong

#

if im using else

#

does that not complete it???

lean sail
rough scaffold
#

its code bra

#

wtvr just help me and ill never do it again

chilly surge
#

Your "1" and "2" branches don't return anything.

spring flame
#

btw, have you even tried googling this, or are you using Discord in place of a search engine???

rough scaffold
#

it is, but they respond with "Console.WriteLine is not a c# line its a java line ๐Ÿค“ "

#

so sorry again

spring flame
#

in C# to return a value you must use return <something>. Contrary to some other programming languages (idk, python?), the return must be explicit.

lean sail
# winter charm I've been working on **Interaction Controller** and I found myself confused. Is ...

Best approach is kinda debatable here. If this works for your use case then carry on. I'm not a major fan of needing to check for every single derived type especially if this grows larger. It kinda takes away from the whole point of interfaces although I see why you use it here.
It could be nicer if the classes just implement methods which happen on interaction, which is really what this interface implies. Then suddenly you wouldnt need to cast for each derived class, and this code wouldnt need to change everytime you have a new interaction.

rough scaffold
#

ok it worked @chilly surge the bob tabor c# beginners guide has the code exactly like mine, must be a c# update or something idfk

lean sail
rough scaffold
#

i want to be mean to you, but i need this discord for help

fervent furnace
#

!cs

rough scaffold
#

so im just gonna say ok and be quiet

lean sail
#

Bot isnt working rn and we cant link discord cause its blocked

fervent furnace
#

oh i see

rough scaffold
#

also isnt c# the main language of unity?

#

maybe im tripping byt

winter charm
lean sail
rough scaffold
#

ok bawsi ur right im wrong

lean sail
winter charm
lean sail
#

Maybe someone else has a better method for this, im about to sleep though so brain not working

#

I'm not entirely sure what that means also, I dont use mirror

spring flame
#

Is it good to put ScriptableObjects inside Resources folder?

chilly surge
#

IInteractable could expose an Interact method which takes in a transform. If the item doesn't care about the transform it's fine to just ignore it.

winter charm
#

I have a prefab player, and I can't just extract hand from it, and put it as a reference in the inspector. It's an error. I had a really good structure without applying mutliplayer.

winter charm
chilly surge
#

Why not?

winter charm
#

There is a lot of overriding being done.

#

Later on this would just become a mess.

chilly surge
#

I might be missing some context, why would IInteractable having a method requires overriding?

winter charm
#

Wait

#

It doesn't.

lean sail
#

In your case yea I'd even opt for what Burrito is saying. Interfaces usually will result in some empty methods/unused parameters which people say isnt clean but ๐Ÿคทโ€โ™‚๏ธ who cares

winter charm
astral nexus
#

when I set this field (pic 1) by other script and it's not null - throws me this error Fields with [SerializeReference] cannot serialize objects that derive from Unity.Object
but it still serializes it in inspector (pic 2) and working fine, only throwing constantly this error in console on field set and that's all
am I doing something wrong with it? also, serialization result looks strange with this drop down for a type, lol

steady moat
astral nexus
steady moat
#

Strange, from what I nkow it should not work.

#

Anyway, you should not use this pattern and ignore Unity warning because you are going to be bitten in the ass at one point or another.

#

Probably something else is happening which "make it works".

#

SerializeReference are used for embeded C# object, not scene reference.

astral nexus
#

hm, got it, thanks!

heady iris
#

i know it provides an inspector UI for [SerializeReference]

#

although it still should not appear in this case, since the field isn't serialized

#

maybe it'd appear if your inspector was in Debug mode

#

but I'd expect the inspector to look a bit different in that case

astral nexus
heady iris
#

Ah, that might be it

#

Although I'm still surprised it's serialized at all.

#

Unity does secretly serialize private fields that aren't explicitly marked with System.NonSerialized

#

so that they can be shown in debug mode

#

Perhaps TriInspector is picking up on that and displaying it, even though it shouldn't be included in the inspector

#

You can test this by adding [System.NonSerialized] to the field

magic vine
#

Hey, i wanted to ask if anyone could help me with some issues regarding TextMeshPro on android

for some reason I canยดt enter any . or , when im typing something into the field (see the video above)
i set the content type to "decimal number", but it doesnยดt register when im typing them on android (it works fine in the unity play mode on my pc)

heady iris
astral nexus
heady iris
#

Json.NET doesn't do anything to Unity on its own

#

(it's not aware of unity at all)

astral nexus
#

yeah, I mean its serializing through it

gaunt holly
#

Hey, I've a problem with my PlayerController if anyone know why ?The player walk in front of him alone and the movement controller doesn't work correctly.. Thanks you

public class PlayerController : MonoBehaviour
{
    private CharacterController controller;
    private Vector3 playerVelocity;
    private bool groundedPlayer;
    private float playerSpeed = 2.0f;
    private float jumpHeight = 1.0f;
    private float gravityValue = -9.81f;

    private void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        groundedPlayer = controller.isGrounded;
        if (groundedPlayer && playerVelocity.y < 0)
        {
            playerVelocity.y = 0f;
        } 

        Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        controller.Move(move * Time.deltaTime * playerSpeed);

        if (move != Vector3.zero)
        {
            gameObject.transform.forward = move;
        }

        // Changes the height position of the player..
        if (Input.GetButtonDown("Jump") && groundedPlayer)
        {
            playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
        }

        playerVelocity.y += gravityValue * Time.deltaTime;
        controller.Move(playerVelocity * Time.deltaTime);
    }
}

#

ping me please

#

I feel like it's so complicated to manage PlayerController and MouseController script ..

valid relic
#

Has anyone got SpriteShapeSegment.spriteIndex setter to actually do anything in a SpriteShapeGeometryModifier? It seems that modifiying the sprite index (inside a job) does not change the sprite that is actually rendered to the screen.

relevant code is
IJob:

    public void Execute()
    {
        for (int i = 0; i < segmentLengths.Length; i++)
        {
            int chosenSpriteIdx = FindLeastStretchedSpriteIndex(i);
            for (int j = 0; j < submeshesPerSegment; j++)
            {
                SpriteShapeSegment submesh = submeshes[i*submeshesPerSegment + j];
                submesh.spriteIndex = chosenSpriteIdx;
                submeshes[i*submeshesPerSegment + j] = submesh;
                Debug.Log($"submesh {i*submeshesPerSegment + j} sprite index set to {chosenSpriteIdx}");
            }
        }
    }

MakeModifierJob:

        StretchMinimisingJob job = new()
        {
            submeshes = submeshes,
            segmentLengths = segmentLengths,
            spriteLengths = spriteLengths,
            submeshesPerSegment = submeshesPerSplineSegment
        };
        JobHandle jobHandle = job.Schedule(generator);
        
        //dispose of NativeArrays after job is complete
        JobHandle disposeHandle = JobHandle.CombineDependencies(jobHandle, segmentLengths.Dispose(jobHandle));
        disposeHandle = JobHandle.CombineDependencies(disposeHandle, spriteLengths.Dispose(jobHandle));
        
        return disposeHandle;
#

What this is supposed to do is make each segment of the spline use the sprite variant that results in the least distortion. But even if I force each SpriteShapeSegment to use spriteIndex 0, nothing happens and it keeps using whichever one was manually defined in the editor.

valid relic
#

Actually I realise now that I can modify the spline's sprite variant directly without using geometry modifiers and jobs, so now the question becomes how do I detect when the spline has been changed? I don't see any callbacks, will I have to do it through OnValidate in a component that inherits from SpriteShapeController?

solemn raven
#

hi
jumpingForce = Vector3.SmoothDamp(jumpingForce, Vector3.zero, ref jumpingForceVelocity, JumpingFalloff);
the code above runs on update.
if I change the value of jumpingForceVelocity on the inspector to something like 1 or 0.1
it keeps going down close to zero then snapes to something like -7 then dumps down to zero then snaps again and again
what is going on ?

valid relic
heady iris
#

To configure how quickly SmoothDamp approaches the target value, you adjust the fourth argument -- the smoothTime

valid relic
#

SmoothDamp(value to be moved towards target, target value, ref current rate of change, estimated damping duration)

astral nexus
#

I'm trying to make an Item system with modular Effects on each item (like "add health", "remove speed", etc.)
I'm storing Item stats as JSON, but can't figure out how to add Effect definition to this stuff properly

My first thought was to make just a special key-value pair inside JSON as a list named "effects" with strings for type names I've made as an Effect class and just create them as plain C# objects at initialization for each item with Activator and cache it in ScriptableObject "database", but I barely think this is the right way of doing it, lol.
And other way I'm thinking of is: ditch JSON, make ScriptableObject for each item and then create each item effect as ScriptableObject too that can be referenced in each item. But, I need to pass a player/npc in it and cast to proper interface each time I use an item, because I can't cache my casted user object in EffectSO or ItemSO, because it's scene objects and will be shared between items.

So, how to do it more properly? Or can someone point me to right direction for implementing this system?

solemn raven
#

like if he is moving forward then hit jump , he stops and only jumps upward, strictly upward not adding the jumping force to the current movement

valid relic
# astral nexus I'm trying to make an Item system with modular Effects on each item (like "add h...

Using SOs is much easier than trying to do it with JSON so that's a good idea. Your code structure is flawed if your item/effect templates need reference to scene objects, the templates should not know about the scene and instead you'd prob want something like an item instance monobehaviour which gets any necessary references during runtime. Also the casting to interface is a red flag in this situation, using an item should go something like entity.heldItem.Use(entity, target)

astral nexus
# valid relic Using SOs is much easier than trying to do it with JSON so that's a good idea. Y...

Yeah, I'm leaning towards SO for this, but still there are problem with passing users and their type:
Item effects will need user and target reference that are passed through some method (I'm obviously not caching scene objects inside SOs, my wording in that post was bad, sorry), so there are will be needed a cast from an object type argument to some common interface of an item effect that supports it, so anyone can use an item with effect if they implement an interface
Main problem is I can't do it without casting, so my item effects inside item is share base class EffectBase or smth like this, so they can be stored inside an Item SO. I want my items and item effects to be generic, but I dunno how to do it for caching item effects inside item without casting it or target user when use it, lol.

stable lintel
#

can i get several terrains, convert them to meshes with heightmaps and textures, combine them to a single mesh and use as entire world's LOD?

latent latch
#

probably

stable lintel
#

well, i can definitely take heightMap

latent latch
#

alphamap textures for the texture then refer to their width and heigth for splatmapping

stable lintel
#

what is splatmapping

#

and can i do this all at runtime

latent latch
#

terrain blends textures together

stable lintel
#

and it's called a splatmap

latent latch
#

it's all in the terrain asset so probably

#

I do populate my terrain using the texture masking

#

at runtime that is

heady iris
#

Unity Terrain has two splatmaps with R/G/B/A channels, so you get to use 8 different terrain layers

#

Each channel tells you how much weight a specific terrain layer gets

#

(i think it's normalized)

#

so a red channel value of 1 means that the first terrain layer is displayed

#

green and blue values of 0.5 mean layers 2 and 3 are mixed 50-50

stable lintel
#

is there a way to get splatmap out of terraindata

#

somehow

valid relic
# astral nexus Yeah, I'm leaning towards SO for this, but still there are problem with passing ...

I'm not sure if I fully understand what you mean but if I do, you can have it with generics:

public abstract class ItemEffect<T1, T2> : ScriptableObject where T1 : IItemUser where T2 : IItemTarget {
  public bool IsUserValid(IItemUser user) {
    return user instanceof T1;
  }

  public bool IsTargetValid(IItemTarget target) {
    return target instanceof T2;
  }

  public T2 GetTarget(GameObject go) {
    return go.GetComponentInParent<T2>(); //may be null
  }

  public abstract void ApplyEffect(T1 user, T2 target);
}

public interface IHealable : IItemTarget {}
public class Player : MonoBehaviour, IItemUser, IHealable {} //can use items, be targetted, and be healed
public class Enemy : MonoBehaviour, IItemUser, IHealable {} //same as player
public class NPC : MonoBehaviour, IItemTarget {} //cannot use items, cannot be healed
public class AreaOfEffect : MonoBehaviour, IItemUser {} //cannot be targeted, but can use items

//subclass example, you need this to make SOs with defined generic
public class HealingEffect : ItemEffect<IItemUser, IHealable> {...}

//naming: effect(user)(target) where X = any, P = player, E = enemy
ItemEffect<IItemUser, IItemTarget> effectXX = new(...);
ItemEffect<Player, IItemTarget> effectPX = new(...);
ItemEffect<Enemy, IItemTarget> effectEX = new(...);
ItemEffect<IItemUser, Player> effectXP = new(...);
ItemEffect<IItemUser, Enemy> effectXE = new(...);
ItemEffect<Player, Player> effectPP = new(...);
ItemEffect<Enemy, Enemy> effectEE = new(...);
HealingEffect effectHealing = new(...);
latent latch
heady iris
#

yeah -- that's a single-channel texture

#

I wonder if the splatmaps are stored as eight separate one-channel textures internally

#

I just know that they're presented to the shader as two four-channel textures

latent latch
astral nexus
valid relic
winged hare
#

Hey, I'm trying to make my game playable on pc (keyboard) and mobile, so I set UI buttons with an On-Screen Button script. Only problem is I don't know which control path I'm supposed to use (and the keyboard and dpad options don't end up working).

stable lintel
#

Then i somehow build up a texture

latent latch
#

it gives you the weight of the position

stable lintel
#

and then i apply it to mesh i generated out of terrains heightmap?

latent latch
#

so you apply the texture now of those coordinates with the weighted value blended with the other textures

stable lintel
#

maybe i don't get smth, but why do i need to blend my map with other textures, if generated mesh has none

latent latch
#

take a brush and use two textures in the same spot on the terrain with 50% strength

stable lintel
#

oh you mean it's a step before getting the resulted map

valid relic
stable lintel
#

but very low-detail

valid relic
#

ahh I see

stable lintel
#

to use it a lod for distant parts of the world

#

so i can get all terains, set pixel error to max amount, convert the thing to mesh, do this for all terrains and then use Mesh.combine

#

and then i also need to apply textures of those terrains to mesh parts

#

so in game it looks like there are terrains, but actially it's like 5k faces(or 50k idk never measured) curved plane

latent latch
#

I wonder why there's a limitation of layers with the terrain

stable lintel
#

is that really a thing i should think about

latent latch
#

hdrp doesnt seem to have that limitation though

stable lintel
#

hdrp is too hard

#

and also my grass shader doesn't work with it XD

latent latch
#

oh huh open gl also has a limitation of 4-8 textures

heady iris
errant flame
#

Hey, I am trying to draw a field that cannot be drawn in the data structure in inspector.

Do I need to draw all the remaining fields manually just to do this?
I just want them to stay the same.

At the same time, since the serialized data is an object, it uses ISerializationCallbackReceiver, when I create a field with the custom property drawer, does this field I created have an onChange callback or a similar structure because I need to manually control the change.

heady iris
leaden ice
errant flame
#
    [Serializable]
    public class GPNodeData
    {
        public GPNodeType NodeType;
        public string GUID;
        public string NodeTitle;
        public bool Expanded;
        public GPSerializableVector2 Position;
        public string Data;
        public GPConnectionData ConnectionData;
    } 
public class GPSelectorNodeData : GPNodeData, ISerializationCallbackReceiver
{
    public object SelectionValue;
    [SerializeField,HideInInspector] private string _valSerialized;
}
stable lintel
#

does mesh.combine take texture or the mesh only

errant flame
#
        public void OnAfterDeserialize()
        {
            SelectionValue = DeserializeValue(_valSerialized);
        }

        public void OnBeforeSerialize()
        {
            _valSerialized = SerializeValue(SelectionValue);
        }
public static string SerializeValue(object value)
{
    if (value == null)
    {
        return "n";
    }

    var type = value.GetType();

    if (type == typeof(int))
        return "i" + value;
    if (type == typeof(float))
        return "f" + value;
    if (type == typeof(Color))
    {
        Color32 c = (Color)value;
        uint v = (uint)c.r + ((uint)c.g << 8) + ((uint)c.b << 16) + ((uint)c.a << 24);
        return "c" + v;
    }
    if (type == typeof(GPSerializableVector2))
    {
        GPSerializableVector2 v = (GPSerializableVector2)value;
        return "w" + v.x + "|" + v.y;
    }
    if (type == typeof(Vector3))
    {
        Vector3 v = (Vector3)value;
        return "v" + v.x + "|" + v.y + "|" + v.z;
    }
    if (type == typeof(bool))
        return "b" + value;
    if (type == typeof(string))
        return "s" + value;

    throw new ArgumentException("Unsupported value type: " + type);
}
latent latch
stable lintel
#

so texture should be applied to the final mesh

#

the combine result

latent latch
#

two ways you do it, bake the textures or do it by shader

errant flame
#

@leaden ice I am just trying to make that SelectionValue to editable in inspector also trying to make sure there is no error after editing due to serialize,deserialize etc.

leaden ice
#

What's going wrong?

winged hare
heady iris
#

controllers have buttons too :p

winged hare
heady iris
#

show me exactly what you picked

winged hare
heady iris
#

okay, that looks fine

#

that should create a virtual keyboard

#

You can see if it's actually being created by looking at the input debugger

#

I would expect it to show up in this list

errant flame
#

@leaden ice

Reasons why I cannot draw a propert field based on _valSerialized,

I can't get the current value in _valSerialized, I can't find a target like in customInspector.

The only thing I found is serializedObject and I can't cast it to GPSelectorNode data.

When I draw it and a wrong value is written into it, the things I did in OnSerialization with a method like onChange cannot be applied and the data there is corrupted and serialization errors come.

At the same time, I can't open an extra field just for this field, I need to make all the fields of GPNodeData and when I add something, it doesn't look like the old first version.

winged hare
#

looks pretty much the same (unsupported is just the extra buttons on my mouse)

#

and other usbs

stable lintel
#

i found this thing, but sadly no screenshots xD

gray mural
#

Could someone tell me their opinion on using switch on Vectors this way? Does if look more appropriate to you?

private void SetTorsoEdge(int index, Vector2Int direction) => 
    SetTorsoTile(index, (direction.x, direction.y) switch
{
    (0, 1) => playerBody.torso.tileEdgeUp,
    (0, -1) => playerBody.torso.tileEdgeDown,
    (1, 0) => playerBody.torso.tileEdgeRight,
    (-1, 0) => playerBody.torso.tileEdgeLeft,
    _ => throw new()
});
leaden ice
#

It's fine - you could also use Vector2Int.up etc to make it more clear semantically

gray mural
#

That's why I'm asking whether converting it into a tuple looks fine

leaden ice
#

Admittedly I don't use pattern matching switches that much so I may be mistaken

gray mural
# leaden ice you're using pattern matching so it shouldn't matter, no?

Using a non-constant value in a switch throws me an error. Surely, I would like to do it this way

private void SetTorsoEdge(int index, Vector2Int direction) =>
    SetTorsoTile(index, direction switch
{
    Vector2Int.up => playerBody.torso.tileEdgeUp,
    Vector2Int.down => playerBody.torso.tileEdgeDown,
    Vector2Int.right => playerBody.torso.tileEdgeRight,
    Vector2Int.left => playerBody.torso.tileEdgeLeft,
    _ => throw new()
});
latent latch
#

you got two params there

gray mural
#

But this is a problem in switches

chilly surge
#

Yeah pattern matching unfortunately require compile time constants.

latent latch
#

or maybe im reading this wrong.

leaden ice
#

Ok I guess I was mistaken about pattern matching switches

latent latch
#

Could do an enum, no?

gray mural
latent latch
#

like enum dict that maps to the value

#

kinda how I do it with my voxel map

gray mural
#
private static Vector2Int GetValue(this MyEnum myEnum) => myEnum switch
{
    // ...
};
latent latch
#

It's up to preference. Switch is probably more performant if you care for it considering the amount of entries.

#

I've a habit of mapping everything though.

late lion
#

Looks like a perfect use case for a look up table!

#

An array with the precomputed values and using the enum as an index.

left adder
#

Question,

Is it possible to call a script & gameobject in a clone of a prefab?
When my players spawn, they have a player prfab clone with the playerManager script attached,
Altho, i want to call a game object & script out of my scene, but if i use

public GameObject ObjectName

I cant assign it to the prefab, is there a way to do this ?

#

i also tried this:

    public void Awake(){
        GameObject.Find("ChatManager");
        chatManager = chatManagerGameObject.GetComponent<PhotonChatManager>();
    }

Seems not the be the way

simple egret
#

Also avoid posting the same question in multiple channels at the same time.

left adder
# simple egret `Find()` returns a value, you're not storing it in a variable. `chatManagerObjec...

Jep! That did the trick,

private PhotonChatManager chatManager;
    private GameObject chatManagerGameObject;

    public void Awake(){
        chatManagerGameObject = GameObject.Find("ChatManager");
        chatManager = chatManagerGameObject.GetComponent<PhotonChatManager>();
    }

    [PunRPC]
    public void SetNickname(string _name){
        nickname = _name;
        chatManager.nickname1Text.text = nickname;
        chatManager.nickname1GameObject.SetActive(true);
    }
left adder
#

never worked with calling prefabs / scripts in prefabs, was just a little hyped haha!

main crystal
#

the red border "highlight switches at the bottom whe i switch in play scene

leaden ice
#

what are they made of?

#

And what does this have to do with code?

main crystal
#

those are images

sonic swan
#

I wanto find the vector 3 back of an object how do I do that

leaden ice
#

You mean the backwards direction for that object?

sonic swan
#

Yea

leaden ice
#

-theObject.transform.forward

sonic swan
#

Pretty much

leaden ice
#

Or to illustrate the point possibly better:
theObject.transform.TransformDirection(Vector3.back)

sonic swan
#

Wait

#

1 sec

#

Nope doesn't work

leaden ice
#

it works

#

you're doing something wrong

#

explain what you're trying to do, show your code, screenshots, etc.

sonic swan
#

Ok so im making a casing of bullets that fire so I instantiate them then apply a force to their rb. The direction is meant to be the backside of the spawner(intatiater obj)

leaden ice
sonic swan
#

Did that

#

Exactly

leaden ice
#

then you did something wrong

sonic swan
#

I'll send a ss

leaden ice
#

your spawner is not oriented how you think, or maybe the things are colliding with something

#

etc

leaden ice
sonic swan
leaden ice
#

your reference is incorrect for example

#

again please show your code, screenshots, etc.

sonic swan
#

Discord is being funny on my pc so I'll just send a pic from mu phone

leaden ice
#

Shouldn't it be firepoint?

sonic swan
#

Point is the spawner

leaden ice
#

why are there two different things

#

Also this is not what I said. to do

#

you wrote point.transform.position

#

that is not what I wrote

sonic swan
#

I named it weirdly but point is the orientation and firepoint is position

leaden ice
#

please copy the example correctly

leaden ice
#

And this

#

Why are there threee different objects here

sonic swan
#

Ok let me explain

#

I have a 3rd person character that rotates according to the carma

#

Now in this player there is two points for instantiating objects

leaden ice
#

Actually 4 diffferent objects lol

#

firepoint
firepointss
firepointsss
point

sonic swan
#

Fire pointsss and firepointss are the two spawn points

leaden ice
#

Your variable naming is absolutely painful

sonic swan
#

Ik it's just placeholders I clean up later

leaden ice
#

It's already causing you problems

#

clean it up now

#

to fix your code

sonic swan
#

Point is the player orientation

spring creek
#

Generally you should clean it up before asking for help from others, because it makes it extremely difficult to parse

leaden ice
#

because you claimed you followed my example and it didn't work, and it turned out you didn't follow the example at all

sonic swan
#

Okso what is your example

leaden ice
sonic swan
#

I wanto apply the force to the rb backward to its relative position

#

Nvm I got it

#

I was being silly

leaden ice
#

yeah, you weren't following the example

sonic swan
#

I didnt read your messgwe correctly

stable lintel
#

code is cool at least

#

for generating mesh

gilded crag
#

Im Having an issue. With a Trigger collider of a game object with a certain tag. not returning in the player script. Anyone who could give me a hand?
Heres my code:

#
 using System.Collections.Generic;
 using UnityEngine;

public class Player : MonoBehaviour
{

    
    
    public GameObject LootBox;
    public GameObject BoxMenu;
    

    

    

    void Start()
    {
        if (LootBox == null)
        {
            LootBox = GameObject.FindWithTag("BoxCenter");
            Debug.Log("LootBox set to GameObject with tag (BoxCenter) ");
            Debug.Log("GameObject: " + LootBox.name);
            
        }
    }

    void OnTriggerEnter(Collider other)
    {
        
        Debug.Log("Collision Entered");

        if (other.gameObject.tag == "BoxCenter" && Input.GetKey(KeyCode.E))
        {

            Debug.Log("Opened Loot Box!");
            BoxMenu.SetActive(true);

        }
    }
latent latch
#

OnTriggerEnter is a single frame, so you are expecting to be pressing E when you enter

gilded crag
#

okay

#

so how do i fix it

latent latch
#

Try OnTriggerStay

gilded crag
#

the problem is. the debug.log isn't printing anything

spring creek
latent latch
#

The one before the if statement?

gilded crag
latent latch
#

Alright, then refer above my post ;p

#

still, may want to change that to OnTriggerStay though

gilded crag
#

i did

#

lets try

#

nope

#

nothin

ruby estuary
#

Just before going further, it's it a 3d or 2d game?

gilded crag
#

is it a problem that the game object with the player collider is a child of the actual player game object with the script?

lost night
#

Hey, I am currently having an issue with the OnTriggerExit2D and OnTriggerStay2D functions:
My game has an building system wich is why blocks can get destroyed. If these blocks have an trigger, the on trigger exit function calls, wich would not be a problem if not the on trigger stay function would stop being called. My current workaround is to execute the following code at the end of the on trigger exit function:

transform.position = transform.position + new Vector3(0, 1, 0);
transform.position = transform.position - new Vector3(0, 1, 0);

Is there an better workaround or a fix?

ruby estuary
#

And are you using other layers that are not the default?

gilded crag
#

dont thinks so

#

wait

#

do you mean me or him?

ruby estuary
latent latch
#

both objects need a collider, one or both colliders need to have IsTrigger selected, and one or both need to be rigidbodies

ruby estuary
ruby estuary
gilded crag
#

the blue one is the one with the "is trigger"

#

The blue one is the one with collider

#

and Player has the script

ruby estuary
#

If you make them touch what happens?

gilded crag
#

Heres the "Box mesh"

#

(second colider is the big one)

gilded crag
#

it doesnt even print the "Debug.Log" i added

#

so something is wrong

ruby estuary
gilded crag
#

yep

ruby estuary
#

No wonder

#

When the trigger, triggers something

gilded crag
#

oh

ruby estuary
#

It calls the "ontrigger" methods on the parent or gameobject that has the rigidbody

#

In this case the body, but the body doesn't have the script aka nothing is called

#

Change either the gameobject in which script is or the same but for the rigidbody

gilded crag
#

It works!

ruby estuary
gilded crag
#

||(A goofy character in the game)||

orchid gust
#

Hi guys, I am looking to send an instruction from one object to another using a string and some parameters, what i want the second object to do is call a function with the same name as the string and fill in the parameters, is coroutine my best bet or should something else be used instead

ruby estuary
gilded crag
#

i realised

#

that what happenes in the if statment can be done wether im in the trigger collider or outside

#

the collision doesnt matter

ruby estuary
#

Huh

gilded crag
#

i don't have to be in the trigger area and click E to open the menu

#

i can JUST click E to open it

gray mural
gilded crag
ruby estuary
ruby estuary
#

Yeah ok that shouldn't be happening right? @gilded crag

gilded crag
#

nope

#

Just to make sure

gray mural
gilded crag
# gilded crag Just to make sure

Heres my code ```
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{

public float Speed = 1f;
public GameObject LilDevl;
public GameObject LootBox;
public GameObject BoxMenu;
public GameObject ShopMenu;





void Start()
{
    if (LootBox == null)
    {
        LootBox = GameObject.FindWithTag("BoxCenter");
        Debug.Log("LootBox set to GameObject with tag (BoxCenter) ");
        Debug.Log("GameObject: " + LootBox.name);
        
    }
}

void OnTriggerStay(Collider other)
{
    
    Debug.Log("Collision Entered");

    if (other.gameObject.tag == "BoxCenter" && Input.GetKey(KeyCode.E))
    {

        Debug.Log("Opened Loot Box!");
        BoxMenu.SetActive(true);

    }
} ```
gilded crag
gray mural
gilded crag
#

not only

#

you see the if?

ruby estuary
# gilded crag

It's hard too read the console, there's too many logs click the collapse button

gray mural
gilded crag
#

to make it so. that when im in that big trigger collider. AND i press E that menu opens

ruby estuary
#

I recommend this
Use a variable to manage if inside the trigger

#

And check for input in the update method

#

Aka (I'm on phone so beware):

bool inBoxRange;
Update(){
if(inBoxRange && Input.E) { openMenu();
}

OnTriggerEnter(){
if(collider is box) inBoxRange=true;
}

gilded crag
#

So like..

#

This?

#

wait

ruby estuary
gilded crag
# ruby estuary I recommend this Use a variable to manage if inside the trigger
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour

{

    public float Speed = 1f;
    public GameObject LilDevl;
    public GameObject LootBox;
    public GameObject BoxMenu;
    public GameObject ShopMenu;

    private bool InsideTrigger = false;

    

    

    void Start()
    {
        if (LootBox == null)
        {
            LootBox = GameObject.FindWithTag("BoxCenter");
            Debug.Log("LootBox set to GameObject with tag (BoxCenter) ");
            Debug.Log("GameObject: " + LootBox.name);
            
        }
    }

    void OnTriggerEnter(Collider other)
    {
        
        Debug.Log("Collision Entered");
        InsideTrigger = true;

        
    }

    void Update()
    {

        float Horizontal = Input.GetAxis("Horizontal");
        float Vertical = Input.GetAxis("Vertical");

        transform.position += new Vector3(Horizontal, 0, Vertical) * Speed * Time.deltaTime;

        LilDevl.transform.localEulerAngles += new Vector3(0, 0.3f, 0);




        //if (Vector3.Distance(LootBox.transform.position, transform.position) < 5 && Input.GetKeyDown(KeyCode.E)) 
        //{
        //    Debug.Log("Opened Loot Box!");
        //    BoxMenu.SetActive(true);
        //}

        if (InsideTrigger && Input.GetKey(KeyCode.E))
        {

            Debug.Log("Opened Loot Box!");
            BoxMenu.SetActive(true);

        }

    } 
}


ruby estuary
#

Now add ontriggerexit to set inside Trigger to false

gray mural
gilded crag
ruby estuary
gray mural
gilded crag
#

Works perfectly