#archived-code-general

1 messages ¡ Page 209 of 1

marsh mesa
#

luckly i only have 2 states, so it isnt a big deal in my case

lyric atlas
#

Sorry, was trying too but it felt more convoluted:

I have a specific method where velocity is calculated in my actor controller and I wish to add more calculations inside it (rather than calculate outside and use a setter on the velocity).
A simple example would be if I handle movement inside the velocity update, but I want to handle jumping in a separate script but have that jump script's calculation be called during the main velocity update. I'd rather not hard code the call as I'd like it to be useable with a variety of scripts I can just add to my gameobject

dusk apex
#

Could probably do some event subscription and process everything inside the method 🤔

lyric atlas
cold parrot
lyric atlas
#

nevermind

#

yeah saw components :P

#

ta v much

cold parrot
#

those components could also be SOs you drop into a list or anything else really, even a list of delegates or c# objects

lyric atlas
#

unity events would work too I suppose? but think interfaces would be more my jam

cold parrot
#

no, unity events dont return values

lyric atlas
#

don't need to return values if the parameter passed has the ref keyword though?

cold parrot
#

what basically want to do is pass a data object/struct through a series of filters

#

thats called Pipes & Filters architecture

lyric atlas
#

ahh

cold parrot
#

1000 ways to actually implement it, the key idea is the unified API between all of them, always operating on the same data structure

lyric atlas
#

what would be the advantage to doing SO's instead of interfaces? is it that the SO's can have their own variables too

cold parrot
#

if you want to configure those filters, with a SO you can reuse configurations

#

use of interfaces is orthogonal to the use of SO/Component

swift falcon
#

any resources for learning CSharp and improving as a programmer?

cold parrot
#

you just can't assign interfaces in the editor and have to query them via script, but just like SOs you could also assign the compoents to a list

cold parrot
# swift falcon any resources for learning CSharp and improving as a programmer?
lyric atlas
cold parrot
lyric atlas
#

as in you have a list of the interface and set the scripts?

#

mb probably a dumb question

cold parrot
#

you can only do that in code

#

Example: `

private List<IFilter> _filters;

void OnEnable() {
    _filters = GetComponents<IFilter>().ToList();
}
plush ridge
#

Hey guys, I have a script that has the "OnTriggerEnter" function in it, however the object the script is attached to can't have a collider on it - however, one of it's children does. How would I make OnTriggerEnter use the child collider instead of looking for a collider attached to its own parent?

lyric atlas
lyric atlas
unkempt kindle
#

Hey, I just found out you cannot use constructors in a monobehvaior class which is giving me a hard time to wrap my head around this.
I have a script GameManagement that controls a bunch of services through interfaces (i.e. _saveManager interface for SaveManager service)
Usually I would just ctor it GameManagement(ISaveManager saveManager){_saveManager = saveManager} however this is not allowed.

How do I keep the clean architecture of using services/interfaces but allowing the game manager to interact with those services given the Monobehavior limitation?

heady iris
#

One option is to give the class an "init" method

#

Which will (roughly) work like a constructor

#
var myFlorp = Instantiate(florpPrefab);
myFlorp.Init(importantInformation);
unkempt kindle
#

But that just instantiates my GameManagement class no? the problem is that I have list of services that I want GameManagement to call

#

am I able to make a public script declaration and just drag the interface onto an empty GameManagement Object? Or will that cause some other issue?

#

oh, apparently you cant attach scripts to a component either?

summer oar
#

may I ask why

UnityException: DoTryParseHtmlColor can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
UnityEngine.ColorUtility.TryParseHtmlString (System.String htmlString, UnityEngine.Color& color) (at <f712b1dc50b4468388b9c5f95d0d0eaf>:0)
UI.Theming.ThemeLoader.LoadColors (UI.Theming.OperatingSystemTheme+ThemeEditor editor) (at Assets/Scripts/UI/Theming/ThemeLoader.cs:222)
#

Why does parsing an html color code need to be done on the main thread

summer oar
#

Okay so I'm not the ONLY one head-desking

#

yknow every time I think of the runtime fee stuff from September, I...think of these weird quirks and just kinda go

#

why

leaden ice
#

My guess is that this particular function is most likely simply an oversight

#

there is some attribute or macro they apply to make native functions "main thread only" and it's on this one by accident

#

You can probably try reporting it as a bug

#

expectation: parsing an HTML string should be possible on a background thread
result: it is not

summer oar
#

If I had the time to fill out a bug report for this stuff, they'd have 50 bug reports every day from me when I close the editor and it decides to crash because I closed it

#

I don't know what's up with 2021 LTS but it loves crashing on exit

#

anyway

leaden ice
#

If they don't know about it they're not likely to fix it ¯_(ツ)_/¯

vivid wind
#

I published custom C# project into my Unity Assets folder. The custom assemblies are working, but they depend on Microsoft Dependency Injection dlls. Any idea why they would be erroring out in the editor saying they can cause crashes? "Unloading broken assembly Assets/GuildLegendsPrototype/Unity/References/Microsoft.Extensions.DependencyInjection.dll, this assembly can cause crashes in the runtime"

heady iris
#

I am having a very weird problem with a package. None of its scripts appear to be importing correctly.

It's just this package. Other packages (including a companion to SuperUnityBuild) work fine.

#

No compile errors right now.

#

I'm gonna hit this with the "delete the Library" stick and see what happens

vivid remnant
#

When I "carry" an interactable object, its direction and speed get calculated in order for it to travel to the hold position by changing its velocity directly. Everything works fine but when the interactable gets to far, it starts jittering. The player character moves using a Character Controller component and the interactable move using a Rigid Body component.

The source code can be seen by accessing the link below:
https://pastebin.com/X0Yw4Aye

#

Could you please help me understand why the jittering occurs?

scarlet kindle
#

I'm trying to play a typewriter sound as I make a typewriter effect in a for loop, something about the Audio Source isn't allowing the clip to play at this frequency (0.016sec/char)... the audio clip is shorter than this time. Is there some way to allow the Audio Source to play at a higher frequency? It beeps intermittently but not at the speed it's printing each character

                    // typewriter.Stop();
                    typewriter.Play();
                    text.text += charArr[i];
                    yield return new WaitForSeconds(timeInterval);
                }```
simple egret
heady iris
hard viper
#

When you have a joint, is there a difference between (joint on A, connecting body B) and (joint on B, connecting body A)?

vivid wind
scarlet kindle
simple egret
#

Audio source shenanigans

#

It also does it with animations sometimes, even if the animation is shorter than the rate at which you transition to it, it'll sometimes skip the animation entirely

scarlet kindle
#

ahhh fun stuff

#

ok well, good to know thx for the help!

heady iris
#

I wouldn't be surprised if the audio source only decided that it was done playing after the next update

pure garden
#

any idea on why slerp doesn't work on 2d? its just normal lerp

time += animationMult * Time.deltaTime;
transform.position = Vector3.Slerp(new Vector3(transform.position.x, transform.position.y), new Vector3(0, 0), time);

i think it might be using the z axis as the rotation but there's no point in that since its a 2d game

heady iris
#

slerping to 0,0,0 is weird

#

i guess it should just behave like a lerp?

pure garden
heady iris
#

Can you give me a drawing showing the motion you want?

pure garden
#

wait youre right if i do vector2(2, 2) it works

pure garden
heady iris
pure garden
heady iris
#

the sphere rotates and resizes so that this point is at the destination

#

so, if you slerp to zero, the sphere is shrinking to a tiny point

pure garden
heady iris
#

If you can pick a pivot point, you can do something like this

#
Vector3.Slerp(start - pivot, end - pivot, t) + pivot;
rain minnow
heady iris
#

I'd have to think for a moment on how to pick that pivot

heady iris
#

There's probably a clever formula for that.

#

There will be many solutions.

pure garden
#

x=3+0/2
y=4+0/2

#

i mean thats the center

#

you can just draw a circle with r=2

heady iris
#

That would spin you 180 degrees around the median point

pure garden
#

from there

heady iris
#

If that's what you want, then that'll work

#

I was thinking of a shallower arc

#

e.g. moving from the cross to the dashed circle

pure garden
#

yh that works better

#

uh

heady iris
#

I guess the player and the origin form a chord

#

The tricky thing is that there are many valid choices of circle. This is a much larger circle that passes through both points

pure garden
#

yh i think i found it out

#

ty

heady iris
#

Any point that's equidistant from the start and end would work, I think

#

because that, by definition, makes a circle

modest jay
#

Hi I am trying to create a UDP server but I get this "error SocketException: An invalid argument has been provided" These are the scripts I am using for server and client https://hatebin.com/espjasneqd

The client script line 40 "recv = newSocket.ReceiveFrom(data, ref Remote);"

young sage
#

Unity gets stuck recently after adding Editor/Play Mode tests to my game.

modest jay
hybrid turtle
#

Hi I have this script in which I call StartCoroutine in Start()

#

for some reason it doesnt play the reverse animation

#
    {
        if (_timeline.time.ApproximatelyEquals((float)_timeline.duration)) // check if the duraation is the same 
        {
            yield return new WaitForSeconds(delayTime); 
            _timeline.ReversePlay(); 
        }
        else if (_timeline.time.ApproximatelyEquals(0))
        {
            yield return new WaitForSeconds(delayTime); 
            _timeline.Play(); 
        }
    }```
rigid island
leaden ice
leaden ice
hybrid turtle
#

is what I've been trying to do

leaden ice
hybrid turtle
#

ok thank you I'll give it a shot

#

will something as smiple as

#
    private IEnumerator FlipAnimationCoroutine()
    {
        _timeline.Play(); // start playing the time_line 
        while(!_timeline.time.ApproximatelyEquals((float)_timeline.duration))
            yield return null; // wait and return here 
        
        _timeline.ReversePlay(); 
    }```
#

work

#

this doesn't seem to add up either sorry newer to using coroutines

leaden ice
#

this will play once, then reverse play once

hybrid turtle
#

it doesnt even reverse play

leaden ice
#

then likely while(!_timeline.time.ApproximatelyEquals((float)_timeline.duration)) the condition here is never true

#

What is _timeline?

hybrid turtle
#

its a PlayableDirector

#

I made the ApproximatelyEquals function

#

and bound it to a static instance

#

of PlayableDirector

#
    {
        return Mathf.Approximately((float)num, other); 
    }```
#

this is approxEquals

leaden ice
#

using the time seems sketchy

hybrid turtle
#

yes its sort of tricky I could just emit a signal at the end

#

may just send a signal

#

I see the issue

#

it reaches duration for an instant

#

then resets to zero

#

ok got it to work but now sorry but now I want it to loop infinitely

#

like keep bouncing back from playing forward to reverse

#

I tried wrapping in while(true) as a guess but obviously doesn't work

static matrix
#

I can't figure out why this code is reading null

rigid island
#

which code

static matrix
#
reader = new StreamReader("Data.txt");
        Debug.Log(reader.ReadTargetLine(SpriteLine));
public static string ReadTargetLine(this StreamReader reader, int LineNum)
    {
        for (int i = 0; i < LineNum; i++)
        {
            reader.ReadLine();
        }
        
        var dat = reader.ReadLine();
        reader.Close();
        return dat;
        
    }

(Spriteline is a const set to 6)

613203
-0.09999934
-2.935
0.4378958
0.7441553
0.9984701
0

file being read
everything else works

latent latch
#

is the variable null or is it empty

static matrix
#

null
its printing this

#

wdym

#

the nullexception was the next line where I try to parseint from it

mossy snow
#

did you read the documentation for ReadLine?

leaden ice
leaden ice
static matrix
#

thats probably faster too

#

I'll switch to that

rigid island
#

how does ReadAllText deal with large files?

leaden ice
#

it loads the whole file into memory as a string

rigid island
#

oh ok so larger files is better to use readline with stream

heady iris
#

even a few megabytes of text data should be completely fine

#

computer fast

#

vroom vroom.

vivid remnant
#

I have a base class called Mobile that includes methods for interactive objects that move such as doors and elevators. This class is inherited by Linear(e.g. sliding doors) and Rotary(e.g. hinged doors). The class Linear is inherited by a class called Transporter(e.g. elevators). I wanted to be able to create custom doors so I made a procedural object. I made a class called EditorMobile that inherits from Editor and it targets the Mobile base class.

The problem is I only want the editor class to replace only the inspector GUI of the Linear and Rotary class but not the one of the Transporter class.

Is there a way to do this?

#

This is how the Inspector GUI looks after being modified by the EditorMobile class.

hybrid turtle
trim rivet
#

Can anyone help me figure out why this line works in editor but not in build?

#

Seems like I cannot change the mesh of a mesh collider at runtime... which is crazy, why wouldn't this be possible ?

#

I cannot set read/write enabled because it is a cheld object inside an fbx, and so when I set read/write enabled in the import settings it only affects the parent object

hybrid turtle
#

cant you use the same collider and only change the mesh in it. I believe you should be able to do that or alternatively you can most definitely add components at runtime and remove them so get reference to both colliders and remove the the mesh you don't want and add the one you do

#

just the best way I could think of it

hard viper
#

I'm not getting what I think I should be getting from friction. I assigned material with friction = 1 to both rigidbodies, but when a kinematic platform moves left and right, the dynamic rigidbody on top of it doesn't move at all. Am I missing something here?

#

do kinematic RBs just not have friction?

cold parrot
#

Standard friction in unity is a game of trial and error. It can’t really be used to make objects stick to moving platforms. It’s basically just for approximately simulating the idea of ‘diffusion/transfer of energy’ on contact

hard viper
#

i don’t expect friction to move the kinetic RB, but I do expect the moving platform to transfer at least some force to the dynamic RBs on top of it

hard viper
cold parrot
ebon apex
#

!code

tawny elkBOT
ebon apex
#

    void Update()
    {
        //draw the line of sight raycast cone
        float stepAngle = coneAngle / rayNumber;
        for(int i = 0; i < rayNumber; i++)
        {
            float angle = transform.eulerAngles.y - coneAngle / 2 + stepAngle * i;
            Vector3 direction = Quaternion.Euler(0, angle * 0.5f, 0) * gameObject.transform.forward;
            Ray raye = new Ray(transform.position,direction);

            if (Physics.Raycast(raye, out hit, coneRadius))
            {
                Debug.DrawLine(raye.origin, hit.point, Color.red);
                if (hit.collider.CompareTag("Player"))
                {
                    player = hit.collider.gameObject;
                    detected = true;
                    lineOfSight = true;
                }
            }else
            {
                Debug.DrawLine(raye.origin, hit.point, Color.green);
                lineOfSight = false;
            }


        }
hard viper
slate fern
#

Is it possible with the InputManager(the old one) to make a key rebind at runtime especially when using things like GetAxis?

dusky lake
dusky lake
lean sail
# ebon apex ```cs void Update() { //draw the line of sight raycast cone ...

the calculation you are doing here for angle seems off. You are rotating the vector transform.forward by the Quaternion you are constructing, but you're also constructing it based on the transforms rotation.
Plus raycasts for line of sight isnt reliable once you start letting them see far, the lines will spread too far apart. If you add more raycasts to counteract the issue, its just a bandaid fix. I would use an overlap sphere then check the angle compared to its transform.forward. Then you can raycast once to see if the object is blocked by anything

slate fern
dusky lake
ebon apex
slate fern
dusky lake
#

All the Input.GetKey[...] methods will stop working

#

Depending on how much you use stuff I'd say 20 minutes intro video + reworking the code

#

But unless you are just using WASD for a platformer and only that, it will save you a LOT of time in the long run

floral kiln
#

Guys, are UTC dates unique?

#

Like let's say I have a list of entries and when they were submitted, but I forgot to add IDs to each of them.

#

In the meantime, is using their UTC timestamp enough?

#

Each entry has a UTC timestamp of when it was posted (and no 2 are posted in the same second).

leaden ice
#

If no two are posted in the same second then naturally they won't have the same timestamp

#

How do you not have an ID though? Where do these entries live?

#

At the very least you have either the index in the list or just the object ID

heady iris
#

i sure hope that timestamps from different times are unique

#

they'd be very bad at doing their job otherwise

floral kiln
#

That's what I hope too

#

But I guess they are meant to be

#

I didn't fully grasp that part, but now I do

#

And this timestamp also has millisecond in it, so even if by some chance, 2 got posted in the same second, it's still unique

leaden ice
floral kiln
#

Gotcha, so that does make it easier

leaden ice
#

Anyway couldn't you just write a quick loop to verify their uniqueness?

floral kiln
leaden ice
#

Where are you storing these things?

floral kiln
#

I pull them as JSON objects from a server, and load them into Unity. Parse them as certain class objects, and then put them in a list and draw them, and users can manipulate their order, and all that.

#

And then save it back to server.

leaden ice
#

Write a quick tool to iterate over them and give them IDs

floral kiln
#

But the timestamp as an ID helps me maintain this

floral kiln
leaden ice
#

Yes

#

Only once though

floral kiln
#

I will eventually do that in the next few days, but needed a quick solution for now to maintain funtionality

leaden ice
#

Is this in Firebase or something?

floral kiln
#

The server is a javascript program I wrote hosted on AWS

#

and acts like Cloud Functions of Firebase

#

but AWS version

leaden ice
#

Where is the server storing the data

floral kiln
#

Dynamo

#

Dynamo is finnicky, I can't just easily edit everyone's entries and include a new property

leaden ice
#

Ok and dynamo requires a key for every document, no?

floral kiln
#

I can do that through code as you suggested above

#

the key is the user itself, and the value is their list of entries

leaden ice
#

So you can also use the (user id, order in list) tuple as a guaranteed unique key too

floral kiln
#

The order can be changed

#

by the front-end player

#

and then they can store it back into the server, as a new order

#

the UTC should work perfectly tho

leaden ice
#

I'd just prioritize migrating to a real ID ASAP

hoary ginkgo
#

hey guys; is there an efficient way of deleting a game object from an array? That is, I want to call a specific game object within an array and destroy it.

spring creek
hoary ginkgo
#

9 items maximum. It may be less depending on how many players are in the game

spring creek
#

You could use a List and do RemoveAt(0)

hoary ginkgo
spring creek
hoary ginkgo
spring creek
hoary ginkgo
fervent furnace
#

Check .Count of your list

magic parrot
#

How can i limit a object's rotation between a negative value and a positive value on the x axis in 3D?

somber nacelle
#

keep a float value that represents its current angle on that axis, add/subtract it when you intend to rotate it instead of just rotating it, clamp that float, then construct a rotation using that float, and the other two eulerAngles and assign it to the object's rotation. you can search "clamp camera" in this discord to find examples

#

or if this is for a camera, just use cinemachine since it already has that functionality built in

dire marlin
#

player won't teleport to a position given by the script when the scene loads, how can i fix?

somber nacelle
#

any errors in the console? is something else affecting its position? have you confirmed this code is actually running?

dire marlin
somber nacelle
#

so you have no other components that may be affecting its position? no CharacterController, no Animator that affects the position property, no movement controller or whatever that stores and applies its position?

dire marlin
#

im playtesting to see whats the issue

somber nacelle
#

okay can you answer the two other questions i asked then

somber nacelle
#

have you confirmed that it is, or are you just making an assumption?

dire marlin
#

the code does not run when i replay the game

somber nacelle
#

well there we go. is the component attached to an active object in the scene?

dire marlin
somber nacelle
#

yes, your script there defines a class called CheckpointLoader which itself is a type of component

dire marlin
#

ah ok

#

im playtesting right now to see if the gameobject is not set active

dire marlin
somber nacelle
#

so you have confirmed that the code is running? but it is still not working?

dire marlin
#

the gameobject is active

#

and yes it is still not working

#

the code should save the player prefs as I have made it when you reach a certain point

somber nacelle
#

instead of printing just useless prints that don't really provide much context, try printing some useful data.
put this at the end of loadData and show what it prints Debug.Log($"Assigning {Player.name} ({Player.GetInstanceID()}) position {Player.localPosition} from {name} ({GetInstanceID()}). Checkpoint is {PlayerPrefs.GetInt("Checkpoint")}");

#

I modified the log slightly to provide the last bit of useful info

dire marlin
#

ill try that

white palm
#

Hi so I have a list of Gameobjects which i use a set of methods to work out wich of these gameobjects need to be turned on or off and i know that this is working as it worked when i had a slider instead of gameobject but when i switched it to gameobject i get null reference error when ever they are used even though they are assigned in the inspector and im not sure as to why this is happening as its only for these object even if different scripts any help is appreciated

somber nacelle
#

did you reassign them in the inspector? what probably happened was you changed the array types but the data was already serialized to be the other type so you need to drag the references back into it

dire marlin
#

CheckPoint 99 is a special level

#

just a little note

#

it says the player is in that checkpoint

#

but they're at the start

somber nacelle
#

screenshot the inspector for the player

dire marlin
#

i've also noticed something

#

when i reopen the game i go to that specified checkpoint

somber nacelle
#

PlayerPrefs are saved between sessions. if you are not resetting it anywhere then it will always be that

somber nacelle
#

you can either set it back to some other number or delete the key

white palm
somber nacelle
#

show the relevant code

dire marlin
somber nacelle
#

where

dire marlin
#

just an example but this is how i usally save my player prefs

somber nacelle
#

yes i know how playerprefs work. that does not show me where you are setting the Checkpoint key or under what conditions it is being set

somber nacelle
white palm
# somber nacelle show the relevant code

okay here is the code private void RPMLightsMovement() //controlls which light should be on
{
rpm = controller.RPM;
float closest = GetRPMClosest(rpm);
RPMLightsDict[closest].On(); //error when access both
List<float> ramaingVals = new List<float>();
foreach (float val in RPMLightsVals)
{
if (val > closest)
{
ramaingVals.Add(val);
}
}
foreach (float val in ramaingVals)
{
RPMLightsDict[val].Off();
}
} private void PopSliderVals(float mRPM) //uses maths to work out a value at which each light should be used and then adds that as a key and the game object as a value in a dictionary
{
float interval = (0 - mRPM) / (RPMLights.Count - 1);
for (int i = 0; i < RPMLights.Count; i++)
{
RPMLightsVals.Add(mRPM + (i * interval));
}
RPMLightsVals.Reverse();
for (int i = 0; i < RPMLights.Count; i++)
{
RPMLightsDict.Add(RPMLightsVals[i], RPMLights[i]); //error when populating
}
}

somber nacelle
#

!code

tawny elkBOT
dire marlin
white palm
#

sorry i didnt know there was a formating setting

private void RPMLightsMovement() //controlls which light should be on
{
    rpm = controller.RPM;
    float closest = GetRPMClosest(rpm);
    RPMLightsDict[closest].On();
    List<float> ramaingVals = new List<float>();
    foreach (float val in RPMLightsVals)
    {
        if (val > closest)
        {
            ramaingVals.Add(val);
        }
    }
    foreach (float val in ramaingVals)
    {
        RPMLightsDict[val].Off();
    }
}

private void PopSliderVals(float mRPM) //uses maths to work out a value at which each light should be used and then adds that as a key and the game object as a value in a dictionary
{
    float interval = (0 - mRPM) / (RPMLights.Count - 1);
    for (int i = 0; i < RPMLights.Count; i++)
    {
        RPMLightsVals.Add(mRPM + (i * interval));
    }
    RPMLightsVals.Reverse();
    for (int i = 0; i < RPMLights.Count; i++)
    {
        RPMLightsDict.Add(RPMLightsVals[i], RPMLights[i]);
    }
}
dire marlin
dire marlin
#

i didnt know you had to do that with character controllers

iron crown
#

Kind of an odd question but, I want to spawn a unit in an area that is off navmesh, and then through code put them on the navmesh and have them work with the navmesh.

#

Any ideas on how to make that happen? It appears that if the unit is spawned off of navmesh, it's forever not able to communicate with it

oblique spoke
copper widget
#

g'day everyone

I've got a bit of a peculiar issue, I'm trying to implement a simple tank control for my third-person fixed camera controller.

I'm trying to have it so A and D (turn character) (using the input system, but for brevity) interrupt any W or S (forward) movement, and vice versa, but at the moment, I can only get one or the other to cancel each other out.

Here's the code (excerpt) at the moment:


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

        Vector3 move = transform.forward * z;

        if (x == 0)
        {
            controller.Move(move * movementSpeed * Time.deltaTime);
        }
        
        player.Rotate(0, (x * (movementSpeedTank * Time.deltaTime)), 0);

Any advice? Thanks 🙂

leaden ice
copper widget
#

i.e. I can make it so A and D cancel any W and S movement, or, make it so any W or S movement cancels any A or D movement, but not both

In tank controls, generally only one movement (rotation or forward movement) is applied at a time

#

so, for example, the player presses W to move forward, then wants to turn. Pressing A or D while W is pressed should result in the forward movement finishing and rotation starting

leaden ice
#

You need a small state machine basically

#

E.g.

enum State {
  Idle,
  Moving,
  Turning
}

State currentState;```
#

So from Idle you can either go to moving or turning but if you're in the turning state don't allow movement and vice versa

#

Those states can only go back to the Idle State

copper widget
#

Alright, makes sense. I'll give it a go - thank you!

iron crown
#

Or maybe I'm trying to set the destination before I actually move it. Hmm.

#

Got me thinking anyway. Thanks.

spice latch
#

guys how do I save the new input I saved in InputAction

https://gdl.space/ohasuheyeb.cs

I have successfully changed the input from W to I but it wont change it in the InputAction file

left anvil
#

Hi, does someone know how I can read only English names from this function? GetBindingDisplayString() When I use the DEU keyboard it show me DEU names for keys

heavy smelt
#

Using the ArSessionOrigin.MakeContentAppearAt() method, I'm placing a prefab infront of the user's android camera. When I'm rotating the camera to look around the prefab stays correctly at the same place but when the user walks around the prefab doesn't stay at its position thus the user can't walk around it or anything since the prefab doesn't stay at the same place.

Any suggestions will be vastly appreciated.

cosmic rain
left anvil
#

ok thanks 😉

scarlet viper
#

when working with linq is it advisable to convert the collection to an array or should i try to work with ienumerable?

heavy smelt
#

@cosmic rain I already did yesterday, was a bit impatient so I just crossposted. Thanks though.

cold parrot
# scarlet viper when working with linq is it advisable to convert the collection to an array or ...

if you don't want the lazy evaluation you can do that, but each time you do it, you are allocating a new array. whether that is bad depends on the situation. Typically, when you care about performance, you'd not access collections by interface or use something as abstract as IEnumerable, you'd work with signatures that provide the most information possible to the user so they can optimize what they are doing. But during processes that occur rarely (not every frame) you'd care more about constraining the API, readability and explicitness, so there you'd opt for linq/interfaces.

thick terrace
hard viper
# cold parrot A custom kinematic solver, maybe built on top of KCC

could you provide more detail? This was on to topic of making dynamic RBs ride other dynamic/kinematic RBs in their reference frames.
Everything I see for kinematic solvers specifically tries to solve joint angles. But idk how this would work exactly in my case (which should be easier)

dusky lake
#

Hey man, obligatory "thank you" 😄 I have now fully implemented cinemachine and its like upgrading from a sedan to a mercedes 😄

cold parrot
# hard viper could you provide more detail? This was on to topic of making dynamic RBs ride o...

have a look at this https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131 it "solves" physics interactions for various kinds of things (like platforms) that you need for a character

Get the Kinematic Character Controller package from Philippe St-Amand and speed up your game development process. Find this & other Physics options on the Unity Asset Store.

hard viper
#

i see. does this work for 2D?

#

i’ve looked into it before, but it looks really for 3D

crude mortar
#

it does not

hard viper
#

does anikki maybe mean to look at how it is implemented?

crude mortar
#

was there context that it had to be 2D?

analog igloo
#

I'm trying to access URP cast shadow and additional light shadow to disable them, how would i access that by code?

hard viper
#

i don’t remember if I told him 2D

analog igloo
#

There is so much document about it on the web even chatgpt seem to have no idea what URP is

#

after that many year i would have expected a few example

leaden ice
#

Or something else

analog igloo
#

on the URP Renderer Pipeline asset, there a lightning section with Cast shadow and Additional light shadow

#

im trying to turn it off from qualitysetting but it does nothing, my guess is i have to turn that off (if i do it in inspector, it effectivly disable the shadow in the scene)

analog igloo
#

it show property on inspector

#

how i access it by code?

leaden ice
#

I just linked to the code documentation

analog igloo
#

i click it, no code

leaden ice
#

wdym "no code"?

#

It's a doc page

#

it's a list of properties and fields and methods you can use in code

analog igloo
#

Where is that property supposed to be?

#

on the pipeline asset?

leaden ice
#

which property in particular

analog igloo
leaden ice
#

What is highSettings

#

is that a QualitySettings object?

analog igloo
#

thats the renderer pipeline asset

leaden ice
#

so which field are you looking for

#

"Cast shadow" is not something I've ever seen

analog igloo
#

its not in that list, but its in the inspector, and thats what seem to turn off and on shadow in scene

leaden ice
#

it's get only though - you'd need to configure two separate assets and swap one in that has the setting you want

analog igloo
#

almost impossible i cant disable shadow directly

#

cant make an asset for every possible settings a player want

cosmic rain
analog igloo
#

no

#

there must be something wrong

#

im accessing the asset directly, setting it in inspector, trying to acess it by code

#

i dont have this, its public

cosmic rain
analog igloo
#

yes

cosmic rain
# analog igloo

This is more about the lights being supported or not.
It's not for toggling them on or off.

#

You could disable the shadows on the light sources. Donno how many you have, but it's not impossible.🤔

analog igloo
#

too many

cosmic rain
#

Could also probably set shadowDistance to 0

analog igloo
#

tryed again quality setting with a debug line under with the value i set to make sure everything is right and yeah, shadow still stay in the scene even if i disable

analog igloo
cosmic rain
#

Aight. Then I guess it doesn't work in urp.

analog igloo
#

ya its somewhere else and google and chatgpt have no idea, doc doesnt say either

#

cant beleive no one using urp disable shadow

cosmic rain
#

Setting the shadow distance to 0 would have the same effect.

analog igloo
#

im sure some code still run under the hood thought

#

not sure its that great

cosmic rain
#

I don't know about it. But if anything runs, it's probably untoggleable.
You can try looking at the urp source code to see what that getter property references.

analog igloo
#

yeah i guess i can start from there

#

all property are on a partial class

abstract ivy
#

hi, does unity 2021.3.2f support default interfaces ?

fleet furnace
abstract ivy
#

oh ok

dusky lake
#

cant you just use abstract classes?

blazing tiger
#

Remind me again is it possible to if(gameobject is interface) to check whether a gameobject has a component which implements an interface or am I mixing something up?

#

With C#'s Is keyword specifically

#

Oh wait you're supposed toGetComponent<interface>

heady iris
#

Correct.

blazing tiger
#

Slowly remembering this engine

heady iris
#

a GameObject is always just a GameObject

#

it has components

#

but it is not, itself, a component

heady iris
blazing tiger
#

Yeah I'm actually trying out newer Unity for the first time after about like, 5 years of using Unreal

#

Last time I used Unity I don't think they even had year for a version, just digits

heady iris
#

yeah, that changed in ...2017?

blazing tiger
#

That was a WHILE back

heady iris
#

Components are similar to unreal's Actor Component. They're attached to a GameObject, and they do not have a Transform

#

If you want to nest things, you parent GameObjects to each other

#

Unity has fewer opinions about how games work. You don't have Pawns and Characters, for example

#

I found this to be very weird when dabbling in Unreal

hard viper
#

Is kinematic character controller performant if you have like 500 controlled bodies for it?

dusky lake
#

you are better off looking for a benchmark online or doing one yourself

lean sail
latent latch
#

So I'm having problems trying to figure out how to do some delete functionality for my tool. Because I'm having troubles with my serialize dictionary, I'm just using a list to store hundreds of thousands of entries, which I read and load into a dictionary on start. Now, when it comes to deleting these entires, usually I'm using the look up and deleting the gameobject directly, but now I have to delete it from my list which I'm not going to iterate 500k times to delete a single entry. Any ideas how I am to optimize this?

abstract ivy
dusky lake
lean sail
latent latch
#

Right, it's just game objects, and they have a vector3int value which is the key to the dictionary<vector3int, gameobject>

heady iris
#

i just checked that they compile

#

A default interface implementation is only accessible if you cast to the specific interface type first

#

They're basically just extension methods.

lean sail
latent latch
#

I don't care too much about the sort, I care about removing the entries and changing the heads of the list to the next valid entry when I delete

heady iris
lean sail
#

Hmm if theres no guaranteed structure to the list, then you're unfortunately just left with a linear search

latent latch
#

Like, if I destroyImmediate from the dictionary lookup, I need to remove the entry from the list, otherwise it'll be full of dead gameobject references

fervent furnace
#

sparse set again....

#

fast O(1) look up insert delete unordered data structure...

heady iris
#

well, you need order to make a dictionary

latent latch
#

it needs to be serializable

#

the list is just for loading

#

otherwise the dictionary would suffice, but unity hates me

#

probably another way to tackle this like just grabbing all the scene objects at the start and loading them into the dict

#

The problem isn't so much cleaning the list after delete, it's that if I don't reduce it every so often it's going to keep growing, so I need to clean it up.

heady iris
#

is it actually a problem?

#

or is it just a potential problem

#

maybe you can just filter the dictionary every now and then

latent latch
#

The dictionary is fine. It removes the entries because it's what's removing the objects. It's just the list needs to be a thing because I can't serialize my objects without it.

#

so next time I load the editor, it has to read from the list to populate the key/values

leaden ice
fervent furnace
#

sparse set is a wrapper of list and dict together, idk if this fit your needs

heady iris
#

if you're performing the (de)serialization yourself, do the filtering then

leaden ice
#

e.g. after you load the list into a dict, you should just clear and null out the list

#

let it get GCed

#

make a new list when you serialize again

#

(when you save I guess?)

latent latch
#

maybe I'm just not using the scene to my full advantage since it does clean up the objects when you delete them

#

so maybe the idea is to just search through the children of some object

rocky jackal
#

how can i pass more then one variable through a unity event calling a function ?

heady iris
#

note that you can't mix and match argument counts

#

but let me check that..

latent latch
heady iris
#

good, I was mostly right

#

so yeah, UnityEvent can support up to four arguments

#

You can pass these along to a method with matching argument types

heady iris
#

in case you were curious about that

hard viper
hard viper
#

I wonder if I can use the asset store KCC to define physics to replace my dynamic rigidbodies

#

i would need to rewrite a lot to being it to 2D

lean sail
latent latch
#

my head is too stuck in how I'd dynamically serialize and save it all

#

because how I'm thinking here, even if your editor crashes, I'd still be able to restore my tool to the last thing serialized.

#

but if I rely on scene objects then I don't really get that safety net I guess?

simple sable
#

Hey, everyone. I have a little bit of a problem, but just can't find a way to solve it. Thought someone might be able to help.

So, I have in my game an inventory system which uses scriptable objects as items.

Let's say I have a class called SwordClass with different properties such as length and strength.
I can then use that class to create different scriptable objects that use that class and change those properties to create multiple types of swords.

The problem I'm having is that I would like to be able to have data that is specific to an instance of that scriptable object. For example, I might have 3 swords in my inventory - the same type of sword (item). Now, what if I want to have a damage property that is different for each sword based on how much that sword has been used?
I can't just add a new variable to the SwordClass, since changing the damage on one sword would change it for all the swords.

heady iris
#

you need to separate the definition of the item from runtime data about the item

#

one option would be to hold the runtime data (e.g. swing count) on a MonoBehaviour that also references the scriptable object

#

call that a "Weapon"

#

the Weapon is defined by a scriptable object, but also has some extra information

somber tapir
# simple sable Hey, everyone. I have a little bit of a problem, but just can't find a way to so...

You could copy/clone the SOs when you add them to your inventory, then you could change the values and it would only change it for that one sword. But that is gonna give you more problems down the line, I would recommend having a "normal" script (Sword) and a SO (SwordData) for your items:

The SwordData holds all the base stats of your Sword and can create an instance of a Sword class.

The Sword class has a reference of the SwordData but also has it's separate fields like:

public int Damage
{
    get
    {
        return swordData.Damage + BonusDamage;
    }
}

public int BonusDamage;
manic gulch
#

Something weird has happened to me when I tried to convert an Animation Clip's Curve to an AnimationCurve...

I am getting the AnimationCurve from the AnimationClip using this line of code

rotationCurves[i] = AnimationUtility.GetEditorCurve(animationClip, GetCurveBinding("m_LocalRotation", i));

The binding I'm using is m_LocalRotation but apparently it doesn't properly copy the actual graph for rotation??? You can see below the difference between the Animation Clip and the Animation Graph.

PS: I tried this with position and it works fine.

simple egret
#

It's against the server rules

#

I do not make the rules

abstract ivy
heady iris
#

as I said, you must cast to the exact interface type or it won't work

#

🤨

simple egret
#

Too late :)

heady iris
#

Default interface implementations are not used to provide multiple inheritance. They're mostly there so that you get backwards-compatibility when making what would normally be a breaking interface change

simple egret
#

This is a code channel

heady iris
#

So that when they are being used as an IFoo (instead of their specific concrete type), the methods are available

#

But it doesn't do anything to the concrete type.

#

This does mean that the concrete type appears to fail to implement the interface, of course.

#

But no existing code will break when you add a new method to an interface and give it a default impl. That's the core idea.

simple sable
heady iris
#

I did exactly that in a soulslike game

#

the SO defines the weapon, and then I have a bunch of extra runtime data to customize it

simple sable
#

Do you know any tutorials or some documentation that might help me wrap my head around it?
It's my first time working on an inventory system and it can get quite complex.

manic gulch
broken heron
#

can someone tell me what I am doing wrong here, I'm setting a reference to my player gameobject in void Awake()

    {
        // Find and assign the player Transform based on the "Player" tag
        GameObject playerObject = GameObject.FindGameObjectWithTag("Player");
        if (playerObject != null)
        {
            playerT = playerObject.transform;
        }
        else
        {
            Debug.LogWarning("Player GameObject not found in the scene. Make sure you have a GameObject with the 'Player' tag.");
        }
    }```

my player gameobject has the Tag  "Player"

However I get these errors
Player Transform is not assigned in the Inspector.
Player GameObject not found in the scene.
Player Transform is not assigned in the Inspector.
Player GameObject not found in the scene.
tawny elkBOT
broken heron
#

gottcha ty

rigid island
broken heron
#

there we go ty

somber tapir
rigid island
#

one of them does from a warning they're logging

broken heron
#

If I double click the Errors I get taken to these two methods.

    {
        if (player == null)
        {
            Debug.LogError("Player Transform is not assigned in the Inspector.");
            AssignPlayerTransformFromScene();
        }
    }

    protected virtual void AssignPlayerTransformFromScene()
    {
      //  GameObject playerObject = GameObject.FindGameObjectWithTag("Player");
        if (player != null)
        {
            playerT = player.transform;
        }
        else
        {
            Debug.LogError("Player GameObject not found in the scene.");
        }
    }```
rigid island
#

ohh

white delta
#

hey guys, how difficult do you guys think it would be to remake the game “erannorth chronicles” coding wise. I want to get better at Unity and i’m actually interested in making a project like this.

white delta
#

yes it is?

#

fine i’ll ask there too..?

rigid island
#

where is the code you're asking about

white delta
#

this isn’t a code question channel. this is a channel where you discuss code. did you read the channel description?

somber tapir
rigid island
white delta
white delta
white delta
rigid island
#

the game is composed of many system, your question is very vague

somber tapir
white delta
#

although i’m most likely wrong

#

i just started unity, but i have 3 years of experience in Lua so i dont see it being difficult to learn C#

rigid island
#

everything in c# is an object

white delta
rigid island
#

ScriptableObject is strictly a unity concept

somber tapir
#

There are probably a lot of tutorials about making a card game in Unity with ScriptableObjects, might be worth it to look one of them up.

rigid island
#

making regular classes the concept is the same.

broken heron
tame urchin
#

I know this is a DOTS question but I was wondering if anyone knew: Is it possible to use subscenes without converting to and from entities? I want to split up a large scenes to allow streaming it in and out of memory, and to prevent my main scene size from being too large, and for organization purposes, but I don't want to have to manage conversion to and from entities. In fact, I don't really want any of the GO to be converted to entities.

#

Does anyone know how to accomplish that? Do I have to write my own subscene system for this?

tame urchin
#

👍

hard viper
#

Is there any downside to using rigidbody.velocity for kinematic rigidbodies? (in 2D, they do move with velocity)

rigid island
#

!code

tawny elkBOT
rigid island
#

use link

dusk apex
#

I'm assuming there's a question?

rigid island
#

from what you shared I don't see the constructor path being passed anywhere

#

unless im like blind

shut wadi
rigid island
#

    public FileDataHandler(string dataDirPath, string dataFileName, bool useEncryption)
    {
        this.dataDirPath = dataDirPath;
        this.dataFileName = dataFileName + ".game";
        this.useEncryption = useEncryption;
    }```
#

where are you passing dataDirPath

shut wadi
rigid island
#

ideally use on screen console

#

or check player logs

shut wadi
#

I have a debug.Log

rigid island
#

in the save method?

#

and are u checking the logs text file in the Build not in the editor?

shut wadi
#

Like you can see in ejemoyiyot.cs, when I don't have a data file, that create a new one Debug.Log("Aucun data n'a ĂŠtĂŠ trouvĂŠ. Initialisation des data par dĂŠfauts"); In french that mean No Data found. Initialization of defaults data. And in my Player data I can see the debug.

#

But no file was create

rigid island
#

this is not actually debugging where you save the data into

#

print out the paths and everything

#

make sure its all correct

#

Debug.Log the paths not random words

shut wadi
#

Oh I didn't see but I have errors in my Player data

#

But it's strange knowing I don't have any errors in my editor 🤔

rigid island
#

it can happen

shut wadi
#

I build the good scene and I send you my log

#

So ! it works but I there is still two errors :
NullReferenceException: Object reference not set to an instance of an object
at DataPersistenceManager.LoadLanguage () [0x0003a] in <d151fee06742438587d44e6d3986dc1b>:0
at LanguageManager.Start () [0x0001e] in <d151fee06742438587d44e6d3986dc1b>:0

#

But it works...

rigid island
#

idk what u mean works

hard viper
#

is there any way to make a joint send force from RB 1 to RB2, and not visa-versa?

shut wadi
rigid island
#

yeah but your error is with Loading

shut wadi
#

Ok I take a look

#

I will come back if I can't resolve the problem.

#

Thanks for the help

earnest epoch
#

I just lost a day over this...

//var inputDelta = Finger.currentTouch.delta; // Periodically loses track of history order and gives bullshit deltas
var inputDelta = TouchInputManager.GetCorrectDeltaFromEnhancedFinger(Finger);```
Meanwhile, in `TouchInputManager`...
```cs
public static Vector2 GetCorrectDeltaFromEnhancedFinger(UnityEngine.InputSystem.EnhancedTouch.Finger finger)
    {
        // Just ask the f***ing device for the right value
        return Touchscreen.current.touches[finger.index].delta.value;
    }```![notlikethis](https://cdn.discordapp.com/emojis/1068134558123442236.webp?size=128 "notlikethis")
latent latch
#

As opposed to the other static method GetAlmostCorrectDeltaFromEnhancedFinger

#

Oh, is that your class. Sorry Im kinda dealing with a lot of their (unity's) verbose methods atm 😂

earnest epoch
#

Actually, I just stepped away after writing that and realized that I understand by exactly how much the delta is from what the expected result should be. I was about to see if Unity offers bug bounties, because I think I have the insight now into what the problem is.

#

It's not just switching positive/negative. The reported value is off proportionately to the radius of the touch and also gets worse as the touch's current position moves away from the initial start.

latent latch
#

Ah, yeah I see what ya mean about it

earnest epoch
#

I tried filtering out results on frames if I could mark them as bad/flipped, but I later realized that the error is measurable if you assume that the integral of all the positions are actually approaching the true correct delta.

lofty egret
solemn wren
#

how can I have a system like a spring arm (godot) for a cinemachine freelook camera?

rigid island
#

cinemachine collider?

#

whats it supposed to do?

solemn wren
#

from the godot docs: "A 3D raycast that dynamically moves its children near the collision point... This is useful for 3rd person cameras that move closer to the player when inside a tight space."

lunar lynx
#

is there a way to check which areas a calculated path goes through prior to traversing the path?

leaden ice
leaden ice
solemn wren
#

@leaden ice thanks ill look in to it

lunar lynx
leaden ice
lunar lynx
#

or volume. say it's just a general 3d rectangle

leaden ice
#

Nore that you're probably talking about the specific asset from Aron Granberg but A* is a general purpose pathfinding algorithm

lunar lynx
#

no, actuall unity's built in a*

leaden ice
#

You mean navmesh?

lunar lynx
#

but i am checking granberg's right now...

#

yeah nav mesh

#

sorry

leaden ice
#

For either of them you can do raycasts along the path against trigger colliders that definite the area

lunar lynx
#

i guess i could have a ghost traverse the path and check which volumes it collides with, but is there a built in way to check areas that the returned path goes thru

leaden ice
#

Or SphereCasts

lunar lynx
#

ah ok

leaden ice
#

No there's no built in way

lunar lynx
#

gotcha, thank you

forest prism
#

quick question on item drop list. Is there a best way to handle drops ? Not sure if it matters but I'm creating a 2d. I've thought about just having the enemy mobs have a drop list that I fill in with prefabs but that seems messy. I also thought about having the mods have a function that drops, it basically reads from a Json list of all dropable items in the game and determines what should drop and how many. So basically between a bunch of prefabs and a json list that dynamically creates the item on drop.

latent latch
#

Quite a lot there for just a quick question

#

More that you're asking how to handle mods on items when they drop from enemies and how would you serialize them, right?

#

Really, there's like three different concepts in your question

leaden ice
latent latch
#

Best advice, keep mods, drops, and stuff wrapped in scriptableobjects and don't deviate too far from them. It's easier to serialize them than it is to serialize every unique value to and from json.

forest prism
latent latch
# forest prism appreciate the advice thank you

Ah, sorry reading it again I thought you were also talking about mods on drops too. But for the drop idea you don't necessarily need to use json, and the scriptable object idea still applies. Basically how I've implemented some is using a level_ID on items and if a monster level falls in some range of that item_ID, then it has a weighted chance to drop. When they drop, I pick from the pools of weighted items and add some extra conditions like amount of items to drop.

#

It's all done by using SOs and I just construct the item through them

forest prism
latent latch
#

The drop is just a dummy container that takes the SO data and uses* the data's sprite/model to display and spawn it on the ground. When collected, the container is destroyed and then the item is constructed and added to the player's inventory

#

As far as a prefab, I have a prefab called Item that has a pickup script and the SO to be inserted.

forest prism
#

good way to do it to save a ton of space

latent latch
#

Pretty much. I only use monobehaviours when I really need it. But technically the item can stay data until then.

forest prism
#

I need to do more reading on monobehaviors and when it's safe to not use. I over use it to avoid any errors but I'm sure it's wasting space

latent latch
#

The overhead probably isn't that bad, but if you do got like some large endless inventory, then it's probably best to just leave it as data until it actually has a scene presence.

forest prism
#

oh sick okay no I'm doing limited inventory and I want stuff to take up space in the game, e.g. no magic endless stash you can store the entirety of the united states in so it shouldn't come up as an issue

#

I appreciate all the info

hybrid turtle
#

Hi may be a simple question but how do you access the opacity of a slider. Typcially id access the material and its color and change the alpha but with a slider idk?

rigid island
#

slider is just bunch of image components put together with some magic

hybrid turtle
#

yes but none of its children like have a renderer with materials like ive normally messed with

#

im assuming there's a way to change opacity of images then?

rigid island
#

yeah the image component

hybrid turtle
#

just get the image component and theres probably some property

#

ok makes sense thank you

rigid island
#

color prop

cosmic rain
#

UI is rendered differently and you usually wouldn't touch it's material. You can adjust the color property of the image component.

rigid island
hybrid turtle
hybrid turtle
#

hey should it not be just as simple as

#

            for(float alpha = 1; alpha >= 0; alpha -= 0.1f)
            {
                c1.a = alpha; 
                yield return null; 
            }```
#

like literally what the unity docs say on decreasing the alpha

mossy snow
#

yes, except you need to assign your modified color to the image on each iteration

hybrid turtle
#

so move GetComponent

#

?

#

sorry probably haviing a brain fart

rigid island
#

where is this script placed?

#

maybe you need alpha -= 0.1f * Time.deltaTime so its not so quick

hybrid turtle
#

called StartCoroutine() in Start and yes I agree I should multiply by Time.deltaTime

#

but even then it has no effect

#

when run

rigid island
#

did you pass the value back to the same image component

rigid island
#

might wanna cache that reference

hybrid turtle
#

sorry doesnt it do that because this line gets it Color c1 = timeScrollerSlider.gameObject.transform.GetChild(0).GetComponent<Image>().color;

#

but yes I'll just cache that in Start() as well

rigid island
#

if this script is like on a parent object / scene you should considering make a inspector reference field

mossy snow
rigid island
#

then just plug it in, skip GetComponent

hybrid turtle
#

I just want to be able to fade away a slider over time

rigid island
#

put them in an array

#

loop through them

hybrid turtle
#

yeah thats what I did technically ive only found that it has one image component which is its background cuz it kept givijng me an error

rigid island
#

you're only looking for 1 child

hybrid turtle
#

yup

#

gonna give it a try here and see

rigid island
#

drag the components in

hybrid turtle
#

ok yeah that is best

#

yeah it only has the background image

#

but script is still not working for that

rigid island
#

something like this ?

private IEnumerator Fade()
        {
            for (int i = 0; i < sliderImages.Length; i++)
            {
                var col = sliderImages[i].color;
                while (col.a > 0)
                {
                    col.a -= 0.2f * Time.deltaTime;
                    sliderImages[i].color = col;
                    yield return null;
                }
            }
        }```
#

i think

hybrid turtle
#

ok yeah that seems right to me

#

you get this though when you try assign

#

i think i forgot the .a

#

ok I just tried it doesnt seem to work but the logic lines up you decrease thee alpha on the color and assign it to be the image colour

rigid island
#

it should be working..

#

hmm let me try

cosmic rain
hybrid turtle
#

ok yeah I didnt assign an image component

rigid island
#

it works but yeah its weird because of loop

hybrid turtle
#

yeah same here

rigid island
#

it does 1 each

hybrid turtle
#

yeah because of the loop I guess you could write coroutine for each and get away but there's got to be a better way

rigid island
#

might also be the coroutine

hybrid turtle
#

also this is the default slider which images did you take for the fill area and handle slide area

#

because I only see RectTransform on these

rigid island
#

nested inside

hybrid turtle
#

gotchu

cosmic rain
#

Make a separate lerpTimer outside the loop, set each components color in a for loop, then yield.

#

Basically, the while needs to be the outer loop that you yield and the for loop should be inside.

hybrid turtle
#

ohh ok and sepearte for loops for each color?

#

so three for loops in the while loop

#

yield at the bottom?

cosmic rain
#

No need for several for loops. You modify the same thing for all the components: the alpha. And you want it to fade at the same rate, so just one for loop that modifies a separate component each iteration.

rigid island
# hybrid turtle yield at the bottom?
 var t = 1f;

        while (t > 0)
        {
            t -= 0.12f * Time.deltaTime;
            for (int i = 0; i < sliderImages.Length; i++)
            {
                var col = sliderImages[i].color;
                col.a = t;
                sliderImages[i].color = col;

            }
            yield return null;
        }
    }```
hybrid turtle
#

oh bruh I see thank you so much guys

#

ive been stuck on it a while

rigid island
#

ofc change 0.12

#

dont hard code numbers 😛

hybrid turtle
#

yeah ofc make a filed

cosmic rain
#

There's a chance that the initial alpha of each image is different too. In that case might want to keep track of the initial state.

hybrid turtle
#

field

#

ok another question this is a linear fade

heady iris
#

yes, since you're subtracting a constant amount of t per second

hybrid turtle
#

yes so can i use like pow then do that

heady iris
#

what do you want?

hybrid turtle
#

To decrease the fade rate of the slider quadratically so was thinking of using t -= Mathf.Pow(0.3, 2)

#

Therefore the fade rate would be dictated by -0.3t^2

cosmic rain
#

Might want to use a lerp instead and modify the time in a non linear fashion.

cosmic rain
hybrid turtle
#

Oh shoot yes you’re right I didn’t see

cosmic rain
#

For non linear interpolation, the change amount needs to change over time.

hybrid turtle
#

Yes Mathf.Lerp(t, 1, something changing)

#

Mathf.Lerp(t, 1, -Mathf.Pow(t, 2))

cosmic rain
#

If you use lerp, the the "something changing" itself needs to change non linearly.

hybrid turtle
#

Possibly

cosmic rain
#

Ah

#

Maybe not

#

Yeah, that should work.

#

Aside from the -

hybrid turtle
#

Hmm ok went on a whim there

#

So how do I make it negative to subtract each time

cosmic rain
#

The third parameter needs to go from 0 to 1 or the other way around.

hybrid turtle
#

Ok nevermind would it work?

cosmic rain
hybrid turtle
#

Yes makes sense

cosmic rain
hybrid turtle
#

Yes it should be so I’m gonna give that a shot

cosmic rain
#

Assuming you want to use the result of the lerp as the alpha value.

hybrid turtle
#

Yes of course I’m still thinking though like it seems too trivial almost

#

I’ll have to try ofc

heady iris
#
t -= Time.deltaTime * 0.12f;
float effectiveT = Mathf.Pow(t, 2);
#

This would make effectiveT fall off quickly at the start

hybrid turtle
#

Oh I see that is plausible too

night harness
#

Is there a way to add a new overload functions and constructors to a pre-existing built in function?

heady iris
#

well, functions don't have constructors

#

you can declare "extension methods" to add new instance methods to existing types

cosmic rain
night harness
#

Ooo ExtensionMethods look like the thing I want for the function side of things

And yeah sorry I meant overloading class constructors for the other part of the question, no luck on that?

hybrid turtle
#

It explains extension methods

cosmic rain
hybrid turtle
broken heron
#

Trying to maintain data from my character creation scene to my actual scene. I've tried a few things put the _player Object in the do not destroy, added in check for player object by tag "player" tried a Service Locator script and added the player to it and set it up in Void Awake()

my current setup

    {
        if (!IsValidSelection()) return;

        player.selectedRace = GetRaceFromDropdown();
        player.selectedClass = GetClassFromDropdown();
        player.PlayerName = buttonManager.nameInputField.text.Trim();
        player.PlayerGender = ParseEnumFromDropdown<BaseRace.GenderType>(buttonManager.GenderDropdown);

        UnityEngine.Debug.Log($"Character created: {player.PlayerName}");
        ServiceLocator.RegisterService<Player>(player);

        SceneManager.LoadScene("GameStart");
    }```

I originally had ServiceLocator register in player.cs void awake() but had the same results.

here is one of my calls to it.
```    private void Start()
    {
        player = ServiceLocator.GetService<Player>();
        player.transform.position = startingPosition;

        InitializePlayerGO();
    ```

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

public class ServiceLocator : MonoBehaviour
{
    private static Dictionary<System.Type, object> services = new Dictionary<System.Type, object>();

    public static void RegisterService<T>(T service)
    {
        var type = typeof(T);

        if (services.ContainsKey(type))
        {
            Debug.LogWarning($"Service of type {type} is already registered. Overwriting.");
        }

        services[type] = service;
    }

    public static T GetService<T>()
    {
        var type = typeof(T);

        if (services.TryGetValue(type, out object service))
        {
            return (T)service;
        }

        Debug.LogError($"No service of type {type} found.");
        return default;
    }

    private void Awake()
    {
        RegisterService<IPlayerService>(GetComponent<PlayerService>());
    }
}

anyone have a suggestion or inkling of what i am doing wrong?

mossy snow
#

you didn't say what the problem was. Persisting the player GO itself from char creation sounds like the wrong approach to me though

broken heron
#

Oh, the problem is every refence to the player in the next scene is Null.

mossy snow
#

is the player a root GO?

broken heron
#

yes

mossy snow
#

does it appear in the DontDestroyOnLoad scene when you change scenes?

broken heron
#

Yes

mossy snow
#

do you have another player instance in the scene you're changing to that overwrites its entry?

broken heron
#

no, im guessing i should?

mossy snow
#

Why would you? it would replace the other entry and generate a warning according to your own script

broken heron
#

I thought you meant The Player GO would overwrite the lets say playholder player GO

mossy snow
#

well, now you should set some breakpoints and walk through your code a line at a time

broken heron
#

You know I try doing that and occasionally it pops up a file explorer asking for a file for my Dropbox. I will attempt again though.

ebon apex
#

in all my 3 years of using unity ive NEVER managed to get mathf.lerp working can someone explain why this simple function only works when it feels like it??

somber nacelle
leaden ice
ebon apex
#

yup got it need to have a new_rotation_angle = mathf lol

leaden ice
heady iris
#

well, yes, if you just call the method and throw the result away, nothing will happen

#

If you aren't passing a float argument with a ref or out keyword, the method cannot modify it

#

you should read the documentation for methods you don't understand the use of

quaint rock
#

also passing it just deltaTime for t is not very useful

heady iris
#

yes, that's an unusual way to use it

#

Quaternion.RotateTowards would be my go-to

#

var result = Quaternion.RotateTowrads(from, to, Time.deltaTime * degreesPerSecond)

quaint rock
#

yup and you get to avoid issues with euler that way to

heady iris
#

Trying to Vector3.Lerp euler angles sure would be interesting

ebon apex
ebon apex
#

just wanted to add a slight camera tilt like in the quake games. using animations made it look bad and janky ig so yeah

ebon apex
ebon apex
night harness
#

Getting a weird null error here. Not sure what could be null here that I'm not checking?

    public bool IsTileChanged(Vector3Int index)
    {
        Debug.Log("ahhhhhhh" + index);
        Tile tile = tileMatrix[index.x, index.y, index.z];
        //Debug.Log("daawdawd");
        if (tile != null)
        {
            Debug.Log((PositionToMatrix(tile.transform.localPosition, Space.World) + " , " + MatrixToPosition(index, Space.Self)), tile.transform);
            if ((int)Vector3.Distance(PositionToMatrix(tile.transform.localPosition, Space.World), MatrixToPosition(index, Space.Self)) == 0)
            {
                //Debug.Log("yey");
                //Debug.Log(tile.transform.name + " , " + tile.TileName);
                return (false);
                if (tile.transform.name == tile.TileName)
                {
                    //Debug.Log("Identical Tile, Skipping Scan!");
                    return (false);
                }
            }
        }
        return (true);
    }
NullReferenceException: Object reference not set to an instance of an object
(wrapper managed-to-managed) System.Object.ElementAddr_8(object,int,int,int)
PuzzleManager.IsTileChanged (UnityEngine.Vector3Int index) (at Assets/Project/Scripts/Gameplay/PuzzleManager.cs:288)
PuzzleManager.ScanTile (UnityEngine.Vector3Int index, System.Boolean enableLogging) (at Assets/Project/Scripts/Gameplay/PuzzleManager.cs:232)
ScriptableManager.CheckPuzzleManager (Tile tile) (at Assets/Project/Scripts/EditorTools/ScriptableManager.cs:112)
ScriptableManager.Update () (at Assets/Project/Scripts/EditorTools/ScriptableManager.cs:60)
UnityEditor.EditorApplication.Internal_CallUpdateFunctions () (at <63965ae56af7489797f355b7c1211ab2>:0)
#

that last if is unreachable on purpose was curious if that property was the problem

mellow sigil
#

Which line is 288?

night harness
#

oh

#

im dumb

#

thank you very much

lone cliff
#
using System;
using UnityEngine;

public class TravellingBalls : MonoBehaviour
{
    private Vector3 startPoint;
    private Vector3 endPoint;
    private Vector3 direction;

    private GameObject travellingBallPrefab;

    private float speed = 6f;
    private float lifeSpan = 10f;
    private float spawnInterval = 1f;

    void Update()
    {
    }
}

I want to modify this script such that:

  1. the travellingBalls will always stay on the lineSegmentLayer while translating between the startPoint & endPoint. Note that these 2 points can change their position, then the balls should change their path.
  2. The balls will destroy themselves after the lifeSpan (in seconds) is over
  3. The balls will keep on being generated after the spawnInterval (in seconds)

I want to achieve the following without the use of lerp, slerp, lookAt(), coroutines.
Can anyone please help me out ??

formal wagon
#

Hey folks, is there any way that I could perform enum-to-int casting in Burst-compiled code?

I've got a burst-ified utility class that's responsible for converting integer/enum pairs into simple hashes. The current setup I have is below:

// Calculates a simple integer hash between two values
[BurstCompile]
public static int CalculateHash(int i1, int i2) {
    return i1 ^ (i2 << 16 | i2 >> 16);
}

// An override that calculates a hash using an integer + enum combo
[BurstCompile]
public static unsafe int CalculateHash<E>(int i1, E enumValue)
where E : unmanaged {
    // Convert the enum into an integer value with a cast
    int i2 = UnsafeUtility.As<E, int>(ref enumValue);

    // Trickle down to CalculateHash
    return CalculateHash(i1, i2);
}

Unfortunately, this doesn't end up being compiled by Burst since UnsafeUtility.As is a non-bursted method. I haven't been able to find an alternative and casting enums to integers is used in a ton of hot loops throughout my application

I really don't want to refactor since I don't want to compromise on readability, so is there some C# wizardry that I can cast to perform the casts in a performant way?

somber nacelle
#

(int)enumValue

formal wagon
#

Tried that, doesn't work notlikethis

somber nacelle
#

ah, it's because you are restring E to unmanaged rather than to an enum

formal wagon
somber nacelle
#

well it would be Enum not enum but i'm not 100% certain if that would work for burstable code

formal wagon
#

Sorry, yeah - I've tried to use Enum but I removed it earlier while fiddling around with the function to see if I could get Burst to compile it

#

Just gave a deeper look into this, seems like Burst just can't support generic static methods atwhatcost

tacit dust
#

Hello, I have a question about local push notification. Since android 13 we must request permission on start session, but if user decline entry game request we can send to him request again? example when user click a button in game settings notification toggle? (In test case on simulator native popup try to show but not) if (!Permission.HasUserAuthorizedPermission("android.permission.POST_NOTIFICATIONS")) { var callbacks = new PermissionCallbacks(); callbacks.PermissionDenied += CallbacksOnPermissionDenied; callbacks.PermissionGranted += CallbacksOnPermissionGranted; Permission.RequestUserPermission("android.permission.POST_NOTIFICATIONS", callbacks); }

hasty silo
#

Hello, what is the easiest way to figure out what file path to tell unity to dig into when I want to grab stuff from a folder in assets? Trying to figure out how to get to the correct folders that I want but not sure how to test it/look for the right path.

#

Pretty sure these are the correct paths but it is not finding any of the files I have in there.

scarlet notch
#

i don't think unity allows you to access the Assets folder at runtime as all the assets are compiled into the game, you'll need to use the resources API to get these files at runtime, it's just a case of creating a folder called Resources at the root of your project and putting everything in there. then you can use Resources.Load("inkyDialogue/RoundOne") (for example) to load the data - not sure exactly how that works for just
https://docs.unity3d.com/ScriptReference/Resources.html

#

from a brief googling, if they're text files you can use the following:

TextAsset mytxtData=(TextAsset)Resources.Load("MyText");
string txt=mytxtData.text;
hasty silo
#

Ah ok sounds good. Ill look into resources folders

lean sail
hasty silo
#

Trying to setup a system for easier dialogue management using inky.

#

Using folders so I can run through them after I put them in a array or list of textassets

scarlet notch
#

so to take one of your examples:

var roundOneTextAsset = (TextAsset)Resources.Load("inkyDialogue/RoundOne");
var roundOneText = roundOneTextAsset.text;

provided your text file is at Resources/inkyDialogue/RoundOne.txt

hasty silo
#

Sounds good, and Im guessing use LoadAll with typeof(TextAsset) for getting all textasset files in the filepath?

scarlet notch
#

i've not personally used LoadAll but yep i'd assume that'd be the case!

hasty silo
#

Sounds good! Ill look into it some more if I run into any problems. Thanks for the help!

scarlet notch
#

no bother, good luck!

hasty silo
#

Thanks I need it 7899peepocry

hoary monolith
#

Hello, I see some youtube tutorials use Singletons but some others don't really recommend using it. But I think it still has some use cases, so I want to know when does using a singleton becomes bad?

#

And is it okay to use Singletons for Data persistence? If not what are good alternatives.

vague slate
#

Is there some sort of child game object index inside of hierarchy?
Persistent one.
Basically, say I have a big bone hierarchy of 100 game objects. I want to have some index associated with each child. Is there anything built in?

cosmic rain
hoary monolith
#

So when does it usually become bad? I plan to use a singleton for my Data Persistence Manager is that a good idea?

scarlet notch
vague slate
scarlet notch
#

depending on what you're wanting to do and if you're spawning these game objects in, you could just use the gameobjects name as the index, so when you spawn them you can name them 0, 1, .., n (if you're not bothered about what they're actually called

vague slate
#

nah, literally need unique asset + child index (for whole hierarchy)

scarlet notch
#
    void Start()
    {
        var i = 0;
        foreach (Transform child in transform)
        {
            Debug.Log($"{child.gameObject.name}: {i}");
            i++;
        }
    }
#

this should get you started

#

prints:

vague slate
#

dw about it

scarlet notch
#

if you're traversing the whole tree you'll need some recursion going on

vague slate
#

I needed it for all children recursively

#

for what you shown there is built in GetSiblingIndex

#

I just get all transforms from hierarchy and calculate index by comparing transform

#

works for me, just sad there is no such thing built in

#

especially considering all children are serialized as part of same asset

scarlet notch
#

ah sorry yeah sibling index will do the same thing

#

if you need it for the whole hierarchy then write a recursive method to traverse the tree doing that same thing

lean sail
cosmic rain
# hoary monolith So when does it usually become bad? I plan to use a singleton for my Data Persis...

As I said, it's hard to say when it's bad, since it depends on preferences and the context.
Roughly speaking, when it is used as a shortcut for objects that aren't actually singletons logically. For example, for referencing a player character in a multiplayer game. Some would say it's bad even in a single player game even if you know you only ever gonna have one player, simply because logically a certain character shouldn't be treated as a single special object.

If it's to reference a manager script, it's totally fine if you ask me, though, again, it's a matter of preference and some would say that it's bad.
And indeed they might have a point. Singletons make it harder to do unit tests or make your code modular, such that you can replace implementation easily without affecting the rest of the project structure.
But then again, these factors might never come into play in your specific project.

Do you understand why I say that it depends?

hoary monolith
#

I get it now thanks

novel socket
#

Hello, im a bit confused about the Graphics.RenderMesh function.

From the Unity docs:

void Update()
   {
       RenderParams rp = new RenderParams(material);
       for(int i=0; i<10; ++i)
           Graphics.RenderMesh(rp, mesh, 0, Matrix4x4.Translate(new Vector3(-4.5f+i, 0.0f, 5.0f)));
   }

This works normally
Now in theory i should be able to store the RenderParams outside of the Update function right? so i dont need to create it each frame.. that doesnt work (probally because RenderMesh needs ref/in?).

So since thats not working ive tried to switch the material on the RenderParams like:

rp.material = newMaterial;

But thats also not working, i cant imagine we need to create a new RenderParams with the material inside the constructor for every different object we want to render.

Edit: I forgot whats not working xD, It just renders without any material so its invsible. I can just see the wireframe

scarlet notch
#

    public Material material;
    public Mesh mesh;

    private RenderParams renderParams;

    private void Start()
    {
        renderParams = new RenderParams(material);
    }

    void Update()
    {
        for (int i = 0; i < 10; ++i)
            Graphics.RenderMesh(renderParams, mesh, 0, Matrix4x4.Translate(new Vector3(-4.5f + (i*2), 0.0f, 10.0f)));
    }

this seems to work fine for me, with the renderparams stored outside

#

(just used some random cabinet mesh in a project to reproduce)

novel socket
scarlet notch
#

2022.3.4f1

novel socket
# scarlet notch 2022.3.4f1

thats really strange. im on 2021.3.18f1
Ive create a new Scene with the exact script and its working.
In the main game im doing exactly the same and its not working

scarlet notch
#

hmm interesting, i wonder if there's any differences between the materials in the working vs non-working, or differences in the render settings for the project

#

oh sorry you said new scene, even more odd

novel socket
#

and same mesh

scarlet notch
#

perhaps something else in your scene is changing some graphics settings that's causing it to have an issue perhaps?

#

weird though that it works fine creating the renderparams in the update though, you'd think there wouldn't be any difference

novel socket
#

I know this is bad, but just for testing:

{
    public Material material;
    public Material material2;
    public Mesh mesh;

    private RenderParams renderParams;

    private void Start()
    {
        renderParams = new RenderParams(material);
    }

    int a = 0;

    void Update()
    {
        if(a == 0)
        {
            renderParams.material = material;
            a = 1;
        } else
        {
            renderParams.material = material2;
            a = 0;
        }
        for (int i = 0; i < 10; ++i)
            Graphics.RenderMesh(renderParams, mesh, 0, Matrix4x4.Translate(new Vector3(-4.5f + (i * 2), 0.0f, 10.0f)));
    }
}

Strangely in a new scene material switching is also working

novel socket
scarlet notch
#

this has the smell of something that you'll find and be like "oh my god of course", maybe try disabling everything in the scene and seeing if it works without any other code running (if that's possible in your scenario)

novel socket
scarlet notch
#

well that is very unsatisfying haha

#

maybe now just keep an eye out for if it stops working again and what happened before that

#

actually, i wonder if unity didn't pick up your last code change for whatever reason, and moving the code to awake kicked it in again

#

that's happened to me a couple of times

novel socket
#

I dont think that can be the case, because i made several changes and other changes where visible xD. Will definitly keep an eye on this

runic granite
#

hi, i want to make game object not visible when it's behind other object, both of them is dynamic and the position which the game object will spawn could be use by another game object with different shape, so basically it's like combine between frustum and oclusion culling but without the need of baking it, i already tried "Renderer.isVisible" but the result is not the one i looking for

scarlet notch
dense cloud
#

Is this good coding practice?
I've been doing this where
a script would pass variables as references via GetComponent()

#

correct me but I read it's not

#

since it tightly couples scripts, and would make maintanence and bug fixes meddlesome?

#

also could lead to class explosion

#

kinda like this

novel socket
fervent furnace
#

if they are just coffee with different taste, i would recommend factory pattern (or just simply separate different instance with enum), but idk if right or left detect are monobehaviour

dense cloud
#

I would say very often

#

since the script is being run at every frame

novel socket
dense cloud
#

ah

#

inheritance, and possibly virtual and override methods?

novel socket
#

Jea

dense cloud
#

I've only used inheritance a few times, plus virtual & override for questions in a c# textbook, but I'll do that next time in unity, thanks for the advice

novel socket
#

A_Behaviour has function public virtual void CheckPlayerLeft() and in B_Behaviour which inherits A_Behaviour you can override it like:

class B_Behaviour : A_Behaviour {
  public override void CheckPlayerLeft(){
    ...
  }
}
dense cloud
#

ooo

#

if i remember correctly about inheritance,
the inherited member will need to implement all the methods from the class it inherits from

#

otherwise it will not work

novel socket
#

if you still want to execute whats in A_Behaviour you can do

public override void CheckPlayerLeft(){
    base.CheckPlayerLeft();
  }
dense cloud
#

oh that's a neat feature

novel socket
dense cloud
#

ah

#

I misremembered

#

I'm familiar with those too, but outside of textbook questions I will still need to learn how to put them in use in unity

knotty sun
#

abstract methods. Abstract classes can contain methods that do not have to be redefined

novel socket
#

you also can "save" it on the same variable like that:
public A_Behaviour aaa = new B_Behaviour();
but i think you already know that^^

novel socket
dense cloud
#

iirc abstract classes are used as a generic blue print for other classes to inherit

#

and methods need to be implemented

dense cloud
#

I used interfaces in some textbook questions but barely abstract classes

novel socket
#

non abstract methods in the abstract class will remain

dense cloud
#

been a while since I looked through my notes

#

but these are right I think

novel socket
#

yes you cant do new AbstractClass() you always need to inherit from it.

#

i would recommed to use virtual function instead and just make it work. You can "improve" that later, maybe theres stuff you currently dont think off

dense cloud
#

oh yea I'm not really familiar with abstract classes myself but I'm more familiar with virtual and overriding

#

via inheritance

#

but thanks again for the advice

#

gotta run cya

novel socket
#

no problem 🙂

vagrant goblet
#

Hello, does anyone know a way to convert a Dictionary<int, MyClass> to Dictionary<int, IMyClass> using LINQ? In the case that MyClass implements the interace IMyClass?

Here is a classic way of what I'm trying to do with LINQ:

[SerializeField]
private Dictionary<int, BaseGun> GunBySlotMap;

public Dictionary<int, IGunData> GetAvailableGuns()
{
    Dictionary<int, IGunData> castGunDictionary = new Dictionary<int, IGunData>();

    foreach (KeyValuePair<int, BaseGun> gunBySlot in GunBySlotMap)
    {
        castGunDictionary.Add(gunBySlot.Key, gunBySlot.Value);
    }

return castGunDictionary;
}

Also which way do you think would be more efficient, the above or the LINQ way?

cosmic rain
vagrant goblet
knotty sun
vagrant goblet
knotty sun
#

I meant code wise

cosmic rain
vagrant goblet
# knotty sun I meant code wise

Not sure what you mean. Code wise I simply read the data that is in the interface.

Each IGunData goes to a designated UI slot, where it is displayed

Here is the content of the interface if that helps

public interface IGunData
    {
        public Sprite GunName { get; }
        public Sprite GunIcon { get; }
        public IObservableVariable<int> CurrentLoadedAmmoObservable { get; }
        public IObservableVariable<int> CurrentReserveAmmoObservable { get; }
    }
knotty sun
#

no. I meant how do you access the returned dictionary in code. The contents are irrelevant

crude mortar
#

it's just that GetAvailableGuns sounds like something you would be using semi-frequently maybe, so it seems weird to create a whole new dictionary every time (assuming you call this method more than once).. But anyways, if your BaseGuns are IGunDatas, then why are you casting it? You could just access what you need via the BaseGun class right?

vagrant goblet
#

Encapsulation would go crazy

vagrant goblet
knotty sun
#

I still no reason to do this recasting of the Dictionary

cosmic rain
#

Maybe have it as a dict of interfaces initially.

crude mortar
#

do you actually cache the dictionary you created?

#

the one returned from the method

vagrant goblet
#

No i dont need to

vagrant goblet
crude mortar
#

are you just enumerating over the dictionary or something?

#

after you receive it from the GetAvailableGuns method?

vagrant goblet
#

Yeah enumerating over it and injecting the data into designated UISlots

crude mortar
#

then I would just do something like this instead of allocating a new dictionary (the as IGunData is unnecessary but I think its more clear? up to you)

#

well, I mean I would just use the BaseGun class probably but if you wanted to cast it, you could do this

vagrant goblet
#

Ohh

#

That makes much more sense than creating a dictionary each time

#

So now how do i use this IEnumerable as any other collection?

foreach(var (slot,data) in GetGunDatas())
{
    //Inject the data
}
crude mortar
#

what do you mean by this?

vagrant goblet
#

I've never used the IEnumerable interface directly, but ill just google it, I wont take any more of your time. Thank you UnityChanThumbsUp

crude mortar
#

it is not a collection, it just lets you loop over the results, basically

rocky jackal
#

i have this shader with vertex displacment and i somehow need to figure out if my camera is above or below the surface in script, how could i do that ? i cant raycast to get the hright at the players pos

#

or can i ? edit: no it has no collider

loud wharf
fervent furnace
#

i prefer type the variable type explicitly

foreach(var idk in GuessWhatIReturn()){}
vagrant goblet
#

but instead of int its a var

vagrant goblet
loud wharf
primal needle
#

Hello all. I was wondering if it is possible to load OBJ file and Texture Files from Azure Blog Storage? I have a local Azurite instance running and I would like to test loading a file from the server and displaying it in a scene. But, I have not found any libraries for accessing storage blobs. Anyone have experience in this?

steady moat
crude mortar
#

what do you mean "not necessary"

#

it's just a shorter version of what you wrote

primal needle
crude mortar
#

well, not inline anyway.. you would have to make 2 other variables below inside the foreach to name them

steady moat
primal needle
#

They would still need to reside on a server, right? I would still need to access Azure Blog Storage?

crude mortar
#

in which case yeah, just preference

#

I have gotten used to var

scarlet notch
#

some situations your hand is forced to use the explicit type, just off the top of my head:
foreach (var child in transform) {} - child will be an object
easier to use
foreach (Transform child in transform {} - child will be a Transform

heady iris
#

yeah, since Transform implements IEnumerable, not IEnumerable<Transform>

#

you just get object

scarlet notch
#

yep!

heady iris
#

I prefer var whenever possible

#
foreach (var (key, value) in dictionary)
scarlet notch
#

same here for sure

primal needle
heady iris
#

oh value, you weird contextual keyword

scarlet notch
steady moat
primal needle
primal needle
scarlet notch
#

it'd just be pulled in from nuget in the c# project, try install Azure.Storage.Blobs and chuck a using Azure.Storage.Blobs into one of y our project files and see if unity complains

steady moat
primal needle
#

Yeah I tried adding it to my C# project and the Using Statement doesnt pull it in

#

let me try again

steady moat
#

You need to download the DLL and setup it through Unity

scarlet notch
#

ah I think you're right yeah @steady moat

#

i'm writing blobs from my game but I'm doing it via a http function app call

#

/ reading them

primal needle
hybrid turtle
#

Hey guys quick question I inherit IPointerClickHandler class and overwrote public void OnPointerClick(PointerEventData pointerData)

#

I want to now idenitfy which object is clicked or not within my scene from this