#archived-code-general
1 messages ¡ Page 209 of 1
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
Could probably do some event subscription and process everything inside the method đ¤
that's what i was going to aim for so was checking whether you can just pass a value by ref into a delegate so that when they're invoked in order the value is updated as each goes
you can make components which implement some sort of IAdditionalCalculation interface that you query via GetComponents<IAdditionalCalculation>() and execute its Vector3 IAdditionalCalculation.OnVelocityUpdate(Vector3 oldVelocity) method in a foreach on the main velocity controller
Ah that's a good idea, how do I make sure when getting the component a unique one is retrieved each time?
nevermind
yeah saw components :P
ta v much
those components could also be SOs you drop into a list or anything else really, even a list of delegates or c# objects
unity events would work too I suppose? but think interfaces would be more my jam
no, unity events dont return values
don't need to return values if the parameter passed has the ref keyword though?
what basically want to do is pass a data object/struct through a series of filters
thats called Pipes & Filters architecture
ahh
1000 ways to actually implement it, the key idea is the unified API between all of them, always operating on the same data structure
what would be the advantage to doing SO's instead of interfaces? is it that the SO's can have their own variables too
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
ah yeah
any resources for learning CSharp and improving as a programmer?
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
to learn C# https://learn.microsoft.com/en-us/dotnet/csharp/
to improve as progammer https://www.amazon.co.uk/
How do you assign the interfaces to a list??
wdym?
as in you have a list of the interface and set the scripts?
mb probably a dumb question
you can only do that in code
Example: `
private List<IFilter> _filters;
void OnEnable() {
_filters = GetComponents<IFilter>().ToList();
}
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?
what if you did new List<IFilter> and had a script inheriting from IFilter AND monobehaviour attached to a gameobj, can you not assign it in the inspector like that?
also does: https://docs.unity3d.com/ScriptReference/GameObject.GetComponents.html
Get components in the order they appear in the inspector?
that is not guaranteed
ok in that case i'll just do a list of SOs
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?
One option is to give the class an "init" method
Which will (roughly) work like a constructor
var myFlorp = Instantiate(florpPrefab);
myFlorp.Init(importantInformation);
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?
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
nobody knows except Unity
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
I'll say this... only the parsing function seems to be a native function. The other stuff seems to be done in C#
https://github.com/Unity-Technologies/UnityCsReference/blob/258abdf1d3dd9c35c4494d7b7acd3f1ce3d9ae84/Runtime/Export/Math/ColorUtility.cs#L9
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
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
If they don't know about it they're not likely to fix it ÂŻ_(ă)_/ÂŻ
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"
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
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Could you please help me understand why the jittering occurs?
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);
}```
.Play() will stop the previous sound and start a new one. Use .PlayOneShot(AudioClip), and pass the clip to the method
I think that did it, along with removing and reinstalling the package. I swear it was still broken and I went off to tinker with other settings, but on second glance, the scripts are importing again. Now to fix the broken SO assets...
When you have a joint, is there a difference between (joint on A, connecting body B) and (joint on B, connecting body A)?
Not sure if this is viable, but I was able to bypass the errors by checking the editor checkbox under "Exclude Platforms". It's only used by some of the assemblies I imported and shouldn't be needed by any unity editor code, so hopefully this will work just fine.
Using an audio clip works! I'm still confused about why using Play didn't work, because there is a time delay set with the Coroutine that is > the clip length?
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
I wouldn't be surprised if the audio source only decided that it was done playing after the next update
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
the goal is to move the player to the middle of the screen with a circular motion
Can you give me a drawing showing the motion you want?
wait youre right if i do vector2(2, 2) it works
yeah give me a second
you can picture how Slerp works by imagining a sphere that your starting point is sitting on the surface of
my drawing skills on paint are horrible ignore that
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
then i have to find the middle inbetween the 2 points?
If you can pick a pivot point, you can do something like this
Vector3.Slerp(start - pivot, end - pivot, t) + pivot;
You're better off rotating around a pivot instead . . .
I'd have to think for a moment on how to pick that pivot
You would be looking for a circle that passes through (3,4) and (0,0)
There's probably a clever formula for that.
There will be many solutions.
That would spin you 180 degrees around the median point
from there
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
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
Any point that's equidistant from the start and end would work, I think
because that, by definition, makes a circle
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);"
Unity gets stuck recently after adding Editor/Play Mode tests to my game.
which script? which line
The client script line 40 "recv = newSocket.ReceiveFrom(data, ref Remote);"
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();
}
}```
are you sure you're correctly formatting the data
this code will only do one or the other
Pretty sure you shouldn't be trying to listen and send on the same port
How would I be able to wait until _timeline.Play() is done then run the reversePlay() coroutine and create a cycle between the two
is what I've been trying to do
use yield statements to wait in a coroutine
use loops (e.g. for and while) to repeat code (anywhere)
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
this will play once, then reverse play once
it doesnt even reverse play
then likely while(!_timeline.time.ApproximatelyEquals((float)_timeline.duration)) the condition here is never true
What is _timeline?
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
Doesn't the playable director have events like https://docs.unity3d.com/ScriptReference/Playables.PlayableDirector-stopped.html you can listen to?
You could also use https://docs.unity3d.com/ScriptReference/Playables.PlayState.html right?
using the time seems sketchy
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
I can't figure out why this code is reading null
which code
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
is the variable null or is it empty
null
its printing this
wdym
the nullexception was the next line where I try to parseint from it
did you read the documentation for ReadLine?
you're just returning/printing the last readline result here
BTW why not just use string fileText = File.ReadAllText("Data.txt");
ooh good idea then I can string.split("\n") and get everthing in a neat list
thats probably faster too
I'll switch to that
how does ReadAllText deal with large files?
it loads the whole file into memory as a string
o
𤌠im dumb
oh ok so larger files is better to use readline with stream
even a few megabytes of text data should be completely fine
computer fast
vroom vroom.
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.
hey if anyone knows of a solution to making this run past one iteration. Ive already tried wrapping it in while(true) pls let me know still sort of stuck it's the last piece of what I need
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
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
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?
They donât respond to any forces
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
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
that sucks. Do you have a recommendation for achieving that effect?
A custom kinematic solver, maybe built on top of KCC
!code
đ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
đ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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;
}
}
for some reason the raycasts arent in the same direction of the enemy when he rotates
ouch. i will look into this. I am at witâs end
Is it possible with the InputManager(the old one) to make a key rebind at runtime especially when using things like GetAxis?
You can create a class that remaps each keycode dynamically, but I think the axis are fixed
Is there a reason or knowledge barrier stopping you from using the new InputSystem?
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
Nope thought I do it the old fashion way but seems like with the "new" one its possible to change it runtime easily?
Yes, there is even code assist for rebinding keys, like you tell the InputSystem the user is about to rebind the key for "Forward" and it will do it on next keypress, with configurable ignored and cancel keys
Okay that is a good idea. thanks alot. i did realize that using Vector3.forward instead worked
Ok Ok is it easy and straight forward to change from the old to the new one?
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
Alright thanks mate
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).
You just answered your own question no?
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
i sure hope that timestamps from different times are unique
they'd be very bad at doing their job otherwise
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
To be clear the unix timestamp is "the number of seconds elapsed since January 1st 1970 midnight"
Gotcha, so that does make it easier
Anyway couldn't you just write a quick loop to verify their uniqueness?
I created these entries, and forgot to add an ID property, but I'll add that for future entries
Where are you storing these things?
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.
Write a quick tool to iterate over them and give them IDs
But the timestamp as an ID helps me maintain this
That's true, but I'd have to go through every user
I will eventually do that in the next few days, but needed a quick solution for now to maintain funtionality
Is this in Firebase or something?
The server is a javascript program I wrote hosted on AWS
and acts like Cloud Functions of Firebase
but AWS version
Where is the server storing the data
Dynamo
Dynamo is finnicky, I can't just easily edit everyone's entries and include a new property
Ok and dynamo requires a key for every document, no?
I can do that through code as you suggested above
the key is the user itself, and the value is their list of entries
So you can also use the (user id, order in list) tuple as a guaranteed unique key too
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
I'd just prioritize migrating to a real ID ASAP
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.
Getting something from an array by index is extremely efficient. Then call Destroy(thingIWantToDestroy); đ¤ˇââď¸
Or, if you don't know the index, I guess iterate it or use Linq, which are far less efficient but are perfectly fine to do.
How big is the array, and how often does this need to be done?
The array is 9 items long. I want to delete the first item in the array, that is, 0.
9 items maximum. It may be less depending on how many players are in the game
Ok, then just get the item, and call destroy on it.
With an array, the length is immutable, so you'll have an empty index at 0.
Is that ok?
You could use a List and do RemoveAt(0)
I tried that and I got an error.
What did you try? And what error did you get?
I tried Destroy(players[0]) and I got an error saying it was out of bounds.
Does the array actually contain anything? The error is saying it doesn't...
Yes, it contains a player object.
Check .Count of your list
How can i limit a object's rotation between a negative value and a positive value on the x axis in 3D?
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
player won't teleport to a position given by the script when the scene loads, how can i fix?
any errors in the console? is something else affecting its position? have you confirmed this code is actually running?
nothing affects the position, the player just spawns where it usally is in the scene view
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?
no
im playtesting to see whats the issue
okay can you answer the two other questions i asked then
the code should be running
have you confirmed that it is, or are you just making an assumption?
the code does not run when i replay the game
well there we go. is the component attached to an active object in the scene?
by component you mean script?
yes, your script there defines a class called CheckpointLoader which itself is a type of component
when i switch to the scene there aren't any errors and it says it has loaded the data
so you have confirmed that the code is running? but it is still not working?
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
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
ill try that
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
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
CheckPoint 99 is a special level
just a little note
it says the player is in that checkpoint
but they're at the start
screenshot the inspector for the player
i've also noticed something
when i reopen the game i go to that specified checkpoint
PlayerPrefs are saved between sessions. if you are not resetting it anywhere then it will always be that
reset?
how do i do that
you can either set it back to some other number or delete the key
yea i even tried attacting a script to each object that it would refrence and use that to control teh gameobject and that still didnt work sorry if that wasnt for my comment im probably beeing stupid
show the relevant code
i set the checkpoints with the set int
where
just an example but this is how i usally save my player prefs
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
still waiting on this too, btw
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
}
}
!code
đ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
đ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
sorry ill do that rn
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]);
}
}
sorry
i didnt know you had to do that with character controllers
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
It should be fine once it's on the navmesh again
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 đ
The issue you're having is unclear to me. What does "I can only get one or the other to cancel each other out" mean?
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
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
Alright, makes sense. I'll give it a go - thank you!
Do I have to call some function to attach it? Because if I instantiate it at 0,0 and then move it onto the navmesh, no dice. Doesn't work.
Or maybe I'm trying to set the destination before I actually move it. Hmm.
Got me thinking anyway. Thanks.
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
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
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.
@spice latch @left anvil
Better ask in #đąď¸âinput-system
ok thanks đ
Probably better ask in #đ¤Żâaugmented-reality
when working with linq is it advisable to convert the collection to an array or should i try to work with ienumerable?
@cosmic rain I already did yesterday, was a bit impatient so I just crossposted. Thanks though.
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.
as a rule of thumb if you're going to access the sequence multiple times you usually want to collect it into a collection first, otherwise it'll evaluate the sequence again every time you iterate through it
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)
Hey man, obligatory "thank you" đ I have now fully implemented cinemachine and its like upgrading from a sedan to a mercedes đ
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
i see. does this work for 2D?
iâve looked into it before, but it looks really for 3D
it does not
does anikki maybe mean to look at how it is implemented?
was there context that it had to be 2D?
I'm trying to access URP cast shadow and additional light shadow to disable them, how would i access that by code?
i donât remember if I told him 2D
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
are you talking about a camera property?
Or something else
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)
first place to look would be the docs for that asset https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@17.0/api/UnityEngine.Rendering.Universal.UniversalRenderPipelineAsset.html#properties
I just linked to the code documentation
i click it, no code
wdym "no code"?
It's a doc page
it's a list of properties and fields and methods you can use in code
which property in particular
thats the renderer pipeline asset
its not in that list, but its in the inspector, and thats what seem to turn off and on shadow in scene
it's get only though - you'd need to configure two separate assets and swap one in that has the setting you want
almost impossible i cant disable shadow directly
cant make an asset for every possible settings a player want
Does this not work?
https://docs.unity3d.com/ScriptReference/QualitySettings-shadows.html
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
Did you actually test it?
yes
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.đ¤
too many
Could also probably set shadowDistance to 0
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
How are you setting it?
Aight. Then I guess it doesn't work in urp.
ya its somewhere else and google and chatgpt have no idea, doc doesnt say either
cant beleive no one using urp disable shadow
Setting the shadow distance to 0 would have the same effect.
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.
hi, does unity 2021.3.2f support default interfaces ?
if you mean default interface implementations then no.
Not even the 2023 version.
I believe they are waiting for the full migration to .NET core with that.
oh ok
cant you just use abstract classes?
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>
Correct.
Slowly remembering this engine
a GameObject is always just a GameObject
it has components
but it is not, itself, a component
This is closer to how Unreal does it; objects in the world can be a specific type, rather than everything just being a GameObject
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
yeah, that changed in ...2017?
That was a WHILE back
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
Is kinematic character controller performant if you have like 500 controlled bodies for it?
you are better off looking for a benchmark online or doing one yourself
Assuming you're referring to the asset store one. They have a benchmark scene included you can use
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?
nah cuz allready implementing some and as i remmeber i cat have multy class inheretance
Can you tell me about your usecase? maybe there is a pattern to use for you
What does the list contain? If you could use some value to sort it, you could easily apply any search algorithm and reduce it from O(n) to logn
Right, it's just game objects, and they have a vector3int value which is the key to the dictionary<vector3int, gameobject>
Default interface implementations are available. They won't let you achieve multiple inheritance, though.
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.
The only issue with sorting is now you'll have to keep it sorted while inserting and stuff, but since you're using vector3int it should be easier to sort. You can sort based on either some combined xyz value or each component individually. Just make sure when swapping elements, you do it from both lists at once
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
they landed in C# 8.0 and unity supports C# 9.0 right now
Hmm if theres no guaranteed structure to the list, then you're unfortunately just left with a linear search
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
sparse set again....
fast O(1) look up insert delete unordered data structure...
well, you need order to make a dictionary
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.
is it actually a problem?
or is it just a potential problem
maybe you can just filter the dictionary every now and then
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
Don't you only need to have the list form when you serialize it again?
sparse set is a wrapper of list and dict together, idk if this fit your needs
if you're performing the (de)serialization yourself, do the filtering then
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?)
right, that's an option, but the bigger problem is I have to clean up the list even before then because the dead references can grow pretty quickly
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
how can i pass more then one variable through a unity event calling a function ?
UnityEvent has several flavors for multiple arguments. https://docs.unity3d.com/ScriptReference/Events.UnityEvent_4.html e.g.
note that you can't mix and match argument counts
but let me check that..
This is all done during editor time, if I didn't mention that, so I do have unity serializing the GOs for me when they are on the scene.
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
It didn't look like I could use a UnityEvent<int, int> to pass an argument along to a method that takes a single int argument, though.
in case you were curious about that
I tried it out. it does start to lag a bit, but also 3D is way worse than 2D
thank you
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
Thatll be the case for pretty much anything
Yeah, technically I just need to repopulate it when I save, so that's probably another option if having some event to repopulate it on when you save the project.
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?
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.
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
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;
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.
We don't offer modding help here, as it's against the server rules. See #đâcode-of-conduct
It's against the server rules
I do not make the rules
am i doing it wrong https://dotnetfiddle.net/8jbjW2
Test your C# code online with .NET Fiddle code editor.
Too late :)
((TheInterface) x).TheMethod();
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
If you want to argue about the rules, do so in #531949462411804679 and a mod will reply
This is a code channel
The idea is that existing implementations of the interface don't need to change.
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.
Hmm... That sounds complicated đ . I'll have to give it some thought on how I might be able to integrate that with the code I already have.
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
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.
Nvm, fixed this. I had to used "localEulerAnglesBaked" as the binding keyword instead of "m_LocalRotation
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.
!code
đ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
đ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
gottcha ty
its backticks`` not '''`
there we go ty
I don't think the error comes from the script you posted. Do you have another Player script in the scene by chance? What happens when you click on the error? And write out the full error, those look like Debug.Error() messages instead of Unity errors
one of them does from a warning they're logging
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.");
}
}```
ohh
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.
not code question
#đťâunity-talk
where is the code you're asking about
this isnât a code question channel. this is a channel where you discuss code. did you read the channel description?
there should be a player variable in that script that you need to assign in the inspector. Your first script is working ok.
So which coding concept are you asking about ?
iâm asking a question regarding code
all of it. iâm asking how difficult it would be to recreate a game like it to learn. why are you uptight rn. itâs not even that serious
what ?
iâll just go to #đťâunity-talk then.. since you clearly arenât going to answer
the game is composed of many system, your question is very vague
Relatively hard, do you know what ScriptableObjects are? It's worth trying though, since you will learn a lot.
scriptable objects, i donât know how to make them or even fully know what they are but (from what I know) they are objects that are modular and easily customizable. like a template essentially
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#
everything in c# is an object
yes, i know
ScriptableObject is strictly a unity concept
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.
thanks đ
making regular classes the concept is the same.
ty, that was it, I forgot I made a new prefab and the Prefabs of my Bears were calling for the old prefabs reference which isn't in the scene anymore.
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?
đ
Is there any downside to using rigidbody.velocity for kinematic rigidbodies? (in 2D, they do move with velocity)
!code
đ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
đ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
use link
I'm assuming there's a question?
where are u passing path
from what you shared I don't see the constructor path being passed anywhere
unless im like blind
Where I use DataPersistentPath ?
public FileDataHandler(string dataDirPath, string dataFileName, bool useEncryption)
{
this.dataDirPath = dataDirPath;
this.dataFileName = dataFileName + ".game";
this.useEncryption = useEncryption;
}```
where are you passing dataDirPath
My bad I forgot a script
sorry
all good. you can try Debug.Log to see where its ending up
ideally use on screen console
or check player logs
I have a debug.Log
in the save method?
and are u checking the logs text file in the Build not in the editor?
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
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
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 đ¤
it can happen
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...
hmm loadedata prob null
idk what u mean works
is there any way to make a joint send force from RB 1 to RB2, and not visa-versa?
The data file has been created
yeah but your error is with Loading
Ok I take a look
I will come back if I can't resolve the problem.
Thanks for the help
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;
}```
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 đ
That's my own method to get around bad deltas.
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.
https://forum.unity.com/threads/touch-delta-switching-positive-negative.1051283/ This bug describes the problem that I was having.
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.
Ah, yeah I see what ya mean about it
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.
Following my question in #đťâunity-talk
how can I have a system like a spring arm (godot) for a cinemachine freelook camera?
What's a spring arm
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."
is there a way to check which areas a calculated path goes through prior to traversing the path?
Cinemachine has CinemachineCollider for that
In what context? What kind of calculated path
@leaden ice thanks ill look in to it
a* pathfinding
How do you define an "area"
or volume. say it's just a general 3d rectangle
Nore that you're probably talking about the specific asset from Aron Granberg but A* is a general purpose pathfinding algorithm
no, actuall unity's built in a*
You mean navmesh?
For either of them you can do raycasts along the path against trigger colliders that definite the area
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
Or SphereCasts
ah ok
No there's no built in way
gotcha, thank you
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.
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
There's no best way but one good way is a ScriptableObject called something like "LootPool" which you can assign on enemy prefabs and contains the pool of items that enemy might drop (along with weights)
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.
sweet okay thanks
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
I like that and makes me think of D2. So you use SO to construct the item instead of spawning a prefab?
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.
got it so like a universal drop prefab that has information filled in
good way to do it to save a ton of space
Pretty much. I only use monobehaviours when I really need it. But technically the item can stay data until then.
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
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.
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
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?
its one of its children
slider is just bunch of image components put together with some magic
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?
yeah the image component
just get the image component and theres probably some property
ok makes sense thank you
color prop
UI is rendered differently and you usually wouldn't touch it's material. You can adjust the color property of the image component.
var color = image.color
color.a = myalphaValue // 0-1
image.color = color
awesome yeah just accessing color prop of image and changing alpha thanks again @rigid island
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
yes, except you need to assign your modified color to the image on each iteration
where is this script placed?
maybe you need alpha -= 0.1f * Time.deltaTime so its not so quick
called StartCoroutine() in Start and yes I agree I should multiply by Time.deltaTime
but even then it has no effect
when run
did you pass the value back to the same image component
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
if this script is like on a parent object / scene you should considering make a inspector reference field
that line gets a copy of the Color, and you're modifying the copy which does nothing
then just plug it in, skip GetComponent
Yes I should make an inspectorRef field to begin with my approach at first was wanting to get all gameobjects of the parent and affect their color
I just want to be able to fade away a slider over time
you probably want all the image components
put them in an array
loop through them
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
GetChild(0).GetComponent<Image>
you're only looking for 1 child
just make a [SerializeField] private Image[] sliderImages
drag the components in
ok yeah that is best
yeah it only has the background image
but script is still not working for that
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
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
did you assign all the image components?
it should be working..
hmm let me try
Show your code.
ok yeah I didnt assign an image component
it works but yeah its weird because of loop
yeah same here
it does 1 each
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
might also be the coroutine
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
nested inside
gotchu
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.
ohh ok and sepearte for loops for each color?
so three for loops in the while loop
yield at the bottom?
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.
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;
}
}```
yeah ofc make a filed
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.
yes, since you're subtracting a constant amount of t per second
yes so can i use like pow then do that
what do you want?
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
Might want to use a lerp instead and modify the time in a non linear fashion.
This would just result in a different constant number though.đ
Oh shoot yes youâre right I didnât see
For non linear interpolation, the change amount needs to change over time.
If you use lerp, the the "something changing" itself needs to change non linearly.
Possibly
That's the same as what you had before.
Ah
Maybe not
Yeah, that should work.
Aside from the -
The third parameter needs to go from 0 to 1 or the other way around.
Ok nevermind would it work?
With lerp, you don't subtract anything. You interpolate between 2 values.
Yes makes sense
If your t is going from 0 to 1 or the other way around, and you remove the minus, it should work.
Yes it should be so Iâm gonna give that a shot
Assuming you want to use the result of the lerp as the alpha value.
Yes of course Iâm still thinking though like it seems too trivial almost
Iâll have to try ofc
Rather than messing with how you change t, just remap the value
t -= Time.deltaTime * 0.12f;
float effectiveT = Mathf.Pow(t, 2);
This would make effectiveT fall off quickly at the start
Oh I see that is plausible too
Is there a way to add a new overload functions and constructors to a pre-existing built in function?
well, functions don't have constructors
you can declare "extension methods" to add new instance methods to existing types
- Functions don't have constructors.
- Assuming you meant a class, no. Unless it's an extension method that you want to add.
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?
Take a look at this article here: https://ironpdf.com/blog/net-help/csharp-extension-methods/#:~:text=To create an extension method,this is an extension method.
It explains extension methods
You could inherit the class to overload it's constructor. Though, you'll need to create the new class instance explicitly, which wouldn't work if you expect existing API to use the new constructor.
There must be a work around however it may be better to write a simpler class with only the functionality you want and use the built in functionality of the other class to help define the methods
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?
you didn't say what the problem was. Persisting the player GO itself from char creation sounds like the wrong approach to me though
Oh, the problem is every refence to the player in the next scene is Null.
is the player a root GO?
yes
does it appear in the DontDestroyOnLoad scene when you change scenes?
Yes
do you have another player instance in the scene you're changing to that overwrites its entry?
no, im guessing i should?
Why would you? it would replace the other entry and generate a warning according to your own script
I thought you meant The Player GO would overwrite the lets say playholder player GO
well, now you should set some breakpoints and walk through your code a line at a time
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.
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??
In 3 years it doesn't seem like you ever learned how the function works
yup got it need to have a new_rotation_angle = mathf lol
It's not that complex, spend about 10 minutes to try to understand what it does.
https://twitter.com/FreyaHolmer/status/1175925033002254338
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
also passing it just deltaTime for t is not very useful
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)
yup and you get to avoid issues with euler that way to
Trying to Vector3.Lerp euler angles sure would be interesting
yeah that i didnt know. i though it would just change the 'a' var lol
yup fixed it after i got it working.
just wanted to add a slight camera tilt like in the quake games. using animations made it look bad and janky ig so yeah
i will also try this thanks alot. never actually knew this method existed
wait there is the transform.Rotate what is the difference ?
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
Which line is 288?
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:
- 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.
- The balls will destroy themselves after the lifeSpan (in seconds) is over
- 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 ??
don't crosspost
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?
(int)enumValue
Tried that, doesn't work 
ah, it's because you are restring E to unmanaged rather than to an enum
I can't use enum/int as a type constraint, unfortunately. Compiler gives me an error if I try
well it would be Enum not enum but i'm not 100% certain if that would work for burstable code
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 
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); }
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.
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;
Ah ok sounds good. Ill look into resources folders
what are you trying to do with these? is this some editor functionality?
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
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
Sounds good, and Im guessing use LoadAll with typeof(TextAsset) for getting all textasset files in the filepath?
i've not personally used LoadAll but yep i'd assume that'd be the case!
Sounds good! Ill look into it some more if I run into any problems. Thanks for the help!
no bother, good luck!
Thanks I need it 
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.
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?
It depends on many factors and preferences. You need to look at each case individually to say wether it's bad or not.
So when does it usually become bad? I plan to use a singleton for my Data Persistence Manager is that a good idea?
I'm pretty sure the order that it's displayed in the scene window is the order they appear in transform, so
foreach (var child in transform) {
}
will loop through each child in order, if that helps? what exactly are you using the index for?
just need unique persistent index along asset guid
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
nah, literally need unique asset + child index (for whole hierarchy)
void Start()
{
var i = 0;
foreach (Transform child in transform)
{
Debug.Log($"{child.gameObject.name}: {i}");
i++;
}
}
this should get you started
prints:
dw about it
if you're traversing the whole tree you'll need some recursion going on
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
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
Most of the time I've seen people will say it's bad when they're using DI (dependency injection). The youtubers who call it bad are probably just preaching what they've heard if they arent explaining why.
You'll probably be fine using it for your use case.
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?
I get it now thanks
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
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)
wow, which unity version are you using?
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
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
using the same material xD
and same mesh
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
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
jea i also dont understand this
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)
im a bit confused now... now its working. Actually i just moved new RenderParams(material); from Awake to Start. Than i thought thats cant be the reason and i moved it back to Awake, now its also working. It makes no sense haha. Unity restart also didnt helped. Maybe it has something todo with the new scene? I dont get it
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
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
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
yeah keep an eye out, a frustrating one haha
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
I think this hardly depends how often you will use that "A_Behaviour" and what exactly Right/Left detect and CastingRay is doing
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
I'm still a novice at AI behaviours, so this is definitely not the best way to go about
But A_Behaviour controls the AI of the archer ,
Right/Left detects if the player hops over to the left or right large collision boxes, flip sprite & firing direction
casting ray manages the ray that shoots only the player tagged object,
if the ray returns the collided gameobject tag as "player"
I would say very often
since the script is being run at every frame
Maybe if its just doing simple stuff you should consider using virtual functions and override the functions when the behaviour changes of another inherit class, instead of creating a massive amount of classes foreach A_Behaviour
Jea
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
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(){
...
}
}
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
if you still want to execute whats in A_Behaviour you can do
public override void CheckPlayerLeft(){
base.CheckPlayerLeft();
}
oh that's a neat feature
no it dont need to, thats only for interfaces or abstract classes
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
abstract methods. Abstract classes can contain methods that do not have to be redefined
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^^
Jea, abstract methods in abstract classes needs to be defined
iirc abstract classes are used as a generic blue print for other classes to inherit
and methods need to be implemented
yes
I used interfaces in some textbook questions but barely abstract classes
non abstract methods in the abstract class will remain
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
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
no problem đ
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?
With linq it might need to allocate intermediary collections. Generally, if you're looking for efficiency, manual looping is better.
why do either ?
What alternative would you propose 
what are you doing with the Dictionary when you get it back ?
The dictionary with the interface goes to the UI to be displayed
I meant code wise
Maybe you can do it with Cast. I'm not sure. Never had a need to do a conversion like that:
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.cast?view=net-7.0
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; }
}
no. I meant how do you access the returned dictionary in code. The contents are irrelevant
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?
BaseGun class has functions like Reload, Shoot, which is not data so its something UI essentialy doesnt care about.
Encapsulation would go crazy
But yeah you are right i use it basically just once to initialize the UI
I still no reason to do this recasting of the Dictionary
Maybe have it as a dict of interfaces initially.
No i dont need to
The dictionary is serialized with OdinInspector, i cant serialize an interface unfortunately
are you just enumerating over the dictionary or something?
after you receive it from the GetAvailableGuns method?
Yeah enumerating over it and injecting the data into designated UISlots
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
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
}
what do you mean by this?
I've never used the IEnumerable interface directly, but ill just google it, I wont take any more of your time. Thank you 
it is not a collection, it just lets you loop over the results, basically
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
I don't think the var keyword is necessary there? 
Idk.
I normally do it like this foreach ((var slot, var data) in GetGunDatas())
i prefer type the variable type explicitly
foreach(var idk in GuessWhatIReturn()){}
both methods would work.
Its essentially this:
// what im doing
int a,b;
// what ure doing
int a;
int b;
but instead of int its a var
Thats true, but i used var for simplicity sake. It is easier to read in quick discussions like this imo. In the code i use explicit types.
I prefer deconstructing tupples or structs with deconstructor on the first line if possible.
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?
If possible, use AssetBundle instead of Textures Files and OBJ files.
So you prefer 2 vars instead of one.. ?
what do you mean "not necessary"
it's just a shorter version of what you wrote
I am not sure I have an option since the server infrastrucutre, with the obj files and materials/textures, were developed first
but then you can't name them
well, not inline anyway.. you would have to make 2 other variables below inside the foreach to name them
Then take sometimes to convert those into AssetBundle. That is going to simplify your work a lot.
They would still need to reside on a server, right? I would still need to access Azure Blog Storage?
oh unless you were showing that as a counter-example
in which case yeah, just preference
I have gotten used to var
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
yeah, since Transform implements IEnumerable, not IEnumerable<Transform>
you just get object
yep!
same here for sure
Maybe I don't understand AssetBundles enough, and I will research them, but I am not sure how that would change the fact that the assets reside in Azure Storage and I need a way to pull them down? Do AssetBundles help with that?
oh value, you weird contextual keyword
pretty sure you can just use the azure blob sdk to pull them from storage, fairly sure its supported in unity (don't quote me on that)
They will help in reading those assets. The rest is standard C#.
Yeah, its that part I need assistance with. I can look into migrating to AssetBundles but I still need to store them all on Azure and pull them down.
I thought so too but I dont see any azure libraries in Unity Package Manager
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
Pretty sure that you cannot use nuget with Unity
Yeah I tried adding it to my C# project and the Using Statement doesnt pull it in
let me try again
You need to download the DLL and setup it through Unity
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
Any documentation you are aware of, of what DLL's I need to bring in and how to do that?