#archived-code-general

1 messages · Page 188 of 1

wanton wasp
#

Plain old c# object
Just a c# class

mystic ferry
#

poco
plain old C# ...? lol

marble halo
#

ah i never heard that term before

mystic ferry
#
public class InventorySystem
{
    private Item[,] _inventoryItems;
    private int _width, _height;

    public InventorySystem(int inventoryWidth, int inventoryHeight)
    {
        _inventoryItems = new Item[inventoryWidth, inventoryHeight];
        _width = inventoryWidth;
        _height = inventoryHeight;
    }

    public bool TryAddItem(Item item)
    {
        for (int i = 0; i < _inventoryItems.GetLength(0); i++)
        {
            for (int j = 0; j < _inventoryItems.GetLength(1); j++)
            {
                if (_inventoryItems[i, j]._amount == 0)
                {
                    _inventoryItems[i, j] = item;
                    return true;
                }

                if (_inventoryItems[i, j]._amount < _inventoryItems[i, j]._maxAmount)
                {
                    _inventoryItems[i, j]._amount++;
                    return true;
                }
            }
        }
        return false;
    }
#

working on an inventory system, currently I have this underlying data structure / helper methods class that I initialize inside a monobehaviour, and that MB also has a second multidimensional array to bind the data to an ingame inventory UI which has a grid layout group of "cells" for each inventory space. I'm not sure how I can get references to each inventory cell in a deterministic way so each cell correponds to the i and j values of the multidimensional array. My first thought was to use an empty component but I'm not really sure how to make that work. How do you guys deal with this problem?

#

GetComponentsInChildren uses a DFS algo right?

steady moat
#
public class UIInventorySlot : MonoBehavior {
  [SerializedField] private int slot = -1;

  public void Initialize(InventorySystem inventory)
  {
    inventory.GetSlot(slot);
  }
}

#

Also, I do not think you should use a multidimension array for your inventory.

#

This is only a concern of UI.

wispy raptor
#

i have an issue trying to serialize a generic class:

[Serializable]
public class IntProp : TranslationProperty<int>
{
}
[Serializable]
public abstract class TranslationProperty<T> : TranslationProperty
{
    [field: SerializeField]
    public T Value { get; set; }
    ...
}
[Serializable]
public abstract class TranslationProperty : ScriptableObject
{
    [field: SerializeField]
    public string Name { get; protected set; }
    ...
}

I dont know why it is failing, i created a test using a IntProp and the serialization fails.

#
public class TestTranslation : MonoBehaviour
{
    public IntProp prop;
}
#

when i set the value, the value is reset when i press play button

#

i tried removing abstract but doesn't work

earnest gyro
#

Help with UI Sliders

brittle sparrow
#

not sure if this belongs in code-general but, a long time ago i noticed that my game is super laggy for the first few frames, probably because everything is loading, and the framerate is unstable. So I implemented this method where I wait a few frames until everything is stable and then run everything game related, and I still use it to this day. Is there a better method? This is out of pure curiosity and not urgent, but it also sprung to me that my constant value of 10 frames might not apply in every situation.

wanton wasp
brittle sparrow
#

oh right

#

a loading screen

#

genius!

#

thank you R1nge!!

broken gazelle
#

Hello every one.

#

Culd anyone help me?

#

I want to integrate stockfish api to unity and build it to android platform.

#

How can i do it?

#

Please help me if you have experience with it.

wispy raptor
#

you mean the chess engine?

steep ermine
#

Hi, I want to add multiplayer to my game, I searched the internet but couldn't find an example which has a separate client + server for netcode. Can I have both code in same project and somehow build the server separately as a dedicated server built?

#

I don't want the serverside code into my client build.

broken gazelle
weary bloom
#

Hi im trying to pick up an AI that moves using the navmesh in vr. for some reason i cant pick it up with a collider attached as it just wont lift off the floor (assuming its cus the ai doesnt see it as moving land) so i have a code to turn the navmesh off and collider on when a trigger collider is triggered, but when it activated, the ai just falls through the floor

rigid island
weary bloom
robust dome
#

yield return new WaitForSeconds(value); but inside a Coroutine

#

inside the OnTrigger you call your Coroutine then

weary bloom
#

alr ill give it a try

broken gazelle
wispy raptor
#

not really

scarlet kindle
#

using a coroutine with a for loop and "yield return new WaitForSeconds(1.5f)" end of loop works for me, but I am getting some odd delay and the time seems off with inconsistent wait times... any idea why the time delay might be inconsistent?

I also tried WaitForSecondsRealtime with the same inconsistency

weary bloom
robust dome
#

show you new code

weary bloom
#

thats where i put it

#

my only other thought is turning gravity off on the ridgidbody attached to it while the trigger is activated, just so it doesnt fall

robust dome
#

but before you had it in OnTriggerExit

wise sapphire
#

Hey I wanna start developing a multiplayer mobile shooter, and I also wanna learn dots. Is that a good use of ecs and dots In general

steady moat
weary bloom
#

ohhh that

#

i messed up codin it

#

wasnt acc ment to b there

#

sorry

#

It originally looked like this

steady moat
steep ermine
scarlet kindle
hard viper
#

I think I finally solved my one-way collision issues

#

the trick is:

  1. Need tilemap with it's own gameobject so all semisolids of that 1-way are combined.
  2. Make tile hitboxes thin, with edges terminating in a point.
  3. CompositeCollider2D with POLYGON mode
  4. PlatformEffector2D with one way on, and one way grouping OFF
steady moat
devout solstice
#

So you can have a keycode variable in the inspector, and you can select what key you want that variable to be set to, is there something like that but for xr controls

devout solstice
#

ah my fault

wild bane
#

I have a code where I'm constantly changing my enemies and player character controller radius. If I do that when characters are already intersecting, they will go thru each other as if collision was disabled. What could I do to fix that?

leaden ice
wild bane
lean sail
leaden ice
#

no

#

of course not

#

how would CCD predict your intention to rescale the object?

wild bane
leaden ice
#

It only knows about normal Rigidbody velocity based motion

wild bane
#

In my specific case, I do have to resize character radius anyway

#

But what I don't get is why object acts as if there is no character controller collider at all, only by a small change in one of the objects radius

#

But I never had such scenario where I have two colliding character controllers changing their radius

#

I know changing a single character controller radius while trying to collide against non character controller colliders works just fine

#

Something like that invalidates the player x enemy collision and I can proceed to pass thru the enemies

latent oak
#

When I am Despawning an In-Scene network objects I keep getting this error SpawnStateException: Object is not spawned Unity.Netcode.NetworkSpawnManager.DespawnObject (Unity.Netcode.NetworkObject networkObject, System.Boolean destroyObject) how do I stop this error even though its working properly

wild bane
#

Just o answer my own question here: looks like by adding a Capsule Collider at the same Game Object as the Character Controller and setting both radius to the same value prevents the two Character Controllers to go thru each other when the radius changes

#

Sounds like overkill having two colliders per character only to do that, but it works...

lean sail
raw scroll
#

hello!!! i'm not sure what the error would fall under but i'm trying to run some old simulations a colleague made and I am getting the error of "Microsoft Visual C++ Runtime Library: This Application has requested the Runtime to terminate it in an unusual way" whenever I click run

#

and then it instantly crashes

#

Would anybody have any idea what error this could possibly be related to? Thanks!

stark sun
#

I can slide only one enemy at a time

hard viper
#

is there a good way to add a distorting effect or something to a spriterenderer? I have some fluids (like water layer) but they don't look very fluid

crystal birch
#

Idk much about how but i know its fairly easy thru the use of shaders

stark sun
#

can someone take a look at my thread

viscid kite
#
using UnityEngine;
using UnityEditor;
 
[CustomPropertyDrawer (typeof(NamedArrayAttribute))]public class NamedArrayDrawer : PropertyDrawer
{
    public override void OnGUI(Rect rect, SerializedProperty property, GUIContent label)
    {
        try {
            int pos = int.Parse(property.propertyPath.Split('[', ']')[1]);
            Debug.Log("Calling in namedArray: "+property.floatValue);
            string fieldName = ((NamedArrayAttribute)attribute).names[pos];
            EditorGUI.FloatField(rect, fieldName, property.floatValue,EditorStyles.numberField);
        } catch {
            EditorGUI.FloatField(rect, property.floatValue, EditorStyles.numberField);
        }
    }
}

For this code, how do I allow for values inputted into the editor to stay there?

heady iris
#

It returns the new float value.

viscid kite
#

ah

#

so where do i store it?

#

do i store it in the property variable?

#

seems like the answer is yes

rigid island
#

!collab

tawny elkBOT
fathom parrot
#

Ah I didn’t see those I’ll post there thanks

green radish
#

does the "Runtime" folder make files inside load at runtime?

dense estuary
#

I made a tree spawner and for a reason I can't figure out, the trees are spawning at weird positions. basically the script spawns a tree at a random position within a range, and shoots a raycast down to snap the tree to the ground, but for some reason the trees are only spawning near water. I have a LayerMask, so the trees can only collide with the land. Here is my script: https://hastebin.com/share/rivinonube.csharp.

#

Getting rid of the layer mask causes the trees to only spawn at a fixed y-coordinate.

#

is it because im using a mesh collider?

dusky dune
#

I am trying to access the button of my prefab when I instantiate it, I cant do in the scene view of the game so I need to do it via script but when I click on the button is does nothing it doesnt even change colour when I hover over it for some reason

desert shard
#

is their initial elevation too short that they are spawning inside the terrain?

#

so it can only hit the water. (because it's lower )

somber nacelle
dusky dune
somber nacelle
#

you sure about that?

#

if you did, your button should be working just fine. unless you've got a world space canvas and haven't assigned the camera to it

dusky dune
#

oh actually it has an error that I can fix

cosmic rain
dusky dune
somber nacelle
#

so the button is still not reacting at all to the mouse?

dusky dune
dusky dune
# cosmic rain Where do you instantiate it?
    void AddCluesFromNoteBookToInterrogationPanel()
    {
        _InterrogationPanel.SetActive(true);

        var entries = File_Handler.Read_From_JSON<Input_Entry>(fileName);

        for (int x = 0; x < entries.Count; x++)
        {
            Transform parent = GameObject.FindGameObjectWithTag("Interrogation_Clue_Panel").transform;
            new_UI_Button = Instantiate(ui_Interrogation_Clue_Button_Prefab, parent);
            //TMP_Text theText = new_UI_Text_Panel.transform.GetComponent<TMP_Text>();
            ////variable text that accesses the instantiated gameObject
            TMP_Text TheText = new_UI_Button.GetComponentInChildren<TMP_Text>();


            //Sets the text.
            TheText.text = entries[x].Clue_Description;

        }



    }
somber nacelle
#

and by reacting to the mouse, i'm referring to responding to the mouse entering it and visibly clicking. not about the code

somber nacelle
#

i'm no longer going to help you. please do some beginner c# courses to learn how to code

dusky dune
cosmic rain
dusky dune
dusky dune
placid temple
#

i was using the following lines of code to handle serverside logic:

if (!isServer)
    return;

unity ran an update and removed the isServer mechanic. can anyone help on what to change?

do i use the [Server] tag on the function?

dense estuary
somber nacelle
#

it will also depend on what networking package you are using and whether you've inherited from the correct class

desert shard
dusky dune
marble halo
#

For some reason it won't let me attach the "remote bomb" ablility to the current ability script.

desert shard
#

It wants an instance of the class, not the class itself.

somber nacelle
#

do you have an object with that component attached?

marble halo
#

basically think of this system like spells or plasmids in bioshock

somber nacelle
#

well that's why. it's a MonoBehaviour which means it needs to be attached to some gameobject to be a valid instance. and the slot in the inspector is expecting a valid instance

desert shard
#

We know what you're trying to do

marble halo
#

I cant do scriptable objects because that wont work with projectile abilities

desert shard
#

Why wont it

marble halo
#

because i would need the transform of wear the projectile is fired

#

Believe me i tried

cosmic rain
desert shard
#

You wouldnt put the spawnpoint in the SO

#

you'd spawn the projectile at the spawnpoint when you're attempting to fire it

#

so GlassCannon.cs would have a slot for GunDataSO and spawnPoint

#

for an example.

marble halo
#

But also not all abilites use a projectile

#

One i have in mind is a grapple hook

somber nacelle
#

this sounds like a use for the strategy pattern

dense estuary
desert shard
#

Told ya 😎

jaunty needle
#

I'm using OnValidate to call this method but it's giving me these weird errors:

    void DrawTrail()
    {
        ClearTrail();

        for (int i = 0; i < xAxisMax * pointDensity + 1; i++)
        {
            Vector2 pointPos = PositionCalculation(i / pointDensity);
            GameObject spawnedPoint = Instantiate(point, pointPos, Quaternion.identity);
            points.Add(spawnedPoint);
        }

    }

    void ClearTrail()
    {
        if(points.Count > 0)
        {
            for(int i = 0; i < points.Count; i ++)
            {
                Destroy(points[i]);
                
            }

            points.Clear();
        }
    
    }
cosmic rain
jaunty needle
#

I'm facing this problem, I'll send a video

cosmic rain
cosmic rain
#

What you want is probably a script executing/updating in the editor

jaunty needle
#

And doing this for every one is exhausting:

        //Updates the trail if something changes
        if(currentPointdensity != pointDensity)
        {
            DrawTrail();
            currentPointdensity = pointDensity;
        }
cosmic rain
#

You can raise a flag in on validate, but execute the logic in a normal update.

jaunty needle
#

How would I raise a flag

cosmic rain
#

Also you can do the same thing in update too.

cosmic rain
jaunty needle
#

Is there an OffValidate?

#

lol

cosmic rain
#

After you update your graph:
somethingChanged = false

jaunty needle
#

ooh

#

Thank you!

swift falcon
#

string ref. suck!

#

I can't be the only one to think this way, right?

dense estuary
# desert shard Log what it hits, and double check that assumption

Now how can I make it only spawn on the non-water parts of the terrain, the water is a separate gameobject, so I tried giving it a layer, and making two layermasks, one for goodlayer and one for badlayers. these layermasks are added together to make the layers variable and that is used for the raycast, then I tried having it check if the layer it collided with was the terrain layer, and if so it would spawn a tree, but it didnt work. Here is my script: https://hastebin.com/share/yilogozegi.csharp

dense estuary
#

What its doing instead is spawning trees no matter what layer it hit

somber nacelle
#

if (hit.transform.gameObject.layer != goodLayer) this is certainly not doing what you think it is.
if you want to check if a layer is contained in a bit mask you need to do some bitwise math

int layer = 1 << hit.transform.gameObject.layer; //gets a mask containing only this layer
if(layer & goodLayer != 0) //this basically just checks if there is overlap in the two masks
{
  //do your shit here
}
devout harness
#

How are you expected to pass in the array results for Physics2D.OverlapCircle?

#

I.e. what sizing?

#

Do I just allocate an array once with the maximum amount of data I expect to go into it, then iterate up to the size passed back from the method call?

night harness
#

If I have a instance of a Poco class in a dictionary, how can I retrieve it as a reference and not a copy?

cosmic rain
night harness
#

Would having [Serializable] be changing that?

devout harness
cosmic rain
#

What makes you think you get a copy?

night harness
#

That would be me being very stupid 😄

#

all solved, apologies and ty

rain minnow
fervent furnace
#

Overlapcircle will return the length

devout harness
rain minnow
green radish
#

for reasons I dont yet understand this causes any other items in the list to never exist, if the override is left empty the list becomes empty. How might I change this to add things to the method instead of replacing the method?

somber nacelle
#

that doesn't replace the list at all. if something is clearing your list or assigning it to null, it's certainly not that

green radish
#

when this is not done the list works just fine, stuff gets added as normal

somber nacelle
#

again, that does not clear the list. and cannot set whatever list you passed to it to null. so whatever is doing it is somewhere else

#

are you receiving any specific errors?

green radish
#

for clarity, I didnt mean its erasing the contents of the list, the override seems to be stopping any code the method originally had from running, like its running the code I put here but none of the original, which is not what I wanted to do, I want to run the code here in addition to the original

#

when this runs the list never gets filled with other things the original method fills it with

somber nacelle
#

if you want the base method to be called too you need to call base.Setup() in there

green radish
#

like this, right?

somber nacelle
#

depends on the order you want the code to be executed in, but yes.

green radish
#

I want the new code to run before the original since the original, at the end, gets the number of items in the list

somber nacelle
#

then yeah, that's exactly it

worn stirrup
#

Is there some version of RaycastHit2D that will return every object it hits instead of just the first one?

green radish
worn stirrup
#

I'm having issues with it immediately hitting the background currently, but I also want to be able to see all of a pile of objects, then pick the lowest

rain minnow
somber nacelle
rain minnow
worn stirrup
somber nacelle
tawny elkBOT
worn stirrup
#

Yes, I'm there all the time

somber nacelle
#

then look at the Physics2D class

worn stirrup
#

oooo I see, thank you boxfren

green radish
#

I second the thanking

rancid frost
#

this is rather strange, but I am replacing text components in an object with text mesh pro,
but it will work fine for all the text components except the last one.

The last component with remove the default text component, but wont add the tmp counter part, even tho the code (when debugged) shows the added component is not null

#
static void ConvertTextToTextMeshPro(GameObject target)
        {
            if (removeEffectComponents)
            {
                var sha = target.GetComponents<Shadow>();
                foreach (var cmp in sha) Undo.DestroyObjectImmediate(cmp);
                var outl = target.GetComponents<Outline>();
                foreach (var cmp in outl) Undo.DestroyObjectImmediate(cmp);
            }

            Text uiText = target.GetComponent<Text>();
            if (uiText == null) return;


            TextMeshProSettings settings = GetTextMeshProSettings(uiText);

            Undo.RecordObject(target, "Text To TextMeshPro");
            Undo.DestroyObjectImmediate(uiText);

            TextMeshProUGUI tmp = target.AddComponent<TextMeshProUGUI>();
            tmp.enabled = settings.Enabled;
            tmp.font = settings.TMPFont;
            tmp.fontStyle = settings.FontStyle;
            tmp.fontSize = settings.FontSize;
            tmp.fontSizeMin = settings.FontSizeMin;
            tmp.fontSizeMax = settings.FontSizeMax;
            tmp.lineSpacing = settings.LineSpacing;
            tmp.richText = settings.EnableRichText;
            tmp.enableAutoSizing = settings.EnableAutoSizing;
            tmp.alignment = settings.TextAlignmentOptions;
            tmp.enableWordWrapping = settings.WrappingEnabled;
            tmp.overflowMode = settings.TextOverflowModes;
            tmp.text = settings.Text;
            tmp.color = settings.Color;
            tmp.raycastTarget = settings.RayCastTarget;

            Debug.Log(target.name + " converted to TextMeshProUGUI");
        }
#

it says text_1 convert but text 1 is clearly not shown

#

the component is missing...

dusk apex
rancid frost
dusk apex
# rancid frost

So this implies that visually in the scene, the object has a text mesh pro component attached. Can you verify this?

#

At the text_1 break point

rancid frost
rancid frost
#

no

#

at* the breakpooint the component is there

dusk apex
#

So the component was created in scene and visible at the break point

leaden solstice
#

Are you dealing with prefab here?

rancid frost
leaden solstice
#

Probably need to do something like SetDirty

dusk apex
#

Either that or there's another script removing the component

#

Else cathei is likely correct

leaden solstice
#

You can use SetDirty when you want to modify an object without creating an undo entry, but still ensure the change is registered and not lost.

#

Your last change isn’t making Undo entry so

rancid frost
#

so, that prefab has 4 text components, the first 3 get changed just fine, its the last 1 that doesnt get added...

dusk apex
#

After adding a component, there are no undos ever introduced - with the exception of the function being called again.

rancid frost
#

i see

#

this should do the trick?

#

nope

#

I dont get it

#

why isnt this working

dusk apex
rancid frost
#

add component u mean

#

idk

#

just kinda winged it

dusk apex
#
//stuff
Undo...
//stuff
SetDirty...```
rancid frost
#

not working

#

problem still persists

dusk apex
#

Did you call the set dirty command like suggested?

#

After everything

rancid frost
rancid frost
#

did this previouslyt didnt work, letme try agian

dusk apex
rancid frost
#

yea,

#

idk why its doing this

#

it removes the text, but it doesnt addthe component

#

didnt refresh the prefab in video

dusk apex
#

You can use SetDirty when you want to modify an object without creating an undo entry, but still ensure the change is registered and not lost. If the object is part of a Scene, the Scene is marked dirty. If the object may be part of a Prefab instance, you additionally need to call PrefabUtility.RecordPrefabInstancePropertyModifications to ensure a Prefab override is created.

#

Or record the object again at the very end as that automatically calls set dirty as well.

rancid frost
#

ok

dusk apex
#

If you do want to support undo, you should not call SetDirty but rather use Undo.RecordObject prior to making changes to an object, since this will both mark the object as dirty (or the object's Scene if it is part of a Scene) and provide an undo entry in the editor. You should still also call PrefabUtility.RecordPrefabInstancePropertyModifications if the object may be part of a Prefab instance.

rancid frost
#

I straight up dont even care about the undo

#

I just want it to work

#

nope diodnt work

dusk apex
rancid frost
#

thanks for the help

green radish
#

is there any way in Unity's physics engine to make one gameObject have a tugging effect on another?

#

for example, say I freeze a gameObjects position but not rotation, then attach another object to it and give it a velocity in the direction of Transform.right, I want that moving object to spin the stationary one while being restrained from moving away from it

cosmic rain
lean sail
lyric moon
#

hey im trying to install Relay and Multiplayer Samples Utilities but both of these packages scream errors at me???
This is the main one:
"The type or namespace name 'Internal' does not exist in the namespace 'Unity.Services.Core'"
Why is this? Do I have to upgrade? I'm using 2020.3.29f1 LTS

#

CS0234

cosmic rain
lyric moon
#

reopening editor rn

lean sail
lyric moon
#

nah didnt install any samples, just installed the package Relay from unity registry to get the error

#

where can I find the NGO discord btw?

lean sail
lyric moon
#

found the discord, ty
ill check the docs now

#

2020.3 seems fine?

#

....i deleted the library folder and reopened the editor and it works now
Thanks Unity!

brittle sparrow
#

how often can I, like, call a function that deletes 100 gameobjects, before it gets out of hand?

cosmic rain
brittle sparrow
#

the average hardware, each gameobject is only a spriterenderer, collider2d, and special information script at most, and out of hand is like, the same way it would get bad if a gameobject was being created and destroyed every frame I guess? though I actually have no idea what that causes other than garbage collector, and possibly lag

cosmic rain
brittle sparrow
#

i guess i'll have to just see what happens when I start doing that with my project

#

i'm allowed to destroy an object from within that object right?

#

or does everything collapse? i doubt it though, since it sounds convenient

cosmic rain
brittle sparrow
#

oh, even better

#

it sounds stable

stark sun
#

I can only slide one enemy in platform when both are walking on the platform

slate lark
#

can anybody help me to sort this out ?

fervent furnace
#

literally you try to access a destroyed gameObject

slate lark
#

I knew, but I don't know why it destroys ?

fervent furnace
#

assume your have 90 fps, then in one second this gameObject will move to backward by 90*0.02*5=9m
it needs 1111 seconds to destroy this gameObject (if this gameObject is start from z=0), i usually not turn on play mode more than 10 mins so idk

slate lark
#

it gets destroyed in a second

fervent furnace
#

idk where your gameObject start at, check the initial position and idk why you use fixed dt in update

leaden ice
slate lark
slate lark
fervent furnace
#

fixed dt is not delta time, it is used in fixed update loop, in update loop we usually use delta time
btw i forgot will this error redirect you to the script, is this error directs you to this line or other line?

slate lark
#

I also tried delta time, it is not working

mellow sigil
#

groundtile has to be a prefab. You've dragged in an object from the scene.

fervent furnace
#

I think the groundtile has the ground script on it and it will destroy itself causing this script instantiate a destroyed go

slate lark
# slate lark

groundtile is a variable name which i used to assign a prefab
Anyways that doesn't matter.
The problem here is how Destroy executes itself without passing the condition
I have not it used in any other scripts

#

the gameobject is at 0

mellow sigil
#

put Debug.Log($"{name} was destroyed because its z position {transform.position.z} is below kill limit {kill}") inside the if statement

fervent furnace
#

The speed is public variable and something may accidentally change it

slate lark
#

its not deleting now

#

I have checked the variables, they're good

leaden ice
slate lark
leaden ice
#

Look like what

slate lark
#

clones are not being destroyed

leaden ice
#

Where did you put that log statement

slate lark
#

wait a sec, can u clarify, which one is the log

dusk apex
slate lark
dusk apex
#

What happened to the destroy statement?

leaden ice
#

So yeah of course it's not destroying you deleted it

slate lark
#

oh, I thought I had to replace
Added it again
And once again I'm back to where I started

dusk apex
#

Now then, stop accessing the object after it's been destroyed.

mellow sigil
#

there's no way you get that error if you actually dragged in a prefab there

#

and you can see a non-prefab "Ground" object without the "(clone)" specifier in the scene in the screenshot

#

$20 says they don't know what a prefab is

leaden ice
#

Yep you've dragged a scene object in

dusk apex
#

Basically the reference groundtile is a object in scene that has been destroyed. You cannot Instantiate/clone it anymore. Maybe reference a prefab instead of a scene object that will be destroyed.

leaden ice
#

If it's a blue object in the scene hierarchy that's not a prefab, it's an instance of a prefab. Delete it from the scene and drag the actual prefab into the slot in the inspector

dusk apex
#

Else don't destroy the original object - preferrably use a prefab though.

slate lark
#

I have used 'groundtile' as a gameobject only to spawn the prefab 'ground' and I have used 'groundtile' only once in the script.
I'm being overwhelmed 🤯

dusk apex
#

What they are asking you to do is to reference the prefab (should not be a scene object) and clone that.

slate lark
mellow sigil
#

This has to be a prefab. But you can see from the icon that it's not, you've dragged in the object from the scene which is not a prefab

dusk apex
mellow sigil
dusk apex
lyric spindle
#

Hi! Does anyone know how should I deal with that?

Assets\ShadowCasterRendererSilhouette.cs(10,9): warning CS0618: 'ShadowCaster2D.useRendererSilhouette' is obsolete: 'useRendererSilhoutte is deprecated. Use rendererSilhoutte instead'

In Unity 2023.1.8f1 ShadowCaster2D component, there is no longer useRendererSilhouette field, but Casting Options enum, from which none is like "useRendererSilhoutte "

vagrant blade
#

Start by checking for updates in your package manager for the lighting package

#

If you're on a newer version of Unity, there should be available updates to packages as well

#

(This is assuming you upgraded your Unity midproject)

slate lark
#

I'm back again 🥲

#

Ground destroyed

dusk apex
torn eagle
#

Wondering if anyone can help me. The player is the small object with the camera icon. I have this script that should trigger when it collides with the torus but it seems to trigger constantly. Any idea what is going funky?

 private void OnTriggerEnter(Collider other)
    {   
        if (other.tag == "NPC")
        {
            currentNPC = other.gameObject;
            Debug.Log("can ask");
        }
        if (other.tag == "Player")
        {
            Debug.Log("Player is here!!");
            evil.SetState(EvilGuy.State.FollowPlayer);
        }
    }
dusk apex
#

Also, although it will not make any difference gameplay wise consider using the CompareTag method rather than tag with string comparison

torn eagle
#

The torus is the purple shape

dusk apex
#

Check the collider for the shape. Don't recall concave shapes working nicely in Unity.

torn eagle
#

Oh ok

#

How are you able to check the shape of a mesh collider? I can't seem to view it

#

Nevermind I'm stupid lol

#

It seems to wrap around the mesh just fine though not sure if maybe it's including its middle which is stuffing it up? Would there be a better way to check for a collission with the perimeter?

mellow sigil
#

Can't it just be a sphere collider? Doesn't look like the middle part is accessible anyway

leaden ice
hard viper
#

a torus is the shape of a donut

#

you can check specific collisions with CompareTag (instead of tag ==). It’s just safer.

#

i sometimes find really strange objects triggering things that they really shouldn’t, because a tag/layer got changed at some point

jaunty needle
#

This is the function itself:

    {

        float y = -(gravityValue/(2 * velocity * velocity * Mathf.Cos(angle) * Mathf.Cos(angle))) * x * x + Mathf.Tan(angle) * x;
        return y;
    }
#

And it works for parabolas and other things

#

I'm getting the velocity and angle using these:

#

Angle: float angle = Vector2.Angle(direction, Vector2.right);

#

Initial speed:
float magnitude = (arrowShower.lineRenderer.GetPosition(1) - arrowShower.lineRenderer.GetPosition(0)).magnitude;

#

I'm gonna continue debugging this, just wondering if somebody might have a clue why it won't be working

mellow sigil
#

Mathf trigonometric functions operate on radians, you're passing in degrees

jaunty needle
neon plank
#

How can I execute a callback in a VisualElement when it's repainted/redraw?

neon plank
#

Not exactly, I want to take a VisualElement, do root.MarkDirtyRepaint(). And then all its hierarchy receive the event that they will be repainted.

last raven
#

is there a way to strip text of tags in TMP, similar to GetParsedText() but without having to assign it to TMP text first and updating mesh

#

some utility method

#

or better yet - is it possible to replace TMP rich text parser with my own so I can control what tags I want to allow and how to escape stuff?

#

I figured kind of working solution where I just replace < with <noparse><</noparse> and that prevents normal TMP tags from working and convert my own tags into TMP tags but I'd like to know if there is a better solution for this

mystic ferry
neon plank
#

Oh, I forgot about the existence of that chat. Thanks

last raven
#

also is there a way to intercept / consume input before it goes into TMP input field? with either new or old input systems

#

for example if I want to handle some key combination somewhere even if input field is focused and prevent input field from receiving this input

craggy veldt
heady pulsar
#

Unity throws a tantrum before compiling, yet VS2019 stays cool

spring creek
heady pulsar
spring creek
tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

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

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

spring creek
#

It might be, but I can't see any other code to confirm. Also see I edited my first message for the namespace I think Image is in

heady pulsar
#

IDE is configured properly so that isn't the issue

spring creek
heady pulsar
heady pulsar
#

😭

mild karma
# heady pulsar 😭

The error clearly states that you have a missing assembly reference. You will need to refernece System.Drawing in your assembly definition.

spring creek
#

And I'm so dumb for missing that sorry

#

Only looked at the first error

heady pulsar
spring creek
heady pulsar
#

that doesn't make me much more wiser yet 😅

#

WAIT HUH

#

no nvm

knotty sun
heady pulsar
#

really?

#

there's no hacky-wacky workaround?

knotty sun
#

iirc it's tied to WinForms

heady pulsar
#

so that means that I'll also have to get WinForms stuff running inside of Unity

leaden ice
#

what are you actually trying to do though

#

why do you need this

knotty sun
#

but the dll has dependencies which wont work in Unity

leaden ice
#

this is all a big XY problem

heady pulsar
spring creek
#

That's they x, they want the y

heady pulsar
#

oh no VS2019 crashed

heady iris
#

this is why you're getting interrogated about an XY problem. It makes no sense.

knotty sun
#

probably because the external dll relies on a class defined in system.drawing

leaden ice
#

but what's the point of the external DLL in the first place

#

XY problem!

heady iris
#

did you mean to say you're trying to load an external DLL so that System.Drawing works? that would at least make more sense.

heady pulsar
#

I'll explain the problem:
I'm using a library/DLL that contains code. The code is to load a more obscure image format.
The library/DLL relies on System.Drawing for the image extraction logic, yet Unity Engine doesn't like that library it seems

knotty sun
#

other way round

#

what image format?

heady iris
#

OK, so you're trying to load an image.

#

That's the X.

knotty sun
#

don't be afraid to give details, we are all grownups here

heady iris
#

What format are you trying to load, and why do you need to load that particular format?

leaden ice
#

And why this particular library/DLL? Maybe there's another library without any external dependencies that does the thing.

heady pulsar
#

if y'all really want to know so badly: a Texture Palette Library (or TPL for short)

heady iris
#

Yes, we want to know so badly.

#

We are attempting to help you.

knotty sun
#

if you want help we need to know, so dont be snarky

heady pulsar
#

yeah I'm sorry about earlier

#

alright so I'm using libWiiSharp to load the TPL, but that relies on System.Drawing for some logic/code

#

but uhh, gotta be honest: never heard about the XY problem before. Interesting to learn about

heady iris
heady pulsar
#

correct

heady iris
#

and this is a pretty esoteric format, I'm guessing

spring creek
#

So this is for modding?

leaden ice
spring creek
knotty sun
# heady pulsar alright so I'm using libWiiSharp to load the TPL, but that relies on `System.Dra...

I’ve been playing around with the “Dump Texture” feature in Dolphin recently. When the emulator dumps textures, it creates a file name that includes a hash of the texture data. Th…

leaden ice
knotty sun
#

easy peasy, change Image for Texture2D and job done

heady pulsar
#

I'm not sure if it will be that easy, but I think it might be the only option I have

knotty sun
#

of course it's easy they are both Image formatters with nearly identical API's

heady pulsar
#

oh that's great

leaden ice
heady pulsar
#

time to get coding replacing

leaden ice
#

should be a straightforward fork/port

heady pulsar
#

though, I'd like to ask, isn't it maybe easier to then just download the code and add that into Unity and edit, instead of forking whole project?

#

nvm it's GPL-3 I have to fork it

leaden ice
#

I'm using "fork" colloquially, either of those would work

knotty sun
#

fork the project outside of Unity then just copy the bits you need to your project

leaden ice
#

Just make sure you follow any GPL-3 licensing requirements 😉

knotty sun
#

I would just clone it if I'm making mods which wont be pushed

heady pulsar
heady pulsar
leaden ice
#

but yes, in general a lawyer is a good idea 😆

knotty sun
heady pulsar
#

I don't need to also provide a local copy of the source along with the modified binary?

knotty sun
#

no, just a link to the git repo in the docs

#

normally I have a separate attribution UI where I list all of the used code/assets and the source repos/web sites

#

no one ever looks at it, but it fulfills your obligations under the licenses

heady iris
# heady pulsar nvm it's GPL-3 I have to fork it

"forking" a repository would have no bearing on its GPLv3 license. If you integrated GPL'd code into your own program, you would need to license your work under a compatible license as well (probably also the GPLV3)

#

If you could keep the GPL'd code at "arm's length" from your own code, then you could get away with keeping the rest of your code proprietary

heady pulsar
heady iris
#

The FAQ talks about it, but it means that the code is clearly separated into multiple programs

#

note that I don't work with copyleft licenses much so I'm only a little more familiar than you are

scarlet kindle
#

How do I get the position of this enemy to be based on the world space,and not the camera space? I'm not understanding what I need to do in the script. You can see the xPos is -1.3 which I do not want

#

` for (int i = 0; i < enemyNames.Count; i++) {
string enemyName = enemyNames[i];
GameObject newAnimator = Instantiate(animatorPrefab, new Vector3(0, 0, 0), Quaternion.identity);
newAnimator.transform.SetParent(this.transform, false);
BattleEnemyContainer battleEnemyContainer = newAnimator.GetComponentInChildren<BattleEnemyContainer>();
BattleEnemy battleEnemy = Resources.Load<BattleEnemy>("BattleEnemies/" + enemyName);
battleEnemyContainer.battleEnemy = battleEnemy;
if (enemyNames.Count > 1) {
float alignResult = i / (enemyNames.Count - 1.0f);
float newXPos = Mathf.Lerp(-battleEnemy.xOffset/2 * (enemyNames.Count-1), battleEnemy.xOffset/2 * (enemyNames.Count-1), alignResult);
Vector3 newPos = new Vector3(newXPos, battleEnemyContainer.transform.localPosition.y, battleEnemyContainer.transform.localPosition.z);
battleEnemyContainer.transform.localPosition = newPos;
}
battleEnemies.Add(battleEnemyContainer);

    }`
#

Im not using worldToScreen space at all, so I don't get why

spring creek
#

Oh, recttransform

#

One sec

scarlet kindle
#

its not just localPosition is what I'm saying

heady pulsar
spring creek
#

Yeah sorry, I didn't look close enough. RectTransform is offset from its ANCHOR point. So still basically local.

These are UI elements, right?

scarlet kindle
#

not your fault, it's hard to tell with limited pictures

#

yea they're in a Canvas

#

but other objects in the Canvas behave the way I'd expect

#

its just these ones with the weird position

#

the reason this is frustrating is that i'd like to have the same animator for the Player and Enemies, but I can't do that if their positions are on some different scale

shell scarab
#

Why not just make those enemies be in world space?

#

what about taking them off the canvas and rendering them with an overlay camera?

odd tinsel
#

Is there a better way?

scarlet kindle
#

ideally without adding in new cameras

shell scarab
#

im assuming it's because it's a battle scenario?

scarlet kindle
#

because they behavae with the mouse, yeah its a battle

#

not sure if it was the best setup

#

but it works shrug

shell scarab
#

I really believe rendering them with an overlay camera would be best. You could try changing their rect transform to a regular transform if it lets yo, but that would probably be actually terrible to do.

#

why don't you want to add more cameras?

hidden flicker
scarlet kindle
#

Well, I'm just not understanding why the rect transform has anything to do with it. The parent is on a rect transform and it's using the world positional space

shell scarab
#

perhaps all the gameobjects in the hierarchy under the canvas do not have rect transforms

scarlet kindle
#

I'm not against the other camera per se, I just don't think it's actually fixing the problem

shell scarab
#

as far as I know the correct way to use it is to edit the rect tranform values, not the world position.

#

if you check character space does it have a rect transform?

scarlet kindle
#

yes it has a rect transform

spring creek
scarlet kindle
#

and the Player object uses a regular transform, but it's animator uses a rect transform

#

(player animator is child of the Character space)

shell scarab
#

sorry, idk then. Maybe that's your reason. I believe all transforms under UI are suppose to have rect transforms.

scarlet kindle
#

yea i mean, that makes sense. technically the canvas is supposed to be in screen space anyway right?

#

I had copied the player object over from a different scene where it wasn't part of the UI

#

so that may be why its behaving differently...

#

so maybe i just change the player to use a rect transform

scarlet kindle
#

that should standardize everything to the screen space

hidden flicker
spring creek
#

Because the error says it is null. soul can't be null

scarlet kindle
#

changed Player to use rect transform, it's still in world space wtf

hidden flicker
#

up top says the error is on line 32

spring creek
hidden flicker
#

correct

#

that's where it says the error is

#

it says object reference not set to instance of object

spring creek
#

You cropped the image, is this at runtime?

hidden flicker
#

yes

#

:(

#

also, seperate issue, lerping soul obviously causes deceleration, but lerping basesoul only decreases the value of soul one time

spring creek
shell scarab
#

why is the namespace not recognized? What's the correct namespace to use?

spring creek
hidden flicker
#

This causes deceleration:
soul = Mathf.Lerp(soul, 0f, (drainPerSecond / 60) * Time.fixedDeltaTime);

#

This causes it to only decrease once:
soul = Mathf.Lerp(baseSoul, 0f, (drainPerSecond / 60) * Time.fixedDeltaTime);

shell scarab
#

what's the command to teach people how to use lerp? !lerp no i forgot?

hidden flicker
#

i've used it before

shell scarab
#

that's not how you use lerp correctly

hidden flicker
#

ok, then how would i use it correctly to make soul linearly decrease by drainpersecond

scarlet kindle
waxen kayak
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

waxen kayak
#

hello, I' mtrying to make a basic collision avoidance script ,and I run into the problem of it not working
here is the code for it

   velocity = (new Vector3(targetPoint.position.x, targetPoint.position.y, 0) - new Vector3(transform.position.x, transform.position.y, 0)).normalized * walkSpeed * deltaTime;
        transform.up = Vector3.Slerp(transform.up, (new Vector3(targetPoint.position.x, targetPoint.position.y, 0) - new Vector3(transform.position.x, transform.position.y, 0)).normalized, deltaTime * turnSpeed);
         weight = 0;
        Vector3 moveForce = Vector3.zero;
        for (int i = 0; i < rayCast.Length; i++)
        {
            Ray2D ray = new Ray2D(transform.position, rayCast[i].up);
            RaycastHit2D hit;
            if(hit = Physics2D.Raycast(transform.position, rayCast[i].up, .7f, collison))
            {
                moveForce += -rayCast[i].up  * hit.distance / .4f;
                inverse = 0;

            }
        }
        moveForce /= rayCast.Length;
        Debug.DrawRay(transform.position, moveForce, Color.red, Time.deltaTime);

        moveForce =  transform.InverseTransformPoint(moveForce).normalized;  
        Debug.DrawRay(transform.position, moveForce, Color.green, Time.deltaTime);
        moveForce = Vector3.Project(moveForce, transform.right);
        Debug.DrawRay(transform.position, moveForce, Color.yellow, Time.deltaTime);

        velocity +=  velocity.magnitude * moveForce.normalized;
        transform.GetComponent<Rigidbody2D>().MovePosition(velocity + transform.position);
shell scarab
hidden flicker
#

why are you changing the value of drainpersecond?

#

drainpersecond should never change

waxen kayak
#

The raycasts are transforms placed in a circle around the agent

#

I have no idea at this point

shell scarab
shell scarab
shell scarab
# hidden flicker why?

because that's how lerp is used. It interpolates between two values, x and y, by t. When t = 0 result is x, t = 1 its y. t = 0.5 its half way between x and y.

shell scarab
heady iris
#

this sounds more like a place for MoveTowards...

shell scarab
#

not really. They're using Mathf.Lerp, not Vector2.Lerp

heady iris
#

current = Mathf.MoveTowards(current, 0, Time.deltaTime * drainRate)

#

Mathf has a MoveTowards (:

shell scarab
#

nevermind

#

TIL

heady iris
#

Saves you from having to clamp it from above or below

hidden flicker
heady iris
#

It is more verbose.

#

but I like the extra clarity of intent it gives you

hidden flicker
#

Appreciate your time heroshrine, ty

#

And appreciate your solution Fen

shell scarab
#

yea fen's solution is better. No idea mathf had that function.

heady iris
#

I wish it had a Distance method

#

it's just Mathf.Abs(a-b) of course

#

but it'd be consistent

shell scarab
#

but you can just subtract

#

anyways, fen maybe ur knowledgable enough to help me?

heady iris
shell scarab
#

yes

#

i restarted the editor too to see if that was a problem

heady iris
#

are you using asmdefs?

shell scarab
#

idk what that is, so no?

heady iris
#

asmdefs let you break your code into several assemblies

shell scarab
#

oh, assembly definitions. No, i'm not

heady iris
#

Assemblies have to explicitly reference other assemblies they want tou se

#

That would cause this problem

#

hmm

rigid island
#

TMP for example

shell scarab
rain minnow
# hidden flicker why?

because it's normalized. a value of 0 will return a: 1st param, a value of 1 will return b: 2nd param with anything in-between a blend of both a and b . . .

heady iris
#

This would be a problem with your code, not the package

rigid island
shell scarab
#

it's just in the assets folder (unorganized, ik, i'll get to it later)

rigid island
#

maybe you can try regen project files

heady iris
#

project files would just affect the IDE

#

unity is also erroring out

rigid island
#

ohh

heady iris
#

You can double check there isn't an asmdef affecting you here by searching your project for t:AssemblyDefinitionAsset

shell scarab
#

🤔 just popped up

heady iris
#

but if you don't see one in the root, then that probably isn't it

#

I don't understand what prompts that error.

#

I know what it means, but I also don't see why entry-points would be relevant

shell scarab
#

"failed to resolve assembly" It's the editor assembly, but perhaps this package is incompatable with my unity version? it says 2020.3+, I'm in 2022.3

heady iris
#

It could be. Doesn't look like that package has changed since 2019.3

#

but then again

shell scarab
heady iris
#

nah, the package clearly says it's compatible all the way up to 2023.2

heady iris
#

ah, I was going off of this, but I forgot that 3.0.2 wasn't showing its unity version

green oyster
#

why is unity telling me this enum needs an accessor? lol

steady moat
#

You want to use enum not Enum

shell scarab
green oyster
heady iris
#

Oh, I mean I was saying "nah, I'm wrong"

shell scarab
#

is there a different way to run benchmarking/performance tests? I was told to not just use the real time since startup - time since startup stored in a variable

shell scarab
#

omg typos

#

after all, it doesn't list 2022.3, it jumps to 2023.1, so maybe something broke that they fixed right after??

#

only thing I can think of really

#

also this when I add through manifest following instructions in the docs:

soft shard
shell scarab
#

It's a pathfinding method I've multithreaded so it doesn't actually hang the execution of the program when several units need to pathfind at once, but in the build sometimes there is a noticable delay between clicking and when units start to move, which is not the case when I'm testing in the editor. It's pretty early for optimization in my game, but I'd rather get the pathfinding running smoothly so I can be testing in a build smoothly.

hidden flicker
#

Ok. Having more problems.

  • The soul bar only starts decreasing after soul = 0, even with CheckDeath disabled, and sometimes it just doesn't decrease at all
  • I get an "object reference not set to instance of object" error when i try to set the text value of soultext to soul.tostring()
hidden flicker
#

link again

soft shard
shell scarab
# soft shard Ah I see, hmm, im not an expert on that level of optimization, I personally havn...

those ms are from:

float startTime = Time.realtimeSinceStartup;
// do pathfinding stuff
Debug.Log($"{(Time.realtimeSinceStartup - startTime) * 1000:F2}");

I've also hooked the profiler into a build to check the timings of the methods running on the threads, which are worse as well, but I can't seem to get the timing of the entire operation with the profiler due to me using await Task.Run(() => //pathfinding method);

#

and I turned off vSync, although I'm not sure if it would be affecting this here.

#

it's just strange to me that the editor would have better timings since usually you hear that the build is faster than the editor.

soft shard
#

Yeah, that is odd, unless maybe because its using a Task, that Unity doesnt calculate it correctly or "skips" some of its logic or changes it in some way while in the Editor? Im not sure if itll help, but if your pathfinding method is able to set a DateTime variable, maybe after its completed, you could compare DateTime.Now - startDate to get a TimeSpan, which should also give ms

mystic ferry
#

what is the difference between using something like Physics2D.OverlapArea and using a cast like Physics2D.Boxcast? they both seem to cast shapes to detect collisions

shell scarab
heady iris
shell scarab
mystic ferry
#

thank you both :) that makes perfect sense

shell scarab
simple egret
#

You can think as a boxcast as a thick raycast

shell scarab
soft shard
#

Interesting, guess it was kind of a red herring with Debug.Log, though in a way its good you found it was a simple fix and not something more complicated

night shore
#

I am new here. is this the chat to clear doubts?

steady moat
night shore
#

does not fit as scripts.

steady moat
rancid frost
naive swallow
#

I need another pair of eyes here. I'm not sure what's wrong with this code that should be moving an object to the edge of the screen if it's off screen. The X position works flawlessly. Y positioning does not. As soon as it's off screen it snaps to a specific point in the world way off from the edge of the screen.

https://gdl.space/danotenide.cs

Context: activeCamera is an orthographic camera that is viewing the world from above. MaxViewportRect is a Rect set from the inspector, currently 0.15f, 0.15f, 0.7f, 0.7f. I'm guessing I've got something wrong with my math or a flipped sign or something but I just can't see it.

heady iris
#

what's with the + 1 on line 10?

#

also, targetXPos is starting out as a world-space coordinate

heady iris
#

oh nvm, I misread that. that's not happening.

leaden ice
#

UI or world space?

heady iris
#

I thought it was getting a viewpoint position assigned to it

naive swallow
naive swallow
heady iris
#

ah, ok

naive swallow
heady iris
#

oh, you're using y, not z, in lines 20 and 25

#

don't you want z?

#

it's a world-space coordinate

leaden ice
#

ooh yeah that sounds right

naive swallow
#

Ah, right, the world point would be Z-forward.

heady iris
#

i love dealing with XZ coordinates

naive swallow
#

Lemme try it

heady iris
#

i kept screwing that up in a game jam

naive swallow
heady iris
#

I actually wrote extension methods that would turn a Vector3 into an [x,z] Vector2

#

and a Vector2 into a [x, 0, y] Vector3

#

i still did it wrong constantly

#

(:

heady iris
#

less clutter

crystal birch
heady iris
#

I was using XZ coordinates to look up map-gen data

daring cove
#

Hey,

My raycast commands keep returning null although the gameObject is point at target

target is 5500 units away.

maxRange is 35,000 units

Here's the snippet where the command is created.

Vector3 origin = lGameObject.position;
Vector3 direction = lTarget.position - lGameObject.position;;

QueryParameters queryParameters = QueryParameters.Default;
queryParameters.layerMask = layerMask;

RaycastCommand raycastCommand = new RaycastCommand(
  origin,
  direction.normalized,
  distance: maxRange,
  queryParameters: queryParameters
);

It seems as if it's random when the result is not null it may take multiple jobs before a hit is returned

knotty sun
#

the obvious question is what is the value of your layermask?

daring cove
#

1|3|8|10

Targets are 8

leaden ice
knotty sun
daring cove
#

It's an argument in the MonoBehaviour

leaden ice
knotty sun
#

Layer mask of layers 1 & 3 & 8 and 10 is
1<<1 + 1<<3 + 1<< 8 + 1<<10

leaden ice
#

yeah if you literally wrote 1 | 3 | 8 | 10 somewhere that's not correct

daring cove
#

The values are selected from the enum

knotty sun
#

I don't care where they come from, you are using them incorrectly

leaden ice
#

If so, that's fine

daring cove
#

yes

leaden ice
daring cove
#
handle = RaycastCommand.ScheduleBatch(commands, results, raycasts.Count, raycasts.Count + 1, default(JobHandle));
rain minnow
#

is maxHits larger than results?

leaden ice
daring cove
# leaden ice can you just show the full code?
private void Update()
{
            if (batchingState == BatchingState.Ready)
            {
                CreateRaycastBatch();
            }
            if (batchingState == BatchingState.Batching)
            {
                if (handle.IsCompleted)
                {
                    handle.Complete();
                    batchingState = BatchingState.Collect;
                }
            }
            if (batchingState == RadarSystemBatchingState.Collect) ReadRaycastBatch();
}

private void CreateRaycastBatch()
{
            Debug.Log("CreateRaycastBatch");
            List<IntermediateRaycastInfo> raycasts = GetRadarRaycastInfo();
            batchingState = BatchingState.Batching;
            
            results = new NativeArray<RaycastHit>(raycasts .Count, Allocator.TempJob);
            commands = new NativeArray<RaycastCommand>(raycasts .Count, Allocator.TempJob);

            int i = 0;
            foreach (var raycast in raycasts)
            {
                QueryParameters queryParameters = QueryParameters.Default;
                queryParameters.layerMask = layerMask;

                RaycastCommand raycastCommand = new RaycastCommand(
                    raycast.origin,
                    raycast.direction.normalized,
                    distance: maxRange,
                    queryParameters: queryParameters
                );
                Debug.DrawLine(
                    raycast.origin, 
                    raycast.origin + (raycast.direction.normalized * maxRange),
                    Color.cyan, 1
                );
                commands[i] = raycastCommand;
                i++;
            }

            handle = RaycastCommand.ScheduleBatch(commands, results, raycasts.Count, raycasts.Count + 1, default(JobHandle));
}
leaden ice
daring cove
#

yeah wait a sec sorry if the code is messy its hard to paste

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

daring cove
#
        private void ReadRaycastBatch()
        {
            Debug.Log("ReadRaycastBatch");
            batchingState = BatchingState.Ready;

            int i = 0;
            foreach (var hit in results)
            {
                if (hit.collider == null)
                {
                    i++;
                    continue;
                }
                i++;
                Debug.Log($"hit={hit.collider.gameObject.name}")
            }
            
            results.Dispose();
            commands.Dispose();
        }
leaden ice
daring cove
#

yes so the hit is null either tho the gameObject is facing the target and debugging the ray with Debug.DrawLine shows that its aligned

#

The batching process takes multiple frames would that cause trouble with colliders?

simple egret
#

Not a jobs professional here but

if (handle.IsCompleted)
{
    handle.Complete();
    batchingState = BatchingState.Collect;
}

Isn't the condition backwards here? I suspect you never run the commands

daring cove
#

I had trouble with it claiming that the handle is not complete even if handle.IsCompleted is true

#

So I think that method waits for the jobs to be complete.
Docs say:
"ensures that the job has completed"

simple egret
#

Yeah it seems like it's blocking execution until it's done

#

Can you do that without all the conditions you have, for debugging purposes?

#

Issue commands, complete the handle, read results all at once

daring cove
#

without conditions?

#

okay lets see

rain minnow
#

yeah, just try handle.Complete() and check . . .

daring cove
#

Still no and had horrible lag spikes

simple egret
#

Yeah lag spikes are normal because the method freezes the game until the handle completes
At least now we know it's not about the code structure and how it's "waiting" for the command to complete

daring cove
#

It might be floating point error because I'm 100,000 units out

#

Lets try with floating point origin shifting

#

It's not 🤔

daring cove
simple egret
#

I imagine the raycasts aren't the most expensive operation in this whole thing, spooling up a job might be

daring cove
#

It only lags when results is being iterated

#

And not all the time

#

Only when a hit has happened

sturdy thorn
#

Excuse me, I'm having an issue about the Item Switch. I have 2 scenes: Overworld and Sword Cave.
1st: Whenever I start the game in Overworld, the bombActive is true, but wont show the desired sprite, until I press L Shift which activates Boomerang and shows said Item. And when Boomerang is on and press L Shift again it activates bomb and shows the sprite. Issue is that I want the bomb item sprite to show up at the beginning.
2nd: The code doesn't work at all whenever I go inside the Cave, nor when I start there. I press L Shift but neither item activates or show sprites.

If you can help me I will appreciate it a lot, thank you!

https://pastebin.com/H8iHFb5Y

crystal birch
#

On bomb active ur making it show the boomerage sprite and on boomerang actve ur making it show the bomb sprite

crystal birch
sturdy thorn
#

That is because when I press L Shift and it activates the switch item function it checks which one is active, if bomb is active, it will then activate the boomerang

daring cove
crystal birch
#

U have the bomb set as true in start but it doesnt check if its true until u press shift

shell scarab
#

when stopping a coroutine, do I need to pass in the same value as when I started it?

simple egret
#

Pass what StartCoroutine() returns. You'll need a variable

shell scarab
#

ah I see.

#

Also, I'm wondering...
is ~(1 << 6) (used as a layer mask) an operation that needs to happen every time (for example if I put this into a raycast), or is it turned into a constant by the compiler?

somber nacelle
shell scarab
#

thx, just wondering

prisma yacht
#

I'm using this code to spawn bullets in a Netcode for Gameobjects multiplayer fps

    [ServerRpc]
    private void ShootServerRpc()
    {
        GameObject new_bullet = Instantiate(bullet);
        new_bullet.GetComponent<NetworkObject>().Spawn(true);
        new_bullet.transform.position = transform.position;
        new_bullet.SetActive(true);
    }
#

and on the host's side it's fine

#

but when the client spawns a bullet, it spawns at the host's gun and then zooms over to the client's gun

#

i didn't even code bullet movement yet, so I suspect it's interpolating or something

#

any ideas why this might be happening?

#

bullet prefab has a network object and a network transform component

dense estuary
buoyant crane
dense estuary
dense stag
#

Hey I just have an important question about loading TextAssets. When I parse the textAsset.text variable into a JSON object it is extremely slow because it takes a long time to get all the data from the text. How can I load this in the background with a really efficient async or coroutine?

[SerializeField] private Transform geoTransform;
[SerializeField] private Transform frontiersTransform;
[SerializeField] private Material frontiersMaterial;
[SerializeField] private AssetReference geoReference;

private void Start()
{
    geoReference.LoadAssetAsync<TextAsset>().Completed += asyncHandle =>
    {
         if(asyncHandle.Status == AsyncOperationStatus.Succeeded)
         {
                // This is really fast
             TextAsset textAsset = asyncHandle.Result;

                // This is not fast due to textAsset.text;
             JObject jObject = JObject.Parse(textAsset.text);
             foreach(JToken features in jObject["features"])
             {
                 foreach(JToken coordinates in features["geometry"]["coordinates"])
                 {
                    DeserializeCountryFrontier(coordinates);
                 }
             }

             Addressables.Release(asyncHandle);
        }
    };
}
tardy basin
#

This object gets added by Unity to my scene, I dont know why. Any clues? It doesn't have any components aside from Transform.

shell scarab
#

I suppose it could be something to do with netcode for gameobjects (since looking it up that's the only related thing google can find, but I find it unlikely, however I haven't used netcode for gameobjects much). Do you have that installed? And how do you know it's added by unity?

dense estuary
#

The instantiatePrefab.transform.Rotate(Vector3.up, Random.Range(rotationRange.x, rotationRange.y), Space.Self); part of my code isn't doing anything, its supposed to rotate my prefab a random amount around the y axis. And it's not doing anything.

shell scarab
#

you are immediately overriding the rotation on line after that. I believe Quaternion.ToFromRotation is rotating the object to point along the hit normal, then you are essentially adding that rotation to the game object, then lerping between the rotation you applied on the 3rd line to that new rotation. What value is rotateTowardsNormal?

dense stag
# dense stag Hey I just have an important question about loading TextAssets. When I parse the...

Never mind fixed my own problem

[SerializeField] private Transform geoTransform;
[SerializeField] private Transform frontiersTransform;
[SerializeField] private Material frontiersMaterial;
[SerializeField] private AssetReference geoReference;

[SerializeField] private GeoRoot geoRoot;

private void Start()
{
    JsonSerializer serializer = new();
    var path = Application.streamingAssetsPath + "/Data/Earth/Countries.json";
    using FileStream s = File.Open(path, FileMode.Open);
    using StreamReader sr = new(s);
    using JsonReader reader = new JsonTextReader(sr);
    while (reader.Read())
    {
        // deserialize only when there's "{" character in the stream
        if (reader.TokenType == JsonToken.StartObject)
        {
            geoRoot = serializer.Deserialize<GeoRoot>(reader);
        }
    }
}
shell scarab
dense estuary
#

I needed to Rotate after setting the rotation. thats why it didnt work before

shell scarab
#

ok, just an order of execution bug. Also sounds like you're using the lerp right 👍

night harness
#

Wasn’t really sure what to ask but can someone give me some sauce for SFX playing programming patterns / common setups? (More specifically for menu related stuff that doesn’t care about positions and such

Right now I have a singleton with a singleton that just stores a shitton of audioclip references just so i can easily play stuff in a single line but curious how other people do it

dense estuary
tardy basin
shell scarab
#

well if it was updated or perhaps some condition is being triggered to cause it to create that? Check to see if they have any kind of support form.

dense estuary
shell scarab
#

yea, you'd have to loop through what it finds and check every object to see if it's a tree.

night harness
#

@dense estuary A more sketchy approch could just be having a little collider above/around your tree prefab with a layer dedicated to just failing that raycast you do

#

that way your raycast hits the trees "aura" and fails because its too close

neon plank
#

Question, is fine in FixedUpdate do rigidbody.AddForce(transform.up * val)? The rigidbody is updated in the physics step, but transform.up doesn't? Shouldn't be rigidbody.AddForce(rigidbody.rotation * Vector3.up * val)?

dense estuary
cosmic rain
shell scarab
#

yea i know, you'd have to loop through the array and check if there is a tree, if not set some bool to true so it's like if(tree)

#

but if a single sphere cast works for you that's fine.

neon plank
#

But if I modify rigidbody.rotation then it will no longer be valid transform.up, right?

celest solstice
#

I'm trying to implement a character selection screen with a circular carousel view (that is, if you keep scrolling left or right, you'll eventually reach the same character). I'm currently using a circular array to implement this since it felt like the most logical thing due to the problem. However, I'm having trouble when it comes to "repositioning" elements, so it acts like an eternal scroll.
Here's my code so far: https://pastebin.com/LA48CZTQ. Yes, I'm currently using DoTween to do the movement, but that shouldn't matter too much since it's just a prettier version of just repositioning things. I'm having brain trouble deciding if I should move the whole array left or right when scrolling and keep an index in the middle, or just move the index and calculate the boundaries in some other way (which is what I'm doing right now).

cosmic rain
#

You can also just apply force in local space.

#

That's guaranteed to work.

neon plank
#

Ok, thanks

cosmic rain
#

If you want to move the rb relative to it's orientation that would be the safest method.

neon plank
#

Ok

#

Thanks

dense estuary
#

wait, nvm

cosmic rain
dense estuary
celest solstice
# cosmic rain Maybe move the index and if it's < 0 or >= array.Length then set it to Length - ...

Yeah, definetly ! The array it's not the problem at all. That's a struct that I didn't include in the code, but it internally does basically that. I'm having trouble with like, the repositioning part of things. So let's say, since it should feel like an infinite scroll, once you reach index 0 it logically goes to index array.Length - 1 , but the visible part, where you just put the element of array.Length - 1 next to the element in index 0 on screen is what's making me squeze my brain juices haha

cosmic rain
#

It might also be helpful to explain the actual issue, as I don't understand it completely.

leaden ice
#

It's technically more correct I think

celest solstice
quartz folio
leaden ice
#

sometimes I want rigidbody.up for other reasons though

celest solstice
#

Is it okay if I send some screenshots here ? I don't wanna, like, flood the chat

#

It's just 3 tho , but still

leaden ice
#

yes you can send screenshots to help illustrate your problem

celest solstice
#

It logically works, however I can't for some reason figure out how to do the movement itself

#

Because when you point to the "last element" to be put as first, the "last" element it's always the same following an index

shell scarab
cosmic rain
#

How many cards do you want to be visible on the screen at once?

celest solstice
celest solstice
cosmic rain
#

Let's say 5 cards are visible at once. And let's say the 3rd card is the one that's always selected.
Let's say you have them display data from 0-5 positions in the array. Once you scroll left, the card at position 0, would shift it's data index from 0 to -1, then fixed to the last position(let's say 31).

#

With the data from 31 fed into the card.

green drift
#

I have a gameManager object that has a public variable that tracks time, and i want at some point in time for a prefab to change sprite, but i can't drag and drop the gameManager object into the editor inside the prefab cuz some reason

#

so how would i access the time variable if i cannot check the game Manager?

cosmic rain
celest solstice
#

That leads me to the problem that the last card to the right in the case of scrolling to the left, gets put into where "it should be"

cosmic rain
#

If the last card is already pointing at the last data position and you shift it to the next position, it should loop back to 0 obviously.

#

If you're not making that check, it would point at last pos + 1 causing an out of bounds error.

celest solstice
#

Yeah, it loops without a problem, when you say "pointing at the last data position" what do you mean ? I'm asking because there's no "data position" as it is, it's just a float value that decides where the card should go, the array doesn't store any information about it

#

Maybe I should ditch the idea of a "static" calculus, and make it more like a "move X float amount to the direction" and just make the last one loop

#

This doesn't go against the implementation of the circular array but it would mean to basically re-do everything I've done , lol

cosmic rain
#

Okay, maybe I don't understand the issue after all. What float values are you referring to? What does it have to do with calculus and what do you mean by "static" calculus?
Is the issue with actually physical movement of the cards?

#

You'd typically have the UI independent of the data, so if you want a looping ui, it wouldn't matter to it if the data has reached the end of the data array or not. It would act and move the same regardless. If it doesn't, then your ui has a hard dependency on the data which is not correct.

cosmic rain
proud juniper
#

For managing multiple UIs that can be shown/hidden, is there any reason to prefer hiding/showing a canvas over hiding/showing a panel or vice versa?

cosmic rain
proud juniper
#

Thanks for the insight!

green drift
cosmic rain
green drift
#

Then how do i change the tiles appearance?

#

i have to replace the tile?

cosmic rain
green drift
#

i'll take a look into it later

celest solstice
# cosmic rain Okay, maybe I don't understand the issue after all. What float values are you re...

It's kind of complicated to explain, but basically to "re-arrange" the cards I just loop from 0 to array.Length through the array and then calculate basing on the index and the difference of the i index currently looping and the index of the selected item. So the block of code that does that is this one:

int trackerPoint = index - i;
RepositionRectTransformToLocation(rect, trackerPoint * -distanceBetweenCards, trackerPoint * distanceBetweenCards);

That's just for the left part, but basically it goes from 0 to index and calculates like so:

i = 1, index = 3, distance = 100
trackerpoint = 3 - 1
RepositionRectTransformToLocation(rect, 2 * -100, 2 * 100);

And that method just sets the left and right parameters of one of the cards

   private void RepositionRectTransformToLocation(RectTransform rect, float left, float right)
   {
       rect.SetLeft(left);
       rect.SetRight(right);
   }

Which, again, just sets the rect's left and right, I know you can't just acess those things with methods, but I coded some extensions that basically do that, that's why "SetLeft" and "SetRight" are correct.

#

Damn, hope I explained it a little better, lol

#

Hence why I call it "static", it just sets the card's positions without caring about where they were before. Just puts them in calculated positions

#

Even if it is UI, I'm just moving UI objects around, it's no different from moving gameobjects themselves

cosmic rain
#

Wait, are you actually shuffling the cards around?

#

Changing their position physically?

#

Okay I see.
That's where you have the wrong approach imho. The cards should never change their physical position.

#

Card index 0 would always stay on the fat left side. The only thing that should change is the data that it displays.

celest solstice
#

O

#

I see

#

Right

#

So instead of just shuffling the things around

#

I should just update the information displayed ?

cosmic rain
#

Yes.

celest solstice
#

But then how would you a transition of the cards ?

#

You know, showing how the left one moves right and so

#

I took the approach to actually moving them because I had in mind to use DoTween to move them and make it smooth, but it's some sophisticated way of just moving them

cosmic rain
#

You'd have one extra card that doesn't fit on the screen on each side. You play an animation of scrolling all the cards to one side , then snap it back and reassign the data of each card.

#

You can still use dotween or whatever you want for your animation.

#

The point is that you only need to make it look like the cards physically shifted.

celest solstice
#

And why is it a bad idea to make them move ?

#

I'm just asking, is there any reason other than the fact that they're UI ?

cosmic rain
#

It's inefficient, less performant and you'll get tangled in the logic of moving them around.

celest solstice
#

As it happened to me

#

I see

#

Well thanks about that, now it's just a matter of re-factoring things to implement that new approach

urban orbit
#

Does somebody know why my code doesn't work? The touch world pos is fixed on the cinemachine virtual camera pos instead of the touch pos.

dusk apex
#

Which part doesn't work? Are there any logs?

urban orbit
#

The weird thing is that I do get the correct screen pixels pos when I don't use ScreenToWorldPoint but it's just fixed on those coordinates when I add that.

dusk apex
#

Does the value not change regardless of where you have touched on the screen?

#

Are the values always the same?

urban orbit
dusk apex
#

Does the value change depending on where you've touched the screen?

dusk apex
plucky karma
rain minnow
urban orbit
#

I had my camera set as perspective instead of orthographic 😅

rain minnow
#

yeah, depth matters in 3d (perspective) mode . . .

plucky karma
#

Has anyone connected a bluetooth device using Unity from android platform before?

dusk apex
#

Don't ask if someone's done something before, just ask your question - coding channel.

urban orbit
rain minnow
earnest gyro
#

Help with Events and Listeners

urban orbit
plucky karma
urban orbit
#

Whaaat? Why am I getting a y coordinate if it's set to 0?

plucky karma
#

you supplied the wrong value. the positon.y is in z value, and y is always 0.

#

I would suggest do this step by step. First, let's reference the camera. Second, create a new vector3 variable, plug in the position x and y into the correct parameters. Then supply the camera's far plane into the z parameter. Last, call ScreenToWorldPoint method afterward.

urban orbit
#

I think I got it working

#

this is what I did

#

now it's better but there's still a small offset in the position. I think it has to do with the z value (cam.nearClipPlane) of the touchScreenPos, but I don't know how to fix it

spring creek
#

Why are you doing touchscreenpos? You're taking the vector2 and going STRAIGHT out to the nearClipPlane (which wouldn't follow the perspective) which gives you a world point. Then you use that world point to get another world point.

I think I'm just confused. I see that was nearly a suggestion (but they said farclipplane). I don't understand it, but if it's getting closer to what you want then before... then... I dunno lol

spring creek
# urban orbit What do I have to do instead?

Why can't you just use the Touch.position in ScreenToWorldPoint? or raycast out if you're trying to hit a terrain or something. I didn't really see the issue you had at the start so maybe I'm way off base

#

Ah, because screentoworldpoint takes a vector3.... hmmm

#

Ok, the docs literally tell you to do exactly what you did
point = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));

EDIT: Ok, forget everything I said lol. Sorry

plucky karma
#

This sounds like an X/Y problem, where you explain that your code doesn't work, but then now that it's working again, you ran into another problem we're completely unaware of. What doesn't work, and what should work.

celest solstice
cosmic rain
# celest solstice Can you further explain this to me ?

So, when you're gonna play your transition animation, you want to move all the cards to the left or right. In this situation, if you only have cards that fit in the screen, you'd have an empty space left when a card should be. Another card outside the bounds of the screen would prevent that.

celest solstice
#

Yeah, with enough cards that's not a problem

#

Thing is, how do you make it so it's a smooth transition in the update of the data in the card

#

Because you either update it before the movement, or after the movement and both look kinda clumsy

cosmic rain
celest solstice
cosmic rain
#

In this case you might need some kind of pooling system, where you take cards from the pool and place them where new cards should appear, while putting scrolled cards back to the pool.🤔

#

In which case I guess we're back to the point where you need to move the cards physically instead of just faking it.

celest solstice
#

Yeah

#

I pondered about that

#

What I figured is that

#

I can set a margin to where cards are moved back to the other side

#

Let's say I have 7 cards with a separation of about 300, so the middle would have 3 cards to each side, that's 3 * 300 = 900 units

#

So any card that goes past 900 units gets set back to -900

#

Same to the other side

#

That way you just move cards left to right and correct them if they go past the margin

cosmic rain
#

Yeah, that should be fine.🤔

celest solstice
#

idk why I didn't figure that earlier

#

but oh well

#

Back to the drawing board I guess, didn't establish any flow managment program like git, so gotta code it again 🤣

cosmic rain
scarlet viper
#

I detect ground angle but how can I then slow the vehicle when it drives uphills?
The issue is speed is an incremental value that grows according to input
But if I reduce the speed in one-frame/update(), it will continue being reduced forever, even though the speed penalty from that uphill shouldve been already applied

I think what i need to do is to cache the ground angle. and also cache how much I already used of it to slow down the vehicle

  • This way i wont apply penalty for uphill driving more than once, at least until the angle changes
  • but unsure when should i reset it
    Maybe there are other ways ?
    This is the concept so far, should be ok, ill code it
            - store ground angle
            - take from it by reducing vehicle speed
            - add to it when ground angle increases
            - remove from it when ground angle decreases
lean sail
#

Like vehicleSpeed += speed * (some 0 to 1 value based on the angle) * (any other factor)
That 0 to 1 is arbitrary as well, it could be 0.5 to 1 or whatever you want the gameplay to feel like

scarlet viper
#

i see yeah your idea is better thanks

native fable
#

Hi

    public class ABDropdownAttribute : DropdownAttribute
    {
        
    }

    public class ABDropdownAttributeDrawer : DropdownAttributeDrawer<ABDropdownAttribute, string>
    {
        protected override ValueDropdownList<string> GetDropdownList()
        {
            var type = typeof(ABFields);

            var properties = type.GetFields();

            var list = new ValueDropdownList<string>();
            
            foreach (var propertyInfo in properties)
            {
                if (propertyInfo.FieldType == typeof(int))
                {
                    list.Add(propertyInfo.Name.ToSpacedCase(), propertyInfo.Name);
                }
            }

            return list;
        }
    }


[Serializable]
    public class ABFields
    {
        public int a = 0;
        public int b = 1;
    }

Can you please tell me why this code does not show me the list of fields in the inspector?

autumn sail
#

im using a ray layer mask but despite the child of my parent being on a layer that shouldn't be hit its blocking the collision of the parent, how can i fix this?

mellow sigil
#

Show code

leaden ice
vague tundra
#

I have:
public ISomeInterface someInterface

But the slot does not appear in the inspector for me to drag-n-drop an object with a script that implements ISomeInterface.
Is it supposed to, and if not, how can I have something akin to this functionality?

lean sail
#

I believe you can also just GetComponent with the interface. so you just need a reference to the object you want it on

strange ferry
#

Hey guys, I'm having trouble adding OnClick.AddListener to instantiated buttons, apparently their events are not triggering. Is there a way that you guys know about? Thank you.

soft shard
strange ferry
#
            InfoCard_UI_Comment comment = go.GetComponent<InfoCard_UI_Comment>();
            comment.Initialize(messages[i], false);```
I instantiate the prefab, get the component and call an Initialize function that inside is the
```        likeButton.onClick.AddListener(OnClickAction);```
#

Sorry for the indentation it came a bit odd

soft shard
#

No worries on the formatting at least its in a code block so a bit easier to read - im guessing messages[i] fill your OnClickAction param?

strange ferry
#

Well yes, it is indeed getting to the likeButton.onClick.AddListener since when using the debugger it gets there but when clicking the object whatever is inside OnClickAction is not executing

#

I'm guessing it looses reference somehow but Im unable to understand the why

soft shard
rain minnow
#

@strange ferry if so, you may have a closure issue. you need to cache i to a local variable and use that instead . . .

var index = i;
comment.Initialize(messages[index], false);
strange ferry
#

Sorry for the late response, I fixed it, I was making two different objects, one listened to the event and the second one was a copy of the first one but it wasn't able to listen to the event, thanks everyone.

orchid bane
#
humanInput.OnLeftClick += () => playerEntity.Shoot(0);

I will have many subs and unsubs like this and to many different entities at that. How do I unsub without creating a separate method for each combination of entity and the int argument?

thin aurora
#

So you need to subscribe like this for example

humanInput.OnLeftClick += Shoot;

void Shoot()
{
  playerEntity.Shoot(0);
}
#

Then you can do humanInput.OnLeftClick -= Shoot

orchid bane
#

But I will have like tens of these methods in that case

thin aurora
#

Otherwise you have an anonymous function and it's unlikely that that will work since there is no proper reference

thin aurora
orchid bane
#

OnLeftClick doesn't have a parameter

thin aurora
#

I was talking about the parameter of your shoot function

orchid bane
#

How do I choose the proper parameter then? It's supposed to be 1 for right mouse button

stark sinew
# orchid bane How do I choose the proper parameter then? It's supposed to be 1 for right mouse...

You could, for example, create some methods like HandleLeftClick and HandleRightClick which then call into the corresponding Shoot(0) or Shoot(1) methods

Or just get rid of the parameters of the Shoot method if possible, that would probably be easier to read as well, for somebody that doesn't know your project it's not clear why Shoot takes an int parameter in the first place.

Maybe do something like ShootPrimary and ShootSecondary

rain minnow
tacit parrot
leaden ice
#

I have no idea what the code you shared is supposed to be doing - it doesn't seem to attempt to get the "current control scheme" in any way

#

it also seems to just be trying to print an uninitialized array and an uninitialized string

pliant gorge
#

hello everyone, can anyone explain how RaycastPadding.Set() works(if it does at all)? i'm literally doing this
GetComponent<Image>().raycastPadding.Set(-400, -150, -400, -1450);
Debug.Log(GetComponent<Image>().raycastPadding.x);
and get a 0 in the console
if i replace the padding with the padding of another image it does work, but i just wanted to know why this one doesn't

leaden ice
#

to be honest though I don't even know what raycast padding is and I don't see it in the documentation