#archived-code-general

1 messages · Page 211 of 1

elder flax
#

im just thinking if theres a better way than what im doing rn for a big 2d array level editor

lean sail
#

A level itself cannot be an image so this doesnt really make sense

elder flax
#

the visuals can, then have collision data as well

#

i was thinking arena game ish with seperated rooms

lean sail
#

What do you plan to store inside the array? Like what do these ints represent?
You could probably optimize since I doubt every single element in your massive 2d array is needed

elder flax
#

the ints are the pixel identity

#

like 0 is empty, 1 is layer 1, 2 is layer 2 (these dont rlly matter in terms of anything here, they just arbitrary)

#

ive used dictionaries for this kind of thing before, would that be a better approach maybe

#

also it seems performant rn for 600x400, it died when i tried 1366x768 though

elfin aspen
#

does anyone know what's going on, this massage appear on my console, i just dont know what's wrong or what seem to be a problem, when ever i click anything on the editor it will appear that massage, but the game run normaly, any help for that?

fervent furnace
#

seems that you need quad tree, but quad tree sucks if the image is too "fragmented".
1366*768*4=4196352bytes, 4MB

elder flax
#

thats a scary amount of memory

#

it seems the main hit is the loop to tell my spriterenderers what colour to use, i guess that could be indivdual scripts job? or a shader somehow?

somber nacelle
elfin aspen
#

i dont know where to ask

somber nacelle
lean sail
elder flax
#

one per entry in the array

#

its horribly inefficient not gonna lie

fervent furnace
#

cant you use tile map?

elder flax
#

oh i didnt think of that

#

good idea actually

fervent furnace
#

at least 1366*768 gameobjects, i believe your editor will crash (though loading 1M gameObject should be possible if your computer is powerful enough)

elder flax
#

mhm

lean sail
#

If anything you probably wouldve been better off generating an image based on the array and pasting that on a single object

elder flax
#

that would be pretty laggy as well no?

#

like whever you draw

lean sail
#

It would be generated just once, your lag was probably just due to the amount of objects rather than anything pixel related

#

Either way yea tilemap is probably what you need

royal temple
#

Yes, I've checked 😦

#

ok, I found the issue.
This is dumb, we have 2 different Animators that are both referenced by a parent C# class.
Therefore, the warning was on the other Animator. Sorry for the trouble. Thanks for your help

floral rain
#

Hey there, I have this screenspace texture shader that works pretty much perfectly, except for one issue: the texture is too big. How do I downscale it? I can't seem to figure it out...
Here's the code:

// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'


Shader "Unlit/Moon" {
    Properties {
        _Tint ("Tint", Color) = (0, 0, 0, 1)
        _MainTex("Texture", 2D) = "white" {}
    }

    SubShader {
        Tags { "RenderType"="Opaque" "Queue"="Geometry" }

        Pass {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            sampler2D _MainTex;
            float4 _MainTex_ST;

            fixed4 _Tint;

            struct appdata {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            v2f vert(appdata v) {
                v2f o;

                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = ComputeScreenPos(o.vertex);

                return o;
            }

            fixed4 frag(v2f i) : SV_TARGET {
                fixed4 col = tex2D(_MainTex, i.uv);

                col *= _Tint;

                return col;
            }


            ENDCG
        }
    }

    Fallback "VertexLit"
}

And here is a screenshot of what it looks like:

floral rain
#

Fixed it! Just multiplying the uvs and setting the texture's wrap mode to repeat worked. Probably not the cleanest way though.

crude mortar
#

that should be the cleanest way

#

I mean you could modulus the UVs to make them repeat yourself but your solution is the how its almost always done

fiery path
#

General more theoretical and functionality question here
I am making a game with multi dimensions that can be switched inbetween
Should this be handeled in one large script that alters between them with button pressing on an empty game object
Or should this script handle bools that communicate with seperate scripts to handle these realms

cosmic rain
#

Well, what exactly does it mean to switch between dimensions from the technical point of view?@fiery path

hard viper
#

idk, there is not enough info to help here

#

Let’s say I have a list to iterate through, and a tree class that contains some of the entries (tree is subset of list). The logic for the order goes by:

  1. yield return all entries where field1 == 1, and not in tree, sorted by GenericSortMethod.
  2. enumerate through entries of tree, which has its own logic,
  3. yield return all entries remaining, in order of GenericSortMethod
#

is there a way to do this without just making a bunch of lists and concatenating them? I’d theoretically want to just get an IEnumerable

#

Tree currently can output an IEnumerable for its own order

#

Also, I am okay with modifying the order of my list

fiery path
fervent furnace
#

i think i understand the problem statement, so you have a tree and you want to iterate the elements stored in tree node in a some order without pushing every element to list and sort it....

hard viper
#

yeah, tree sorts itself, and uses its own recursive methods to give an IEnumerable for itself

late lion
# hard viper is there a way to do this without just making a bunch of lists and concatenating...

Pseudocode would look something like this:

public IEnumerable<T> IterateList()
{
    // 1. sort the list.
    GenericSortMethod(list);

    // 2. return filtered entries
    foreach (var entry in list)
    {
        if (entry.field1 == 1)
            yield return entry;
    }

    // 3. enumerate through tree
    foreach (var treeEntry in tree)
    {
        yield return treeEntry
    }

    // 4. return remaining entries
    foreach (var entry in list)
    {
        if (entry.field1 != 1)
            yield return entry;
    }
}

The multiple enumeration of list can be avoided by filling an intermediate list during the first iteration, but that uses more memory and allocates garbage if you don't pool it.

fervent furnace
#

so is the order of tree different from the order you need in this iteration? if yes then i think you must stores the entries in list then sort it....

late lion
#

Ah, forgot about the "not in tree" condition for the first step.

hard viper
#

yeah, three enumerations + full sort might be the way to go. Not sure if there is a smarter way

lost knot
#

guys can you help me

hard viper
#

similar, but obeys tree structure

lost knot
#

how do i check for collisions in an if statement

fervent furnace
#

tree can be unordered but no one will use it

hard viper
#

assume tree manages sorting itself

#

before we start, it is ready to spit out an Ienumerable

hard viper
fervent furnace
#

if the order of iteration is different from tree, that means you have no way to predict where is the first element, second element and so on, then list is needed in this case

hard viper
fervent furnace
#

maybe your tree is sorted by field0 but you need to iterate in the order of field1 etc

lost knot
#

so how would i store a booelans?

#

i am kinda new to unity and c#

#

just came back after 3 years

hard viper
hard viper
lost knot
#

oh

#

so just variables?

hard viper
#

yeah

lost knot
#

they work as booleans?

#

thats nice

#

really conveniant really

#

thank you

hard viper
#

you can handle things during collision callback, which happens after physics step. Or you can store information to run things at some other time

open pewter
#

hello

hard viper
#

Maybe I should make a different tree structure, that consilidates everything via root nodes

cosmic rain
# fiery path Think of it in this sense 3 states (simplifying this mega lets say switching bet...

This is not very detailed. Or technical.
I was thinking about state machine, but since it's only 3 states, it might be simpler to just hardcode it.
Now, whether to put it all in one class or multiple, depends on many factors. If you can isolate separate objects/behaviours without spaghetti dependencies between them, it's a good idea to split it into several classes. Can't say anything more specific without more details on your implementation.

knotty sun
#

!collab

tawny elkBOT
knotty jacinth
#

😮

fiery path
fervent furnace
#

your problem can be translated to:
how to iterate a unordered list (since tree can be iterated as list with dfs and the order is different from tree, can be treated as unordered) using constant memory (stack needed in dfs is ignored) ofc O(n^2) time O(1) memory exists.....

cosmic rain
fiery path
#

aweomse ill have a look into them

#

thank you

eager fulcrum
#

Hey, I have a list of layers
[SerializeField] private List<LayerMask> _playerLayers = new();
and im trying to change layer of a player when he spawns
player.gameObject.layer = LayerMask.NameToLayer(_playerLayers[_playerCount - 1].ToString());
but i get this error

A game object can only be in one layer. The layer needs to be in the range [0...31]
#

Why?

hard viper
#

also, refactoring my tree to not autodelete nodes with no children, and using a treenode class helps so much.

fervent furnace
#

layermask is not layer

eager fulcrum
#

so what should i use

hard viper
#

it’s a bit confusing. LayerMask is an enum flag type

knotty sun
hard viper
#

layer is an int, which corresponds to one of those bits

#

i always forget, so I use a package with a static Layers class. So I can do things like Layers.ENEMY and Layers.ENEMY_MASK

#

it greatly improved my workflow with layers

eager fulcrum
edgy badge
#

Guys, good day :3
Sorry for the stupid question, I'm a newbie game developer ❤️
What's the best way to design level changes for indie platformers? is there any guide? Is it better to do this on one stage or create several for each level?

oblique spoke
knotty sun
hard viper
#

there are many options. I like this one because it just generates static classes with public const int

#

no references like other packages. just const

#

my professors in college told me: consts basically tell the compiler to control+F modify your code before compiling it.

fervent furnace
#

depends on language, but true in c#

hard viper
#

this was in context of C and C++. Not sure how big C# was during my college years

#

Python and C++ were the big players at the time.

eager fulcrum
#

I have another issue

#

i have a sprite with box collider (trigger)

#
private List<Collider2D> colliders = new();
private void OnTriggerStay2D(Collider2D other)
{
    if (!colliders.Contains(other) && other.transform.CompareTag("Player")) 
    {
        MainMenuManager.Instance.PlayersInsideStartingArea++;
        colliders.Add(other); 
    }
}

private void OnTriggerExit2D(Collider2D other)
{
    if (other.transform.CompareTag("Player"))
    {
        MainMenuManager.Instance.PlayersInsideStartingArea--;
        colliders.Remove(other);
    }
}
#

PlayersInsideStartingArea = 1 when player enters this sprite

#

but it increases to 2 when he jumps

#

any ideas why?

fervent furnace
#

no, maybe try log if (and why) the increment is executed twice

#

and consider ontriggerenter, though guard is still needed

eager fulcrum
#

tried ontriggerenter too

#

it didnt work

fervent furnace
#
void OnTriggerEnter(Collider other){
debug.log($"other is {other.go.name} tag is {other.tag} is the list contains it {list.contains(other)}");
}
#

log all infos you need

eager fulcrum
#

for some reason it fails at Contains

#

fixed

#

i changed the list to the list of GameObjects

hard viper
#

exactly how do IEnumerable/IEnumerator work with foreach enumeration? The syntax always confuses me

fervent furnace
#

just cpp iterator* it=something.begin();it!=something.end();it++, but the ++ is overloaded...

royal temple
#

Hello, can anybody tell me (maybe a link to documentation) what API should I use if I want, from Script, to add an actual Prefab instead of instantiating an instance of it to my GameObject please?
I want version 1 and not 2 of my screenshot

hard viper
#

I see. So from a functional standpoint, IEnumerable allows clean foreach syntax, while IEnumerator has messier syntax (because you need to cast), but allows you to manually iterate/skip/reset if needed?

vestal quartz
#

Can someone tell me how to fix this please I’ve suffered for 3 days trying to start making games

royal temple
royal temple
#

Ha, it says somewhere PrefabUtility.InstantiatePrefab

#

Thanks 🙂

hard viper
#

i don’t understand. Instantiating a prefab makes a clone

#

it’s a prefab. that’s the point

fervent furnace
#

reset a iterator is equivalent to create a new iterator, i think foreach is just syntax sugar of getting iterator->while(haveNext())->moveNext(), you can still continue; and break; in foreach loop

royal temple
#

Yes, but I want to keep working with the whole linking to parent Prefab etc

#

It's editor behavior, not runtime behavior

hard viper
#

oh. that’s really weird. you usually don’t want to do that

spring creek
royal temple
royal temple
hard viper
#

oic. that is a weird use case

fervent furnace
hard viper
#

you know you can have a prefab in a prefab too, right?

#

like, I have UraniumBlock as a prefab variant of a generic solid prefab, and it has a RadiationField child object which is linked to a RadiationFieldPrefab

royal temple
# hard viper oic. that is a weird use case

Well to give a bit of context:
I have Interactable script on Interactable gameobjects. I want to add a World Space Canvas feedback above each one. For now, I can't really have a parent prefab (in the future, I will have a single prefab where all interactable objects are Variant of it, so no problem), but for now, I want some QoL to improve older scenes.
So my approach was to add some behavior in Reset() function of that script so that it adds what it needs when it's added, but I don't want to just add a cloned object, I want to keep the whole "working with prefab" thing

#

I'm quite well versed in Prefab, yes, I know about nested and variants. It's a temporary QoL, not a best case scenario sadly

#

But I appreciate the feedback 🙂

hard viper
#

just making sure you aren’t making life harder than it needs to be

royal temple
#

Yes for sure, it's appreciated

#

Using PrefabUtility.InstantiatePrefab worked like a charm.

hard viper
#

sounds good

ivory dock
signal cape
#

why when i print jsonOverrides it prints : "{}" while print(overrides[key]) prints : /e

(i need jsonOverrides to store the changed key but i have no idea why it does not work)

code :


  private void SaveOverrides()
    {
        //save
        var overrides = new Dictionary<System.Guid, string>();
        foreach (var map in actions.actionMaps)
        {
            foreach (var binding in map.bindings)
            {
                if (!string.IsNullOrEmpty(binding.overridePath))
                {
                    print("saved");
                    print(binding.overridePath);
                    overrides[binding.id] = binding.overridePath;
                    print(overrides[binding.id]);
                }
            }
        }
        print(overrides.Keys.Count);
        print(overrides.Values.Count);

        print(overrides.Count);

        string jsonOverrides = "";
        foreach (var key in overrides.Keys)
        {
            print(key);
            print(overrides[key]);
            jsonOverrides += JsonUtility.ToJson(overrides[key].ToString());
            print(jsonOverrides);
        }
        print(jsonOverrides);
    }
leaden ice
#

You should add more descriptive text, for example:

print($"Full jsonOverrides string: {jsonOverrides}");```
leaden ice
#

sketchy - anyway show the output

signal cape
#

(exemple :

leaden ice
#

yeah i can't make heads or tails of that

signal cape
#

ok so

leaden ice
#

add more info to the logs

#

also you have Collapse turned on as far as I can tell

#

which is going to really confuse the ordering

signal cape
#

alr i changed it gimme 1sec

#

here

leaden ice
#

would have to show the corresponding code

signal cape
#
private void SaveOverrides()
    {
        //save
        var overrides = new Dictionary<System.Guid, string>();
        foreach (var map in actions.actionMaps)
        {
            foreach (var binding in map.bindings)
            {
                if (!string.IsNullOrEmpty(binding.overridePath))
                {
                    //print(binding.overridePath);
                    overrides[binding.id] = binding.overridePath;
                    //print(overrides[binding.id]);
                }
            }
        }


        string jsonOverrides = "";
        foreach (var key in overrides.Keys)
        {
            print($"overrides key string: {key}");
            print($"overrides value string: {overrides[key]}");
            jsonOverrides += JsonUtility.ToJson(overrides[key].ToString());
            print($"Full jsonOverrides string: {jsonOverrides}");
        }
        print($"Full jsonOverrides string: {jsonOverrides}");
    }
leaden ice
#

This: JsonUtility.ToJson(overrides[key].ToString()); makes very little sense

#

why are you calling ToJson on a string?

signal cape
#

to put it to json format right? and the store it in a file

leaden ice
#

that doesn't make any sense, no

#

you don't put strings in json format

#

json IS a string

#

you take objects and put them in json format

signal cape
#

oh well i'm dumb

leaden ice
#

in any case you don't need to do any of this yourself

#

SaveBindingOverridesAsJson creates the JSON string for you

#

unless you're not using the input system?

signal cape
signal cape
hard viper
#

are IEnumerables generally lightweight to work with when I don’t need to save the whole thing to a list?

leaden ice
#

List is an IEnumerable

#

having an IEnumerable reference doesn't actually tell us the nature of the object

signal cape
leaden ice
signal cape
leaden ice
#

Why?

#

At least go to the latest 2021.3 LTS version

signal cape
hard viper
#

i understand, but let’s say that I store a List<T1>, and I want to mostly just enumerate based on and outputting fields in T1. Is making functions that give IEnumerable<T2> etc a more lightweight way to do this?

leaden ice
#

Then you'll be able to get newer versions of the input system package, among other things

signal cape
leaden ice
#

shouldn't be but as general practice ALWAYS make a backup and/or commit to version control before upgrading

hard viper
#

like, if T1 is a monobehaviour, and I want to iterate through the GameObjects, and don’t necessarily need to save a whole new list of GameObjects. Would making a method that returns IEnumerable<GameObject> be smart or no?

leaden ice
signal cape
leaden ice
hard viper
#

i’m thinking more about avoiding making a whole new second list (temporarily) for enumeration

#

which avoids allocation/GC

leaden ice
#

yes, but in that sense there's little difference between passing the existing list around directly as a List<GameObject> and passing it around as an IEnumerable<GameObject>

#

they are both just different views to the same object

hard viper
#

ty

#

In my case, I had a List of a class I didn’t want to reveal to outside world.

leaden ice
#

I do think it's a good idea to pass the list around as IReadOnlyList<GameObject> if you don't want scripts that receive the reference to tbe able to modify the list

#

i.e.

private List<GameObject> myList = new();
public IReadOnlyList<GameObject> PublicListRef => myList;```
hard viper
#

i was basically refactoring the Tree to use TreeNodes, and wanted TreeNode to just be internal to tree, while tree doesn’t expose that class at all

leaden ice
#

In that case You should/could make a public interface

#

which determines the exact API surface you want to expose to the outside world

#

and expose your objects as that interface instead of the actual class

oblique spoke
#

||/// <summary> Don't modify this! Use XYZ methods. </summary>||

old haven
#

Why is my gun pointing at my player and is so far away? (it rotates with the camera)
On the first pic u can see, it is right next to the player but when i start the game the gun is far away (pic2)

leaden ice
topaz gulch
#

If I want to make a 2d platformer using visual scripting, would I be limited in some way?

leaden ice
#

It's harder to express many things in Visual Scripting

#

but aside from those usual limitations, no.

topaz gulch
#

@old haven sure you wanted to tag me buddy?

old haven
#

lol my bad again

hard viper
leaden ice
#

one or both of those may be messing with its position

old haven
leaden ice
old haven
leaden ice
#

but yeah would need to know the components on all these

#

is there a Rigidbody for example

old haven
pearl ice
#

It's very likely that your model's pivotpoint is broken. With that many child components that might be the reason of your problem

leaden ice
#

that too ^ I notice tool handle position in the video is set to "Center". Press Z to toggle it to "Pivot" to see the real object pivots

pearl ice
#

Is the gizmo on top of your model when you choose it or somewhere else

leaden ice
#

this thing

#

Your PlayerNetwork script may also be at fault

#

it seems to reference the weapon xform so could be doing all kinds of things to it

old haven
#

@leaden icewhat was the side again where u can send the code?
also pivot doesnt work

leaden ice
#

as for code: !code

tawny elkBOT
old haven
leaden ice
#

this looks pretty damning

#

this combined with the above mentioned likely issues you have with your object's pivot explains the issue

leaden ice
#

the code?

#

No you should fix your pivot issues

#

although really why not just make the weapon a child of the camera instead of having that code.

leaden ice
#

your mesh's origin and orientation are way off as imported currently

#

Switching from Center to Pivot as described above will show you where your weapon's actual pivot is.

patent hound
#

so i'm having an odd issue with RaycastHit.point, it's working perfectly along the ground plane, but when hitting an object it's returning the correct position but with the y value always 0

leaden ice
#

Presumbly the hit point is correct.

patent hound
#

nevermind, rebooted unity while i was typing that message and now it works correctly

#

🤷‍♂️

leaden ice
#

"ruins everything" is hyperbole

#

handling errors in your code is a skill that you learn over time, and it's normal and not a big deal to have and fix errors as you grow more experienced.

swift falcon
#

https://www.youtube.com/watch?v=MyuZC40vNr4

anyone who knows perlin noise / unity can you please check this vid if the code is correct?

similar to diamodn square algorithm

https://www.youtube.com/watch?v=1HV8GbFnCik

In this video, we will create a perlin noise procedural terrain, using the Unity Mathf.PerlinNoise function.

▶ Play video

In this video, we will look at how to go at creating a procedural terrain using the Diamond-Square algorithm.

Custom Mesh video: https://youtu.be/UeqBwK27sV4

▶ Play video
rigid island
swift falcon
#

are different

eager fulcrum
#
var deathEffectParticle = Instantiate(_playerDeathEffect, player.transform.position, Quaternion.identity).GetComponent<ParticleSystem>();

var color = PlayersAndPoints[player].PlayerColor;
deathEffectParticle.startColor = color; 
deathEffectParticle.Play();
rigid island
eager fulcrum
#

NullReferenceException: Do not create your own module instances, get them from a ParticleSystem instance

#

im getting this error

#

why?

rigid island
#

then spawn it as ParticleSystem

leaden ice
#

but worth it

#

Life is pain

#

deal with it

swift falcon
hybrid turtle
#

very dumb question but I would like to edit animation keyframes in playable director however when I ijmported my animation from blender they're all grayed out and locked does anyone kno whow to unlock them

leaden ice
#

and modify the duplicate

hybrid turtle
swift falcon
#

sorry i dont know

#

i only know this

#

ama check google

sharp robin
#

Hello everybody,
I'm a relatively experienced developer with a bunch of engines, but not so much with the 2D part of Unity.
I am working on a simple 2D platformer with a mixture of 2D and 3D graphics. Unity seems a good fit for that.
I started working on a 2D character controller and faced issues almost immediately. There is no alternatives to the CharacterController for 2D. So I had to make a choice between using a dynamic RigidBody, a KinematicRigidbody or shape casting.
The game I am making is quite arcady and I want full control. I chose against a Dynamic Rigid body.
I chose to go with RigidBody2D.Cast because I thought it will work with the rest of Unity. I guess I am wrong.
The controller itself was easy to implement. But I can't seem to make triggers work with it.
At first they were blocking the body. I found a way to go around it with a contact filter. But now entering a trigger is simply not detected.
I found a few solutions online but they are either hacky or really inefficient (overlap in the FixedUpdate).

Is there a better way to do that? Also, if rigidbody.cast does not work with triggers are there any benefits over a shape cast besides being able to use multiple colliders per object?

patent hound
#

is there a performance difference between raycasting 100 units and raycasting math.infinity units if the object it's hitting is the same distance away?

leaden ice
low summit
#

hey yall im trying to follow this tutorial but im a bit confused on one of the steps

#

specifically when they begin making the overlay camera

#

is the game object they use to put the camera in like completely empty? how does it render the cockpit then?

rigid island
low summit
#

is the whole cockpit on a specific "cockpit" layer then?

#

like the base structure bottom left right screen top thing

rigid island
#

the cockpit object is set to cockpit layer and on cameras you can choose specific layer to hide (cull)

#

so you hide it on main renderer cam and show it on a separate cam

#

this is useful for many use cases

leaden ice
#

I just don't think people are going to commit to watching a video to answer a question here >_>

swift falcon
#

i mean its not watching just briefly seeing

#

but yeh ur right

low summit
#

so if im trying to implement some kind of UI that goes over the main camera

rigid island
low summit
#

ah i see mb

#

i thought this is where u ask questions

rigid island
#

code questions , yes

low summit
#

i seee

tribal gust
#

Hey there! Is there a place where i can find simple scripts like a car control script ?

simple egret
winged hull
#

I want to create a multi windowed game, such that one window shows the game, so that it can be streamed or whatever, and the other window shows the options/actions that interacts with the game. Is this possible to do in Unity?

rigid island
#

ofc

rigid island
#

oh wait you mean two separate monitors

#

in that case use this option TargetDisplay

#

if you mean two separate executables thats tricky but doable

leaden ice
winged hull
#

yeah i mean like two separate application windows, kind of like maplestory external chat, where they can be moved around separately

leaden ice
#

Separate application windows may require some native windows plugin shenanigans

lean sail
#

launch it twice then select which one is your main game and which is your external options/actions

eager fulcrum
#

Hey, can I somehow make player not affected by Global Volume Bloom?
I want only specific parts of the map to glow and not the player

rigid island
#

also not a code question

eager fulcrum
#

like this?

#

cuz it doesn't seem to work

rigid island
eager fulcrum
#

oke

swift falcon
#

i am literally following a tutorial tookekwait

fringe ridge
#

okay, i'm a bit confused 😄 I try to instantiate ui objects inside a scrollview content and set their position as needed. They are instantiated correctly, but somehow the position is absolutely not correct. The printed values are correct, but they dont match the rect transform position inside the content object.


leadPrefab.transform.localScale = Vector3.one;
leadPrefab.transform.localPosition = new Vector3(-30, 300 - i * 210, 0);
Debug.Log(leadPrefab.transform.localPosition);``` prints : -30, 300,0. Actually is -570,1000,0 (shown in editor.)
swift falcon
simple egret
#

Log the value, as well as the length of the collection you're trying to index with that

fringe ridge
lean sail
#

debug.log, not math log

simple egret
#

So you see the value of that monstrosity of a line

swift falcon
#

i forgot debug log exists

#

i didnt code for a while

simple egret
fringe ridge
#

ahh

#

okay

#

thanks dude, it works

#

completely forgot about the differences from rect transform and transform

swift falcon
#

there is 25 vertexes so the mVerts = new Vector3[mVertCount]; Has array size 25 so when we did mVerts[mid] which is 16 within the bounds

then wtf i am getitng out of bound error

swift falcon
#

i just checked the count in this iteration, vector3 array didnt change its length at all

wet gyro
#

hello guys, i need some help please.

i'm facing the following problem: i have those mixer groups, all the parameters are exposed. I have some snapshots with different audio values. I change the Music value in the game though the slider, but when I do this and the value is changed, it prevents the Music channel from being controlled by changing snapshots. The other values changes without problem but Music is the only disobedient one.

The formula in the code keeps the volume between -80dB and 20dB

swift falcon
swift falcon
#

this shit looks awful

i did the code correct but was there a change to random.generator by any chance

#

i suspect the issue is with random geenrator

split patio
#

what is the best way and easy way to make online game in the way players host it self like pair to pair ?

dusky lake
swift falcon
#

it should be smooth like this

swift falcon
#

bec i understood the code perfectly

#

from youtube

#

i reviewed many times

dusky lake
#

Looks like you most likely have the vertecies switched

#

from what your screenshots look like

#

in the tri order

swift falcon
#

ok i will check

swift falcon
#

doesnt seem to wrong

#

its 3am this thing still not done🥲 cant figure out the mistake

#

@dusky lake i am not figuring out how

cosmic rain
#

Either step through the code or print the first few vertices and their intermediate calculations.

swift falcon
#

i did for smaller values, its look right

swift falcon
cosmic rain
#

Yes

swift falcon
#

then what should i do

#

@cosmic rain i rmeoved shadows but does it loook right?

dusky lake
#

can you, just for a test, crank up the division count?

cosmic rain
swift falcon
#

true

swift falcon
dusky lake
#

M Divisions

#

put it x10 or something

swift falcon
#

it can be maximum of 128 , each of the mini square is considered mdivisions

rocky basalt
#

I'm trying to paste code, but it seems to have an asterisk that I've never seen in C# before, and it's causing errors. Hoping someone could explain what this is about.

leaden ice
#

it's possible they wanted to do samples * i though

#

in which case it's just the multiplcation operator

swift falcon
swift falcon
rocky basalt
leaden ice
rocky basalt
#

ah shoot sorry

scarlet juniper
leaden ice
cosmic rain
rocky basalt
swift falcon
#

i ahve been stepping through it for past hour , ig i will just sleep

leaden ice
cosmic rain
leaden ice
#

did you do waveform = Mathf.Abs(samples);? Why did you delete the subscript on the left side?

cosmic rain
rocky basalt
scarlet juniper
#

ever seen spaghetti

cosmic rain
#

I don't. But then what's the point of sharing an irrelevant script?

leaden ice
leaden ice
scarlet juniper
#

hatebin cannot handle my script it simply wont load

rocky basalt
#

It's a bit tricky because the thread suggests two methods. My original image was based on the second one

leaden ice
#

i mean you can understand what the error is saying right?

#

And why the code without that makes no sense, right?

scarlet juniper
leaden ice
#

waveform is an array

rocky basalt
leaden ice
#

with what code

rocky basalt
leaden ice
cosmic rain
# scarlet juniper https://hatebin.com/jvhgjmbjrp <@209684227720085505>

This is a very weird camera controller. Disregarding the Find in update, which is a horrible idea, the fact that you set the rotation of the camera separately from the player doesn't make sense. Also, rotating the player in the camera script doesn't make sense either.

Try disabling this script and just parenting the camera to the character.

Also, maybe just follow a fps controller tutorial...

leaden ice
#

you can't put that in Mathf.Abs

#

presumably you want samples[i] or something

rocky basalt
#

Yeah, I mean this is square one of why I was confused in the first place

#

they had samples*

leaden ice
#

yeah the formatting on that site is clearly very fucked

rocky basalt
#

yeah maybe samples[i]

scarlet juniper
rocky basalt
#

at this point i'm taking shots in the dark lol but thanks for trying to make sense of this

scarlet juniper
#

ill try disabling the script

leaden ice
#

which destroyed the formatting

cosmic rain
rocky basalt
cosmic rain
scarlet juniper
#

ive disabled the movement script and it still does itnotlikethis

cosmic rain
#

Movement or camera?

scarlet juniper
#

movement

cosmic rain
#

Disable the camera script as I suggested

scarlet juniper
#

oh sorry i misread

#

its still goingnotlikethis

#

so its def the movement

cosmic rain
#

Didn't you say that it was still happening after disabling the movement?

scarlet juniper
#

shit

cosmic rain
#

Disable both for a test

scarlet juniper
#

i will but then i cannot do anything

cosmic rain
#

But then it would probably confirm that it's one or both of these scripts.

#

In which case, as I said, go implement a basic controller first following a tutorial.

scarlet juniper
#

i have a short feeling its not the scripts

cosmic rain
#

What then?

scarlet juniper
#

ive disabled all scripts and i try to move my player trough the world and its glitching like that too

cosmic rain
#

How are you moving it?

scarlet juniper
#

just in the scene view

cosmic rain
#

Via the transform gizmos?
What other script do you have on or that reference the player/camera?

scarlet juniper
#

yes transform gizmos

#

lil axis

#

let me check because im unaware of any other scripts then these

cosmic rain
#

Is it not your project?

scarlet juniper
#

it is mine but i cannot remember putting anything on anything else

#

i have one more script on my feet transform but i doubt thats it

#

thats all on this one

cosmic rain
#

What's BaseMovement? Is it the movement script that you disabled?

scarlet juniper
#

yes thats the movementscript

leaden ice
scarlet juniper
#

iknow and its not used

#

thats why i forgot about it

leaden ice
#

This is saying "when I collide with an object that is NOT the ground, make grounded false"
What you actually want is "when I leave the ground, make grounded false"

cosmic rain
#

Okay. Take a screenshot of your character inspector and the whole editor window. As well as of your camera inspector with the whole editor window.@scarlet juniper

scarlet juniper
#

this is the player

cosmic rain
#

The whole editor window please.

#

I want to see the hierarchy too.

scarlet juniper
#

so just the whole screen

cosmic rain
#

Yes.

scarlet juniper
cosmic rain
#

Also, I can already tell you that rigidbody and CC combo is not a good idea. I'm not sure if it's the source of the issue, but it could be.

scarlet juniper
heady iris
scarlet juniper
#

what am i missing

cosmic rain
heady iris
#

The rigidbody and the character controller are going to be fighting over how to position the player

#

You must not use both.

scarlet juniper
#

ive deleted the cc and its still misbehaving in the scene view

cosmic rain
cosmic rain
scarlet juniper
#

its empty

scarlet juniper
#

i feel like im just annoying atp

cosmic rain
#

Hmmm

cosmic rain
#

Capsule collider

scarlet juniper
#

a second one? or just enable the first one

heady iris
#

Is this a collider?

scarlet juniper
#

its a trigger

#

so its not colliding with the main

#

it was for the old script that didnt make sense

cosmic rain
#

Disable that trigger and add a normal capsule collider to the rb.

spring creek
heady iris
#

I wouldn't expect dragging a rigidbody around to make you "lose your grip" like that

cosmic rain
heady iris
#

there is a capsule collider

#

it is disabled

scarlet juniper
#

there is yes

heady iris
#

although, it's also a trigger

cosmic rain
#

Ah right. I though that was the CC still

#

Enable it and make it non trigger

scarlet juniper
#

its a trigger yes cuz that one was going crazy with the collider from the CC

scarlet juniper
#

enabling and making it non trigger dont work either

cosmic rain
scarlet juniper
#

yes same thing]

cosmic rain
#

Did you disable/remove the box collider/trigger?

scarlet juniper
#

im going to disable the entire groundcheck which holds the trigger

#

no progress

heady iris
#

If so: create a cube, add a rigidbody, and see how it behaves.

scarlet juniper
#

the cube works fine

#

smooth

#

no weirdness

heady iris
#

What are Body and Cube doing?

scarlet juniper
#

its the cilinder and the 'forwardindicator'

#

both no colliders

cosmic rain
scarlet juniper
#

none

#

hol up hol up

heady iris
#

Deactivate children until the behavior changes.

cosmic rain
#

Also, are there any OnCollision/TriggerEnter/Stay/Exit in any of your scripts on the character?

#

Because these would run even if the script is disabled.

scarlet juniper
#

ive disabled everything but the cilinder and the camera and now it works smooth

#

i am so lost

heady iris
#

Well, then start re-activating things.

scarlet juniper
#

it is the... environment

#

the playspace

cosmic rain
#

I don't see it on the screenshots

#

Also, if it could just disabled the symptoms of the issue

scarlet juniper
#

so it is a performance issue?

heady iris
#

You still have a bunch of components that could be receiving physics messages

#

notably, your framerate is going from under 50 to over 50 when you turn off that volume component

#

Perhaps you have code that malfunctions if two physics updates happen between two frames

cosmic rain
scarlet juniper
cosmic rain
#

One thing that bothers me is that the capsule collider seems to be shivering a little bit...🤔

heady iris
#

That is very abnormal, yes

heady iris
#

Repeatedly declaring that you don't understand isn't going to get you any closer to understanding the problem.

#

It's weird, yes

#

You can share those scripts you have attached to the player, perhaps.

cosmic rain
#

That's what happens when you want everything at once, but not ready for it. Referring to trying your own "advanced" controller implementation+ using hdrp.

scarlet juniper
heady iris
#

you do not, no

cosmic rain
#

Try removing all the scripts from your character controller(could maybe duplicate the root object to preserve them), and see if the issue occurs.

scarlet juniper
#

there is not 1 script in the entire scene anymore and it still doesnt

#

everything is deleted no more scripts

#

its also 3:37 so my brain aint braining anymore too

heady iris
#

Look at it later

#

trying to diagnose a weird problem at 3:30 AM is a terrible idea

#

there's going to be something niche happening here

scarlet juniper
#

i have one more option. im draggin the entire world in there WO any colliders on the environment

#

if that dont work im gonna sleep

#

nope it dont work, welp ill get back to it tomorrow, if anyone is willing to help me

#

thanks for all the effort

cosmic rain
#

Most likely, the transform gizmos not moving it is unrelated to your original issue. This must be some issue with how unity syncs transform and physics in the editor during low frame rate.

scarlet juniper
#

yes im not too bothered by that but i am bothered with that awfull main issue

#

we'll see tomorrow, cyall and thanks again!

proven mauve
#

if an object is being rotated via a drag script is there a way to tell if it is spinning clockwise or counter clockwise? I figured I could take the Quaternion rotation of the previous frame/drag tick and compare it to the current one but haven't really found a way that returns a value that clearly tells if rotating one way or the other

dusky lake
#

It would be easier to check the drag values instead of the rotated object

leaden ice
#

should be very easy if you have access to the script

#

exactly - the script knows which way it's turning the object

proven mauve
leaden ice
dusky lake
#

yep sounds about right

leaden ice
#

if it's doing the rotation

#

it's hard to not be vague without seeing the existing code

proven mauve
#

The rotation is happening with Quaternion.AngleAxis()

leaden ice
dusky lake
proven mauve
# dusky lake yep sounds about right

I'll give this a try, I feel like I tried it before but I must messed it up. Think it should be as simple as checking if the x value is going positive or negative on that first drag

dusky lake
#

dont look for the first drag, minimal movement could trigger a false trigger

#

give it a threshold of some units

leaden ice
#

Else counterclockwise

#

Simple

proven mauve
#

Not really that simple because rotations are a nightmare. Where

Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
post = Input.mousePosition - pos;
rotationAngle = Mathf.Atan2(pos.y, pos.x) * MathfRad2Deg;
transform.rotation = Quaternion.AngleAxis(rotatingAngle, Vector3.forward);

Rotation angle will veer into both positive and negative values regardless of which direction you spin so it hasnt been a reliable way to tell which direction we're rotating the object

#

So I think I'll stick with looking at drag directions if possible

leaden ice
#

it was very unclear how the drag rotation was working before

#

so hard to give a good answer

#

I was under the impression it was something like dragging left/right and doing additive rotations

#

which is not the case

#

float diff = Mathf.DeltaAngle(previousAngle, currentAngle)

#

check if that's positive or negative

proven mauve
#

After trying many, MANY types of rotations, using AngleAxis was was the best way to rotate smoothly without awkward jumps when it reached 180 degree range and dealing with the previous rotation. eulerAngles were a hard no go

leaden ice
#

AngleAxis is not the question

#

it was about whether you were additively rotating or setting the rotation

leaden ice
proven mauve
leaden ice
#

read the doc

#

if you do DeltaAngle(180, -179) it will return 1

proven mauve
#

Did it say that on the doc? Guess I missed it?

leaden ice
#

Calculates the shortest difference between two given angles given in degrees

#

the shortest distance between 180 and -179 is 1

proven mauve
#

And then the doc proceeds to give an example with two positive values so that's kind of an assumption to make. "read the doc" given the example is pretty condescending lol

leaden ice
#

Try it out if you don't believe

#

anyway it does what you want

proven mauve
#

i do believe you

sweet raft
#

Can someone help me understand this?

private bool IsIdentifierStartChar(char c)
{
    if (char.IsLetter(c))
        return true;

    if (c == '_' || c == '$')
        return true;

    return false;
}

Will this not always return true, since the if statement is referencing the char being passed to the method?

quartz folio
#

why would it? What if you passed '#'

sweet raft
#

Would the very first if statement not basically then say if(char.IsLetter('#')...in which case it would return true, since that's what you passed it.

sweet raft
#

Okay. So I misunderstood the usage of IsLetter() apparently then. It's checking to see if the character IS A LETTER... It's not a comparative method.

#

My mistake.

fervent furnace
#

If the word start at _ $ or letter then it maybe a valid identifier

soft shard
fervent furnace
#

Btw you can just
return char.IsLetter(c)||c==‘_’||c==‘$’

hybrid turtle
#

hey Ive asked #archived-lighting but does anyone know here know of reflection probes ive been stuck on a small detail with them

kind grove
#

Hey developers. I'm coming to unity from Unreal. I have a value I want to be able to set from anywhere and have it persist between scenes, but not a static method because I want to be able to edit it at editor time. For Unreal that would be a value in the GameInstance. What about for unity?

#

From what I can tell I would want a gameobject that's marked Don't Destroy On Load, but I would need to ensure one exists on every level in my project?

lean sail
kind grove
#

@lean sail How do you ensure the object would be present in every level and avoid duplicates or absences?

lean sail
kind grove
#

Yeah, I want this to work even if I'm loading an arbitrary level.

#

Hmm, I was going to have each instance of the object check if it's the oldest and if not destroy itself, but that means I can't configure values across multiple scenes.

#

Sounds like I would need an editor script or something.

#

I'll do it manually for now and deal with the conflicts later.

lean sail
lean sail
kind grove
#

Think I found something

lean sail
#

Itll work across multiple scenes, the object in your new loaded scene will just destroy itself

kind grove
#

there's a UnitySingleton repo in Unity Community that uses the build system

sullen fern
#

Im trying to access child objects in a player character i have but i get this error

#

how do i fix it?

lean sail
sullen fern
#

im using animations and models from mixamo, and the mixamo rig object is under a gameobject i made

#

but the animations still play as normal

#

im doing some testing and that seems to cause that error

#

but the error pops up after i refresh the animator

#

when i click on some other object with an animator

lean sail
#

im unsure but this doesnt seem related to a code question then, maybe something got moved around in the hierarchy so your rig doesnt match 🤷‍♂️

sullen fern
#

yeah its not a code question, is there a differnet spot i should ask in?

#

and now the problem seems to be solved, but i think the error might happen again so still unsure

lean sail
#

oh it seems like they changed the layout

sullen fern
#

if i get the issue again ill ask in #🏃┃animation since thats probably the correct channel

#

thanks for the advice

delicate whale
#

Hello, is there a way to check for raycast on a non-convex mesh collider in Unity? I have a zone/district mapped out with a non-convex Mesh Collider (they are located above the terrain around 100 units) and I want to be able to detect in which zone/district I am with a raycast up from the player

#

I've tried raycast and sphere overlap but none of them work

swift falcon
#

how do i use memory profiler, i installed it but where do i go

silent shuttle
#

https://gdl.space/hajevacufi.cpp

I'm trying to create a square based mon isometric sprites that means that each sprite on the screen looks like a rotated pixel art tile i want it to allign correctly but right now it's not working

pseudo nymph
#

!code

tawny elkBOT
pseudo nymph
#

@silent shuttle

silent shuttle
#

ok

#

do you know a solution

pseudo nymph
#
  Debug.Log("So the code is formatted like this, and is easier to read"
pseudo nymph
silent shuttle
pseudo nymph
#

!code

tawny elkBOT
pseudo nymph
#

^^^^^^^

silent shuttle
silent shuttle
pseudo nymph
#

your problem description is vague, and full of difficult-to-read typos as well, might help the helper if you cleaned that up :D

silent shuttle
#

i want it to align like this basically

#

it's in a zigzag patern but i want them straight

#

mayb that makes more sense

reef garnet
#

I have a custom event system I've been working on and realised that my event listener will call all the game events in it's list rather than a specific one, any suggestions to improve this?

Event Listener:

public class GameEventListener : MonoBehaviour
{
    [Tooltip("Event Item")]
    public GameEventListenerItem[] eventItems;

    private void OnEnable() 
    {
        foreach (GameEventListenerItem eventItem in eventItems)
        {
            eventItem.gameEvent.RegisterListener(this);
        }
    }

    private void OnDisable() 
    {
        foreach (GameEventListenerItem eventItem in eventItems)
        {
            eventItem.gameEvent.UnregisterListener(this);
        }
    }

    public void OnEventRaised(Component sender, params object[] data)
    {
        foreach (GameEventListenerItem eventItem in eventItems)
        {
            eventItem.response.Invoke(sender, data);
        }
    }
}

[System.Serializable]
public class GameEventListenerItem
{
    [Tooltip("Event to register with.")]
    public GameEvent gameEvent;

    [Tooltip("Response to invoke when Event with GameData is raised.")]
    public CustomGameEvent response;
}

[System.Serializable]
public class CustomGameEvent : UnityEvent<Component, object> { }```
#

Game Event:

public class GameEvent : ScriptableObject
{
    public List<GameEventListener> listeners = new List<GameEventListener>();

    // Raise Event on all subscribed listeners
    public void Raise() 
    {
        Raise(null, null);
    }

    public void Raise(params object[] data) 
    {
        Raise(null, data);
    }

    public void Raise(Component sender) 
    {
        Raise(sender, null);
    }

    public void Raise(Component sender, params object[] data) 
    {
        for (int i = listeners.Count -1; i >= 0; i--) 
        {
            listeners[i].OnEventRaised(sender, data);
        }
    }

    // Manage Listeners
    public void RegisterListener(GameEventListener listener)
    {
        if (!listeners.Contains(listener))
        {
            listeners.Add(listener);
        }
    }

    public void UnregisterListener(GameEventListener listener)
    {
        if (listeners.Contains(listener))
        {
            listeners.Remove(listener);
        }
    }
}```
#

I have a custom event system I've been working on and realised that my event listener will call all the game events in it's list rather than a specific one, any suggestions to improve this?

The system is just these 2 scripts

#

Looks like this in the inspector

cosmic rain
torn eagle
#

Hey!! Would anyone happen to know if there's a way to programmatically check if headphones are plugged in or not on Windows and/or Mac? Or even a means to see if there are any currently connected audio devices. Documentation isn't giving me anything

reef garnet
cosmic rain
reef garnet
frozen sun
#

can anyone explain this?

ebon wing
#

Can anyone help me please, im trying to make it so when u die in my game it displays how manu coins you got as well as resetting the coins counter so when u press retry it is bacn in 0

leaden ice
ebon wing
#

i keep getting same error

leaden ice
#

So it's not showing errors

#

You should configure it first

frozen sun
#

i may be wrong however if it didnt actually exsist it wouldnt find it

leaden ice
#

Further proof it's not properly configured because it's seemingly unaware of your assembly definitions

ebon wing
frozen sun
leaden ice
#

Or maybe you just need to regenerate package files or something

#

The error is real though

ebon wing
frozen sun
frozen sun
leaden ice
#

Probably need to add a reference to your assembly

ebon wing
#

ok

frozen sun
cosmic rain
heavy smelt
#

Is it possible to do something similar to this picture but inside a Unity TextMeshPro Text Component ? I have a similar photo added between text segments like this : <size=95%><space=12.5em><sprite="mural" index=0></size> . I would like the picture to be bigger and to be able to be slided left and right so the user can see it completely.

somber nacelle
#

i'm no UI expert but i'm pretty sure you can't do that all in a single TMP_Text component, you'll probably need at least a ScrollView for that scrolling action. but you can always ask for help with setting up your UI in #📲┃ui-ux

dusky lake
#

I am doing my first project with the new InputSystem and would like to enable local multiplayer, I create an InputUser with _user = InputUser.PerformPairingWithDevice(Gamepad.current /* TODO: Device detection */); how do I now actually get input from that user? Usually I did with InputSystem.actions.FindAction(...) but that doesnt work on _user.actions

leaden ice
dusky lake
#

Nah, first project with the input system, not first one in general 😄

leaden ice
#

I know

#

Point stands

dusky lake
#

Ill take a look at those two tools, still, is it possible to get them similar to FindAction()?

uncut cape
#

is there anyway to detect the collision only once using raycasting?
i used bools to detect if it has been hit or not but it didnt work.
any other way?

somber nacelle
#

what do you mean by it didn't work? that should work just fine

uncut cape
somber nacelle
#

that doesn't explain anything

uncut cape
# somber nacelle that doesn't explain anything

well i tried to instantiate a particle effect when hitting an object tagged sth it kept instantiating them for ever this also happens when i use debugs , it keeps spaming it in the console for ever

somber nacelle
#

show the code

uncut cape
dusky lake
# leaden ice For your first project you should use PlayerInputManager and PlayerInput which h...

Is it possible in general at all to get them the same way? I promise I will try your suggested method first, I just want to test the available options, if it was purely local multiplayer, your solution would 100% solve my problem, thing is I network over steam and instead of sending the input from the player object to the network systems just to funnel the movement data back to the player i want to catch the movement data directly in the systems that handle sending the input, so if its possible, I'd like to atleast have a look what works better for me

uncut cape
somber nacelle
#

and where are you doing anything at all that would attempt to make sure you are not hitting the same object more than once?

uncut cape
#

wait i will try again and show you

somber nacelle
#

also if you want to hit everything in the line, why not just RaycastAll instead of recursively raycasting if you hit something?

#

why are you using a 3d raycast for 2d?

uncut cape
#

but is that the problem?

heady iris
#

then you'd better start telling that story

somber nacelle
uncut cape
#

the objects are cubes

somber nacelle
#

why

uncut cape
#

why not

#

it worked better

heady iris
#

perhaps because you were doing something fundamentally wrong with the 2D colliders

uncut cape
#

it worked

#

but not as well as i wanted

heady iris
#

and what was the problem?

heady iris
#

This does not tell me anything.

uncut cape
somber nacelle
#

holy shit dude

uncut cape
somber nacelle
#

if you're not going to actually answer questions, don't expect to get help

uncut cape
#

i told you what happnes

#

and the code

heady iris
heady iris
#

in case it is unclear: I am asking why you decided you have to use 3D colliders

uncut cape
heady iris
#

Okay. That is a reasonable explanation.

hard viper
#

2D and 3D engines are super different

heady iris
#

not a very long story, now is it

hard viper
#

and do not communicate with each other

somber nacelle
#

but anyway, i've already suggested a solution to your issue

somber nacelle
hard viper
#

do you mean you only want to raycast once, and return 1 result?

somber nacelle
#

i hope you also realize that doesn't really show what you are trying to fix

heady iris
#

You are not communicating very clearly. I can't see anything "wrong" with that screenshot.

hard viper
#

yeah. you just need to implement the behaviour

heady iris
#

Take two minutes to compose a clear explanation of what is wrong.

uncut cape
#

that is supposed to happen only once

#

not for ever

hard viper
#

you mean there should only be one yellow dot?

#

i feel like I’m playing charades with code

uncut cape
#

thats it

heady iris
#

Okay. That is your problem: the code that winds up spawning particles is running more frequently than it should.

hard viper
#

oh, so this is a VFX issue

somber nacelle
heady iris
#

Good point.

#

Perhaps it's not a code issue at all.

#

I think Rad said that the console was "getting spammed"

uncut cape
hard viper
#

VFX graphs use visual scripting, so still technically code

#

but not a C# code issue, potentially

uncut cape
somber nacelle
hard viper
#

first, are you using a VisualEffect component, with VFX graph?

somber nacelle
#

they are using a ParticleSystem

#

so neither

heady iris
#

Verify this before you continue. See if there are many particle systems or if there's just one particle system.

#

To solve a problem, you must have information.

hard viper
#

idk much about using particle system without vfx graph, so I need to dip

uncut cape
#

was for the collision detection

somber nacelle
#

you should unfold the scene in your hierarchy so you can actually see how many particle systems there are

uncut cape
#

but thats the problem i think

heady iris
#

You must replace "I think" with "I know".

heady iris
#

When I am debugging bad behavior, I try to rule out as much as possible.

uncut cape
#

sorry i got disconnected

heady iris
#

Okay, so now you've confirmed that you're spawning way too many particle systems.

somber nacelle
uncut cape
#

i misunderstood

heady iris
#
        else if (hitInfo.collider.gameObject.CompareTag("Mirror"))
        {
            Vector3 pos = hitInfo.point;
            Vector3 dir = Vector2.Reflect(direction, hitInfo.normal);
 
             GameManager.instance.SpawnHitParticle(hitInfo.point);
           
            CastRay(pos, dir, laser);
        }

I presume this is the offending code. You reflect the ray with the hit normal and then cast it again.

#

I wouldn't be surprised if you were just hitting the surface again and again

#

I would suggest logging the hit point and normal to give you some more information.

#

But, assuming that's the cause, you will probably need to add a little bit of "wiggle room" so that the raycast doesn't just smack into the surface again.

#

You could move the origin slightly.

#

Although, actually -- if it was doing that, I'd expect infinite recursion that crashes your game.

#

It's more likely that it's just spawning a new particle system every frame and building up a huge pile of them.

#

Verify this. Pause the game and watch what the hierarchy is doing as you advance frame-by-frame.

uncut cape
#

should i try destroying it?

#

i used the same with the laserbeam object

heady iris
#

Destroying the particle system would mean that the particles don't get to spread out.

#

I'd have to think about that for a minute.

#

One option would be to spawn many particle systems, but have each particle system only spawn a few particles

#

and then die after a few seconds

#

Another would be to move the same particle system from place to place (after setting it to use world space, so that the particles don't follow it)

heady iris
#

You'd have way more particle systems in total.

#

The VFX Graph would actually be pretty useful for this situation. You could just have one Visual Effect component that you ask to spawn sparks wherever the ray hits

uncut cape
heady iris
#

If it gets too heavy, you can always slow down the rate that you spawn particle systems at

uncut cape
#

i have no idea how to do that

heady iris
#

the Particle System component has an option to destroy itself when all of its particles are gone, iirc

dusky lake
# dusky lake Is it possible in general at all to get them the same way? I promise I will try ...

Figured it out

    public class PlayerView : MonoBehaviour
    {
        private InputActionAsset _inputActions;
        private InputUser _user;
        private InputAction _moveAction;
        
        private void Start()
        {           
            _inputActions = InputSystem.actions;
            _user = InputUser.PerformPairingWithDevice(Gamepad.current);
            _user.AssociateActionsWithUser(_inputActions);
            _moveAction = _inputActions.FindAction("Player/Move");
        }

        private void Update()
        {
            var v = _moveAction.ReadValue<Vector2>();
            if (v == Vector2.zero) return;
            
            Debug.Log(v);
        }
    }
somber tapir
#

You could also only have 1 particle system and make it follow the impact position

scarlet juniper
#

Fen and dlich i think im going to restart the entire movement unless you want to fix it i feel like that redoing the movement would be faster then solving the issue

lusty vine
#

maybe a simple one - is there an accepted / best practice way to set an environment name (development, staging, production) for a client (eg unity desktop) build? tried a custom build script to accept env name as an arg at build time and set it to a class that hopefully was going to be read at runtime, but of course, that value doesn't persist at runtime bc the vars are reinitialized to defaults.

is there a place in project settings.asset i can stick an env name? i thought about appending a char to build version, e.g. 1.0.1d (dev), 1.0.1s (stage) ...

heady iris
#

I have not done this before, but perhaps you can generate a TextAsset at build time that contains the string you want

#

I'd probably just stick it on the end of the version string

steady moat
lusty vine
heady iris
#
#if florp
  public static thingy = "foo";
#elseif blarp
  public static thingy = "bar";
#else
  public static thingy = "baz";
#endif
#

That member is guaranteed to exist, but its value will vary

#

I was originally thinking of using defines directly, but C# doesn't do that, iirc

#

(i.e. doing #define BUILD_KIND "Release" like you would in C)

lusty vine
steady moat
lusty vine
#

looking like i'm going to use a prebuildaction e.g.

using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;

public class PreBuildActions : IPreprocessBuildWithReport
{
    public int callbackOrder { get { return 0; } }

    public void OnPreprocessBuild(BuildReport report)
    {
        // Load the ScriptableObject
        GlobalSettings settings = AssetDatabase.LoadAssetAtPath<EnvironmentSettings>("Assets/PathToYourScriptableObject/GlobalSettings.asset");
        
        if (settings != null)
        {
            settings.EnvironmentName = (populated from arg passed to build)


            // Make sure to save changes to the ScriptableObject
            EditorUtility.SetDirty(settings);
            AssetDatabase.SaveAssets();
        }
    }
}
steady moat
ebon wing
#

anyone know why this is here; in visiual studio it has no problems with my code but it still says this for some reason

vagrant blade
#

Beacuse that's a null reference, which happens at runtime. Your code won't have an issue with it until it becomes a problem.

#

So whatever is on line 30 is referencing something that doesn't exist.

opaque ledge
scarlet notch
#
moveDirection.y = movementDirectionY - gravity * Time.deltaTime;
moveDirection = (forward * curSpeedX) + (right * curSpeedY);

swap these lines around

#

you're setting the gravity, then immediately overwriting it

scarlet notch
#

no probs!

thick socket
#

how can I get a gameobject thats a child thats named "laser"

heady iris
#

sounds like you should be putting a component on this object called "Laser Holder"

#

rather than just searching for something by (child) name

scarlet notch
thick socket
scarlet notch
#

but @heady iris is right, searching each time you want it isn't great

heady iris
thick socket
#

should only grab it once at startup

heady iris
#

Why do you need a parent object? Is the player rotating this object, perhaps?

#

In that case you definitely want to create a component that represents "a thing you can rotate"

scarlet notch
#

not sure why the ❎ , that's literally how it would be done, regardless of other solutions

leaden ice
#

bad practice to reach into the innards of other objects

scarlet notch
#

agreed

thick socket
#

so its better to create an empty class and search for that object instead?

heady iris
#

you don't want to depend on the exact hierarchy and naming

#

Explain your use case.

heady iris
thick socket
#

need to grab to disable/enable it at certain times

heady iris
#

now we need to hear the "X".

#

what does this parent object represent?

#

what is it?

thick socket
#

I'll just grab the laser from another script that already has it serialized 🙂

heady iris
thick socket
#

Lasers is a parent that has 3 children that make up the laser

heady iris
#

then you should really have a Laser component

#

something that lets you reason about this contraption without caring about exactly how many children it has and what they're named

thick socket
#

so I should have

public class lasers{
//this class is empty}```
scarlet notch
#

another alternative, if the laser will always be there, you can also define it as a public GameObject Laser in the class you want to use it in, and drag the correct gameobject into it on the inspector

heady iris
#

no, you should have a class like

#
public class LaserEmitter : MonoBehaviour {
  public LaserSource source;
  public SomeOtherPart anotherPart;
}
#

i don't know how this is set up

thick socket
#

why

#

I have no need for anything except the gameobject

heady iris
#

if you want to disable the laser source, now you can directly access it and turn it off

#

you can also do other useful things, like set its color or change its max range

#

or whatever else you might do in your puzzle game

somber tapir
#

You should move the code that belongs to the Laser into the Laser script, I assume shooting a light beam and all that stuff

heady iris
#

GameObject references are rarely the right choice. They give you very little information and are very easy to mess up.

#

since you can drag literally any game object into the field

#

if you reference a LaserEmitter, you can only assign a laser emitter into that field

thick socket
heady iris
#

and you can easily do things to the laser emitter

thick socket
#

just shows where you are aiming

#

or enemy aiming

heady iris
#

instead of having to search for random components and children

rigid island
heady iris
#

There's nothing stopping you from having a big pile of GameObject fields, but you'll also find yourself making more mistakes

#

I prefer to get rid of as many ways to make mistakes as possible.

#

(i already have enough as-is)

rigid island
#

at most I use a Transform field just by principle

heady iris
#

yeah

#

if I actually want a Transform, I use a Transform field

#

I use that to mark where to attach UI elements, for example

#
public Transform itemHolder;
#

in this case, I really do not have any thing more specific in mind than a Transform

#

it's a conceptual match

#

public GameObject verySpecificKindOfThing; is bad

thick socket
#

whats the use in grabbing transform if I just want to setactive

heady iris
#

I think you want to turn the laser on and off

#

Is that correct?

thick socket
#

yep

heady iris
#

Then make your code do that

thick socket
#

that would be gameobject.SetActive(true)

rigid island
#

just make a laser script

heady iris
#

It might, under the hood, just deactivate the game object

#

But now your code is much more clear

#
laserSource.TurnOff();
#

or laserSource.emitting = false;

#

This code turns off a laser

scarlet notch
#

agreed, if you have your laser script just have a public void ActivateLaser(), for example, the other places that use your code won't need to be changed if y ou decide that it will do more than just activate the gameobject

heady iris
#

It's very obvious what it does, and it can't possibly be turning something else off

heady iris
#

and you probably will decide this at some point

#

maybe you want to "break" the laser until the player performs an action

#

if you just directly activate the laser's game object, you're going to have to change every single place you do that

scarlet notch
#

or spawn some particle effects, etc

heady iris
#

to make sure the laser isn't broken

#

encapsulation makes your life so much easier

#

I'm making some sweeping changes to how a game I last touched 6 months ago works

#

but because most of the details are encapsulated, it's been remarkably easy

#

The player now takes a few frames to spawn because I have to additively load a scene or two first

#

all I had to do was change the one place that deals with telling everyone that the player now exists

#

if I had lots of Transform.Find("Player") all over my code, it'd be a nightmare

#

(and it'd break, because the player's name changed)

#

I have components whose sole job is to reference other components

#

Components are cheap. Your time isn't.

scarlet juniper
#

@heady iris @cosmic rain LMFAO i got it to work and im actually devestated that this was the issue after doing all that major work

heady iris
#

...huh, interpolation did it?

#

That's really weird.

#

I guess it could malfunction if you were setting position and rotation outside of FixedUpdate

#

since the interpolation would be trying to apply during Update

#

That could be it.

scarlet juniper
#

i guess so but ngl interpolation was the last thing i'd think about

heady iris
#

yeah, it didn't jump to mind

#

but it makes sense in hindsight

scarlet juniper
#

i tried creating a new character controller and after turning on interpolation it did that weird thing

heady iris
#

You saw the behavior change when going below 50 fps

scarlet juniper
#

i was like hol up

#

yeye so it was not a performance issue what im thankful for

heady iris
#

I might try reproducing this later

scarlet juniper
#

it has very low impact to the camera script on itself, however when i enable the movement script i just created it starts again with those huge spikes

#

let me throw the script in here for you to utilise

main coral
#

Hello maybe someone can help me here. Im using Unity Gaming Services Authentification and implemented the register with username / password. All is working fine. What is the best place to safe the Username ? Maybe I can search on dashboard with name and not with playerid .. ?

thick socket
#
        laser = fighter.GetComponent<LookAtEnemy>().laser?.gameObject;
#

throwing error when laser is null...did I put the ? in the wrong place?

#
        laser = fighter.GetComponent<LookAtEnemy>()?.laser.gameObject;
``` this also didn't work
#

I got around it another way...but still confused on why this doesn't work

pearl ice
#

simply add an if statement to check if the laser is null

#

call this only when laser is not null

thick socket
#

I "should" be able to use the ? somewhere to avoid having to add another if statement iirc

knotty sun
#

? and ?? do not work correctly on Unity Objects. The docs are pretty clear on this

hard viper
#

unity overloaded == null to check for object destruction