#archived-code-advanced
1 messages Β· Page 199 of 1
Thank you!
Color32 is 4 byte values in range 0-255 tho
Easier to use Color32 bc it hasbyte as the type for r, g, b. You can add 1 to it since it's range is from 0-255 . . .
making progress. i got the rgb to count by 1 but problem is actual solid color of camera renders automatically to 255. doesnt count same way text ui is rendering the count for rgb values
this is my code
33-36 and 39 are wrong. Main issue is creating a Color instead of a Color32. Color takes floats 0-1. Why not assign color directly to cam.backgroundColor? They're implicitly convertable
And also the problem might have been that he has been adding to color variable that's why the color had been changing, right?
The problem was creating a 0->1 colour using 0->255 values on line 39
i have multiple 2d triggers as seperate child objects on a parent object. Now the problem is that they wont detect collisions unless either one of the colliding gameobjects, has moved. I have a player and an enemy and the enemy has a player detection collider for moving towards the player and one for detecting the player close by in order to attack. They detect collisions once and wont until the player gameobject moves again. what is the issue here
so in python there's this method called repr which gives you a string with explicit escape codes & surrounded by quotes to see trailing whitespace:
In [3]: x = '\t '
In [4]: repr(x)
Out[4]: "'\\t '"
```is there any equivalent in c#?
Check your rigidbody sleep settings. I've seen others have this problem when the rb is going to sleep unreasonably fast
Hello, could someone help me understand how to complete this? It seems simple but I am having trouble understanding the part about overlaying two cameras on each other towards the bottom, let me know, thank you.
Hey guys, suppose I have a big 2D array as attached. What are some more optimised algorithms I can use to find the surrounding 1's around each 0; diagonals included? And when that edge has been generated, the same: finding the surrounding 1's around them
I.e:
So I am working on a script to cut objects, It worked fine but the program doesnt handle high poly meshes well. So i started to try parallel jobs with burst.
Now the problem is that each time I add a triangle or vertex I must check if they already exist in the upper or lower half array. This is so that i dont add it and I find its corresponding index for the index list.
Now each thread is independent of the other, and will be adding to their own lists.
How on earth do I now make a mesh whilst being unable to have each thread read and effect the same data
Its set to start asleep
should i change it to always awakw
So similiar to bucket tool on drawing programs? If thats the case, take a look at flood fill algorithm, theres multiple more and less optimized variations of it (theres even wikipedia page about flood fill)
It's like the inverse of a bucket tool. Like if I have a connected group of zeros, I'd like to have a ring of say "2s" around them, then a ring of "3s" around the "2s". Only replacing the 1s each time. However, I also dont know where the groups are because I'm planning to generate them using types of noise algorithms. My current strongest algorithm is to loop through the array and check the 1s to see if they are adjacent to a zero and if so convert them to a 2 for the first iteration
so in python there's this method called repr which gives you a string with explicit escape codes & surrounded by quotes to see trailing whitespace:
In [3]: x = '\t '
In [4]: repr(x)
Out[4]: "'\\t '"
```is there any equivalent in c#?
Nope, python has all kinds of crazy stuff.
lol f
Well hey maybe there is some obscure method after all!
Python probably has a built-in function for folding your laundry.
import laundry
anyone here know how to use configurable joints? im losing my mind a bit
anybody in this chat know how to setup isometric tilemaps in unity?
other chats didnt respond
i have this open but unfortunately it doesnt fix the issue i have
it looks like you're getting help in beginner. Don't split the conversation
which is that the grid never seems to fit my sprites no matter how much i tweak
sorry I responded here
I am trying to cancel a mousedown event, while the mouse button is still pressed down. Can someone guide me into accomplishing this please?
Not entirely sure what you mean, but there's CancelInvoke to cancel invocation of an event
Anyone know how I can use unity remote 5 I have iphone 13
Look into QuadTrees to improve the performance of your edge-detection algorithm. Also, try to convert it to Burst-compileable code for even more significant performance increases.
Any idea about source generators?
Are they supposed to be outside of Editor folder?
I mean exactly dll and assembly def of generator code
Thank you I'll take a look in a bit π
Hello !
What's the correct way of finding an UI element and enable it ?
I thought I could do it like this but it doesn't work :
public void OnAwake()
{
planetInfos = transform.root.Find("MainCanvas/PlanetInfosCanvas").GetComponent<Canvas>();
planetInfos.enabled = false;
}
public void OnPointerEnter(PointerEventData eventData)
{
planetLight.enabled = true;
}
this problem is usually called "edge detection" and whatever you do with spatial lookup, you probably want to use a data-structure optimized for the lookups you perform most often, most aim at nearest neighbor lookup. for your problem you need an edge walk, that would not need an optimized structure though since it a grid and the neighbors you need to check are in predictable locations.
Hey! I need to get the surface Normal direction of a raycast Hit. Can anyone please point me in the right direction ?
Hey guys, can someone help me with a webgl thing?
When you have a webgl build on your website's server, does it automatically keep creating the a webgl folder? Because we don't need the 'webgl' folder, we put the build in another folder. But for some reason the webgl folder keeps coming back on our server
causing us to get a 403 error
Are you looking for SetActive(bool) ?
No, my planetInfos is null, though my objects look like this :
The script I'm writing is attached to the planetMesh
Any reason you can't just cache the reference to the planetInfos? either set planetInfos public or [SerializeField]?
Because i'm attaching this script to each planet, and i didn't want to set everytime the ui to my objects
but if its the best way to do this i'll do it that way
Well, OK - there's many ways to skin a cat, but I definitely would try to avoid the way you have now. Say in the future you cahnge "PlanetInfosCanvas" to "PlanetInfoCanvas". Now suddenly the code breaks. Rather, is there some sort of special script on that InfoCanvas which is a singleton and you can search for? I.e. FindComponent<PlanetInfoCanvasScript>() ? That will search the entire hierarchy and return the first one it finds. If you know there will only ever be 1, then that's a good fix
Yeah i guess that's my best solution, attach a script (I will still need to do that after to close my window for example) to the canvas, so I can retrieve the class instead of the object
if I understood you correctly
(I'm coming from a β world, so this is a bit different to me π )
it's more like you're using the script as a tag, and saying "find me the component with this script attached to it"
Still, the script itself will be useful
so it wouldn't work if there are ever two of the PlanetInfosCanvas in existance
but if you know there will only ever be 1 instanciated at a time, you're good
Yeah, there will be one window, with dynamic data in it
Thanks for the advice π
np
anyone knows why rider unit test in play mode takes 2 minutes?
i literally have only ```
[UnityTest]
public IEnumerator UpAndDownSelection()
{
Assert.AreEqual(true,true);
yield return null;
}```
Anyone know how to determine forward in a 2D Isometric game?
that's all up to you and how your sprites are laid out
im using an enum to set what direction im walking - ie UpRight / UpLeft etc. Then i just switch on that enum, and if UpRight, i draw a line from my position to my position +1 x and y
{
UpRight,
UpLeft,
DownRight,
DownLeft
}
void OnDrawGizmosSelected()
{
Vector3 _target = new Vector3();
switch (PlayerFacingDir)
{
case PlayerFaceing.UpRight:
_target = new Vector3(transform.position.x + 1, transform.position.y +1, transform.position.z + 0);
break;
case PlayerFaceing.UpLeft:
_target = new Vector3(transform.position.x - 1, transform.position.y + 1, transform.position.z + 0);
break;
case PlayerFaceing.DownRight:
_target = new Vector3(transform.position.x + 1, transform.position.y - 1, transform.position.z + 0);
break;
case PlayerFaceing.DownLeft:
_target = new Vector3(transform.position.x - 1, transform.position.y - 1, transform.position.z + 0);
break;
default:
break;
}
Vector3 targetDir = _target - transform.position;
Gizmos.color = Color.blue;
Gizmos.DrawRay(transform.position, targetDir);
}```
This works great
but the angles do not line up with the tile grid
to have isometric 2d
you need an angle
Gizmos.DrawRay(transform.position, transform.TransformDiretion);
try that
Aren't isometric angles like 30 degrees above and below horizontal?
you're doing 45 degree angles
hm yes, that still needs a vector3, which is why i tried the other thing, i could not get that to work
like PraetorBlue said. You want 30 degree angles. Not 45 degree angles.
no shit
I'm confused what you're asking then?
well im having trouble setting the angle from a float, because every method i have tried so far is requiring a vector3. that is why i tried the above code, which obviously did not line up xD
vector2 is also a vector3
whats your exact trouble
Quaternion.EulerAngles(0,30,0); ?
case PlayerFaceing.UpRight:
_target = new Vector3(transform.position.x + Mathf.Sqrt(3), transform.position.y +1, transform.position.z + 0);
break;
get familiar with the unit circle:
https://www.mometrix.com/academy/unit-circles-and-standard-position/
or it has to be a vector3 .. where you got the values anyway
Vector3 upright = Quaternion.Euler(0, 0, -30) * Vector3.right;
Vector3 upleft = Quaternion.Euler(0, 0, 30) * Vector3.left;
Vector3 downleft = Quaternion.Euler(0, 0, -30) * Vector3.left;
Vector3 downright = Quaternion.Euler(0, 0, 30) * Vector3.right;```
those can directly be used as targetDir
why z
the rotations are around the z axis
but yes trig is also an option here
@sly grove that was close to perfect
they were switched around, and iso is 26.565f
but perfect
thanks
why didnt you search the value in the first place lol
i never said anything about angles xD the way i did it was to try and make it fit into a tilemap grid system. where 0,0 and 0,1 would be next to eachother - but yeah would have worked in topdown but not iso π
in 2d?
everything in unity is 3d, so yeah you can rotate the camera. even though its a "2d project", it's actually 3d but the camera is locked in just a way to make it look 2d.
2d just means you have everything in z position at 0
nothing else
vector2 is just a vector3 with z value 0
but you can use z as layer?
yes
as its still 3d
after all
its just per "default" 0 at z
just put a 10 in your camera z
aint on the same position
and if you're not comfortable with quaternions but you still want to do isometric instead of top-down, look at my solution i posted and get to understand the Unit Circle, then you can still do a tile-based isometric grid. #archived-code-advanced message
im watching it, thanks m8
So I have this function that checks my entire tilemap and sees if a stalactite has ground or another stalactite above it and if not it removes it but instead it just removes the entire pillar. Here is the function:
public void DestroyStalactites()
{
//Checks all tiles for stalactites
for(int x = -mapWidth; x < mapWidth; x++)
{
for(int y = -mapHeight; y < groundLevel; y++)
{
Vector3Int cellPos = new Vector3Int(x, y, 0);
if(stalactites.GetTile(cellPos))
{
Vector3Int abovePos = cellPos + Vector3Int.up;
//If a stalactite doesn't have ground or stalactite above it, remove it
if(!ground.GetTile(abovePos) && !stalactites.GetTile(abovePos))
{
stalactites.SetTile(cellPos, null);
}
}
}
}
}
Throw a couple debug outputs in there and track down which line is mis-behaving
It's not really misbehaving I think my logic is flawed
I'll send some context
First image is before, second is after I break one block, third is after I break a second block
Well, i mean, technically it would probably work if you just reverse the direction in which you check the tiles. Since you're progressively deleting the tiles as you go, change your y-forloop the following:
for(int y = groundLevel - 1 ; y >= -mapHeight; y--)
(which I mentioned way above the first time this question was asked)
@plucky kestrel you're best off doing that, for now. And maybe sticking to #archived-code-general for questions like "hows this logic look"
Which I didn't know I was supposed to do because you didn't elaborate :/
Alright mb, thank you
you didn't ask
I don't know where that is or if I was tagged or whatever
Ok sry didn't tag you
Thank you, it worked.
So like, does anyone have any idea what the heck Subsystem is/does?
https://docs.unity3d.com/ScriptReference/SubsystemsImplementation.SubsystemWithProvider.html
I think it's some framework that the AR/XR/VR stuff is built on
(there is only 2 pages of google results, that's when you know it is not used much...)
That seems to be the only thing that uses it. But looking at the code, idk why it was even created or how it should be used.
why go poking around weird caves Β―_(γ)_/Β―
Because who knows what treasure you might find!
So after poking around some more.... I have decided that there seems to be no real reason for to exist as even the XR stuff doesn't seem to really have much code that really needs it....
{
Weapon, Armor, Tower, Relic
}
public enum ItemRarity
{
Common, Uncommon, Rare, Unique
}
[Serializable]
public class Item
{
public Sprite uiSprite;
public string itemName;
public ItemType itemType;
public ItemRarity itemRarity;
}
[Serializable]
public class SpawnableItem : Item
{
public GameObject prefab;
}
[Serializable]
public class EquippableItem : Item
{
public StatBonus[] statBonuses;
}
[CreateAssetMenu(fileName = "ItemData", menuName = "ItemData")]
public class EquippableItemData : ScriptableObject
{
public EquippableItem equippableItem;
}
[CreateAssetMenu(fileName = "ItemData", menuName = "ItemData")]
public class SpawnableItemData : ScriptableObject
{
public SpawnableItem spawnableItem;
}
I ran into issues with Unity not allowing me to easily instantiate a ScriptableObject during runtime. I need some items to be randomly generated at runtime, and others to have preset data. This is the solution I came up with. Is there any way to skip having essentially duplicates of every item class, or is this a good way to do it too?
What "issues" did you run in to?
Why are you instantiating scriptable objects?
They said because they want to have randomly generated items at runtime.
I think your model is a little bit backwards
I'd do something like this:
class ItemData : ScriptableObject {
public GameObject prefab; // can be null
public Sprite uiSprite; // can be null
public string itemName;
public ItemType itemType;
public ItemRarity itemRarity;
}
class EquippableItem {
ItemData baseData;
StatBonus[] bonuses;
}
class SpawnableItem {
ItemData itemData;
}```
That wouldn't work at all though. What if you want to set bonuses of EquippableItem in the editor?
I don't think you ever would.
I'm imagining this is like a diablo item. There's some base stats then randomly generated bonuses
It's not an edit-time thing
Yeah, I guess it really depends on the type of game/use-case for it.
I was basing it off of path of exile, so basically diablo. Some items would have non-random bonuses and would drop from specific places.
I could see that model working without needing seperate types for items
ItemType could take over as my way of checking what type an item is, and then I just make:
class Item {
ItemData itemData;
}
How would I make a custom editor to edit the values nested inside of Item?
This throws a null error:
public override void OnInspectorGUI()
{
var so = serializedObject.FindProperty("item").serializedObject;
Debug.Log(so.FindProperty("itemName").stringValue);
}
A question for #βοΈβeditor-extensions extensions, where I have a guide to serialised object pinned (at the bottom)
https://help.vertx.xyz/programming/editor-issues/serialisation/serializedobject-how-to#objects
I have a bug where, if a player is holding down the left mouse button over a tile gameobject (with a onmousedrag implemented that creates a highlighted spot), while a force play (a method in another script, that forces the player to play a random tile and also creates a highlighted spot) has started, a random tile is selected and moved to the wrong highlighted spot. That wrong highlighted spot should not be there, but because of the holding down of the left mousebutton on the first tile, it is creating a highlighted spot that, when the force move method is called, is recognizing both that tile's highlighted spot and the highlighted spot created by itself, causing the forced tile to move to a highlighted spot that should not be there if randomly selected. I've tried removing all spots before calling the the force move method... Setting a flag on the tile being held down, so that its onmousedrag doesnt call while the force move is called, but to no avail. I am stumped at this point, as it has been a couple of days that I've been trying to fix this bug. Can anyone give any pointers as to how I can resolve this please?
highlighting something should probably be visual and not actually effect game logic - alternatively, reset the relevant objects and lock player input so that the forced sequence can't be disturbed
Thank you for responding. What would locking player input look like?
hey, I'm trying to create a hole into a box on run time , the box has a collider, I don't just want to make a shader mesh gap, I want also to somehow make the collider gap at the exact same region
you can think of it as a breakable wall that wont just allow you to see what is behind it, it would also allow you to walk through it
is it possible to disable collider at certain areas of the wall/cube?
maybe? when I do stuff like this (which isn't often), I use layer trickery like in https://www.youtube.com/watch?v=cHhxs12ZfSQ
Make sure to SUBSCRIBE so you don't miss a video!
Download the complete project: http://quill18.com/unity_tutorials/PinballDepthTest.zip
Also, please feel free to ask lots of questions in the comments.
This channel is mostly all about game programming tutorials, specifically with Unity 3d. You may also be interested in my primary channel, wher...
though I'm sure someone has done other ways like actually replacing/modifying a mesh collider's mesh which would be much more difficult
that looks nice, but it's definitly not optimized for android devices, i need to make multiple holes in many walls/cubes
I'm stuck with URP I think, I could used a shader mask to cut the whole, but what about the collider ?
also explained in the video. (after 14:30)
you are right , that would probably do the trick! , thanks so much
the only thing I would need to modify is that he buit his hole as for not to render anything behind it, I actually need to rennder everything behind it except the wall itself.
Is there a way to subscribe to the EventSystem to be notified about clicks on the Canvas without having the events be consumed by buttons?
really depends on your current input architecture - guard flags on individual object event handlers, disable input actions, disable canvas raycaster, etc
from the sound of it you're just using standard input & EventSystem - simplest but rather specific method would be to put a guard flag in the handlers, if (playerInteractionBlocked) return; etc
Going off the top of my head here but would adding a listener to EventSystem.OnMouseUp suffice? Unsure if this captures the GameObject the event is happening on though
Does anyone know good resources on creating unit formations and group orders for RTS games?
has anyone seen this error its when i archive in xcode.
Undefined symbols for architecture arm64:
"OBJC_CLASS$_PHPickerViewController", referenced from:
objc-class-ref in NativeGallery.o
"OBJC_CLASS$_PHPickerFilter", referenced from:
objc-class-ref in NativeGallery.o
"OBJC_CLASS$_PHPickerConfiguration", referenced from:
objc-class-ref in NativeGallery.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Hello. Is there a way to debug in Unity through VS Code?
The only VS Code debugger extension is marked as deprecated.
This has been bugging me for years. I finally sat down and settled things by staring Unity and vscode deep in its eyes. Also giving them blue eyes. Yes, I beat the living code out of software. It's a living. Good night.
I've got an issue with my multiplayer game i'm working on. My cinemachine camera seems to follow the wrong character and I would need to do an: if (view.IsMine) but there is nowhere to put that code for it so I need help.
I am making a projectile system. Is it more efficient to have one update method within the system, which will iterate through all projectiles and make them move or have one update method per projectile?
Use community
has anyone here used ios goodies? I can't seem to build in xcode fo rit
Hi Iβm looking for a game dev
Hello dear friends i have a question that is a little bit complicated:
how do i apply rotation to a vector3
i have two vector3 points (no gameobjects, no transform) and i am trying to apply a rotation according to the direction but i can not wrap my head around it somewhow. This rotation can also be a rotation of 90 degrees according to the direction:
Vector3 direction = b - a;
Quaternion rotation = Quaternion.LookRotation(direction, Vector3.up);
so what i want is the blue position
You have a vector that represents a direction and want another vector that is 90 degrees to it? can't you just use cross product?
i donΒ΄t know would it work? how would you apply that
This physics video tutorial explains how to find the cross product of two vectors using matrices and determinants and how to confirm your answer using the dot product formula. This video contains plenty of examples and practice problems using the components i j k.
My E-Book: https://amzn.to/3B9c08z
Video Playlists: https://www.video-tutor.ne...
You need to describe the rotation you want
but you can rotate any vector using:
Quaternion someRotation = whatever;
Vector3 direction = whatever;
Vector3 rotatedDirection = someRotation * direction;```
tried that i think let me see again
that might be because i wanted some kind of distance
means a small offset to the right
Can you explain the picture?
I get you have points A and B, and a direction vector B - A.
What is the blue arrow and the blue point?
i want a new vector3(blue dot) exactly 90 degrees from vevtor a with a distance
This isn't enough information for that
There are infinitely many vectors 90 degrees from the B - A vector
from vector a exatcly
like on the right side from A
"like on the right side" isn't precise enough for code
you need some other vector as a plane normal or something
or a third point on the plane to define the plane
Maybe one of the world directions like Vector3.up or Vector3.right, or Vector3.forward?
i ll try a few things and let you know. i cant use vector3.right because direction can change
Maybe if you back up and explain the problem you're trying to solve it would help
allright
i forgot to normalize the direction it is fixed, thanks everyone
Vector3 direction = (b - a).normalized;
Vector3 desiredVec = a + Quaternion.Euler(0, 90, 0) * direction * distance;
your middle two lines of code don't do anything
Vector3 direction = (b - a).normalized;
Vector3 desiredVec = a + Quaternion.Euler(0, 90, 0) * direction * distance;``` will do
Does anyone know if UnityWebRequest just straight up doesn't work for getting local files on linux? I'm using stuff like UnityWebRequestTexture.GetTexture to load textures from the local disc, and it works perfectly fine on Windows, but on Linux it always fails to go through with UnityWebRequest.Result.ConnectionError along with the error message Cannot connect to destination host. I double checked the path with someone on native linux, and it's as it should be
what path did you use?
I need opinions on the solution I came up for custom item effects. These effects would be too unique from item to item to solve with a bunch of editor fields. The solution I came up with is string-based, with a class called ItemEffectManager.cs being in charge of executing necessary code when each effect is added or removed.
In ItemEffectManager.cs:
public static void OnEffectsAdded(string[] effectNames) //Called when an item is inserted into the inventory
{
if (effectNames == null) return;
foreach (var s in effectNames)
{
switch (s)
{
case "crystalRegenReplace":
Crystal.CrystalRegen = () => 1f + PlayerStats.GetStatBonus(Stat.HpRegen);
Player.Instance.HpRegen = () => 0;
break;
case "crystalDamageReplace":
break;
}
}
}
use scriptableobject for effects instead of strings
What data would the scriptable objects carry?
OnAdd and OnRemove methods?
it would look something like this
public abstract class Effect : ScriptableObject
{
void Execute(Context context);
}
[CreateAssetMenu]
public class HealEffect : Effect
{
public float healAmount;
public override void Execute(Context context)
{
context.target.health += healAmount;
}
}
dev debate... what's more readable, the green or the red? :p
green definitely, even though its not perfect
thanks, I might have done the red lel and my studio changed it to green... thanks for the feedback :p
if you want more insights: red one is one line, and looks good, but if you don't know anything about the code, you're lost instantly
green one creates variables with explicit names that allows anyone reading what is the condition actually doing
more lines is probably a better coding practise, tricky when our studio has no lead devs for guidance.
"more lines" is not really what it is about, it's more about "understanding the code quickly"
i don't know the code so i might say something wrong, but the base issue is your HasFlag methods in the first place
HasFlag doesnt really say much
Green but those variable names are awful. Would be improved with better local variable names
Has flag is for using flag enums, part of .system...
yeah isDead is a bit confusing as It doesn't work when looking for an alive state
allowedSurvivalStatusEnum should be renamed survivalStatus or something
damageFlag should also be renamed like damageTypeIsLegal
hasDied should be survivalStateIsLegal
so your final condition is like damageTypeIsLegal && survivalStateIsLegal
I would say more like
legalDamageType and legalSurvivalState
and then the IsLegal method makes a lot more sense
The hardest parts of programming:
- Cache invalidation
- Naming stuff
Thanks so much guys, feedback is actually fantastic
yeah, that should be it
Easiest part of programming: making a working program
Hardest part of programming: making a working program that is easy to change (& easy to read)
oath
i'm stupid, those are bool, those names are very wrong lol
I think they make sense for bool
Found out who named the variables rushed them for a 5pm finish XD
i thought it was enum values
legalDamageType would be expected to be something like DamageType.Steel not "true" lol
π€£
The verb is implied
XD
well maybe i'm not good enough in english that i don't see the thing there is to see
What about isLegalDamageType? That's what I would normally do but it might not make sense in other situations
Imagine speaking to your secretary about a building approval you are setting up:
"Ok is the tax assessment legal?"
"yes"
"Is the survey legal?"
"yes"
"legal floorplan?"
"yes"
"legal title?"
"yes"
English can happily degenerate into having no verbs and still make sense
yea i was thinking about like this
ah ye
I see
this should do I think, think I incorporated the most of what you lads said :p
Is there a word to describe what type of variable the Func<float> field is that I could add as a suffix to the name to make it less confusing?
public static Func<float> HpRegen_____ = () => 1f + GetStatBonus(Stat.HpRegen);
public static float HpRegen => HpRegen_____.Invoke();
a delegate, if i understood the question correctly
fixed π
yep it's a delegate. You could also call it something more on the nose like HpRegenFunction or HpRegenHandler
I like handler, that's what I'll name it.
You could also make a custom delegate type like this:
public delegate float HpRegenHandler();
Then your code can look like:
public static HpRegenHandler HpRegenHandler = () => 1f + GetStatBonus(Stat.HPRegen);```
which is maybe getting a little Java-ish but idk
I could see that getting messy since I'm doing that for 13 different stats... What would the benefit be?
ah perfect then you can do:
public delegate float StatHandler();
public static StatHandler HpRegenHandler = () => 1f + GetStatBonus(Stat.HPRegen);```
And you can use StatHandler instead of Func<float>
everywhere
oh wow that's so much better
which feels a lot nicer imo
If I want to create my own "update()" system, that goes through a varying number of objects/structs and calls an update method on them all, and there needs to be a way to remove and add objects/structs to this, how is this done well?
"Well" = performant, elegant and garbage free
You can create a sort of tick system and subscribe members to a master class that performs the function tick to any of its subscribers
so I'm doing a lot of stuff in "OnDisable()"
whenever I exit the play mode
console will give me a lot of null errors as expected
am I doing things wrong or I should just don't worry about it
This sounds good! How do they subscribe to "listening" to this tick?
My initial idea was a List<> and the objects/structs, and a Manager that adds them to that List<> and iterates over them doing the update, notes down a list of all the indexes of those that need to be removed after this round of Updates(), and then does that after iterating over all of them via a reversed (high to low) index removal of the "flagged" indices of the List in that second pass.
Is this kind of the way these things are done?
Hmm I think you'd rather the subscriber add itself to the list rather than the other way around to reduce dependencies, so you could use an Interface like ITickable with a Tick method, and maintain a list or set on the master class that is subscribed to, or I think Unity has an events system that would also be suitable for this purpose. This is the Observer Pattern if you want to research it
Cheers. Will research Observer Pattern and come back with retarded questions...
Not a good idea to subscribe a struct member to an event, they get copied everywhere and you can end up with invalid data if you aren't extremely careful
Guys, why the code is not waiting the first wait I just added?
IEnumerator CheckAndFixDependencies()
{
// Wait the internet check to become true
yield return new WaitUntil(predicate: () => InternetManager.instance.online);
var checkAndFixDependanciesTask = FirebaseApp.CheckAndFixDependenciesAsync();
yield return new WaitUntil(predicate: () => checkAndFixDependanciesTask.IsCompleted);
is internetmanager something you wrote? my guess would be that it does in fact wait but semantically doesnt do waht you want
sorry I missed the message, this is an example path /home/yonaton/.config/unity3d/Arcy/TwinEdge/CustomSongs/Hellsnake No Way Back (arcy)/audio.wav, which is a correct 100%
Yes it is.
This is what it contains:
https://hatebin.com/jlwaujwppg
I tried both with both CallCheckConnection() and
StartCoroutine(CheckConnection())
As it seems it indeed waits but it says online even tho I have wifi off.
On the other hand In my phone after I build it says offline always?!
When it says online even though you have no connection, what device are you using?
https://docs.unity3d.com/ScriptReference/Application-internetReachability.html
The docs say this property should not be used to determine actual connectivity, and that on non-handheld devices are always considered to be NetworkReachability.ReachableViaLocalAreaNetwork
I use an Iphone with iOS build.
Yes I read that as well.
I found a solution for the Editor. I put both the conditions in one if.
And it seems to work fine.
I will try with phone now.
(Also I have to add that its not that my build does not support internet connection because Firebase Database works fine)
Nope it is always offline on phone 
[Solved]: It needed an https instead of http for a phone. A warning occurs now tho:

wtf is LEGAL SURVIVAL STATE?
im intrested
I have a struct PlayerStats with 9 floats and 1 int
I want to make an operator overload that multiplies two PlayerStats together, but if any of the stats are 0 in the second struct I want it to either be ignored or turned into 1
Im trying to do this with reflection but that 1 int is messing things up I think
Im getting this error:
InvalidCastException: Specified cast is not valid.
Heres the code I have:
public static PlayerStats operator *(PlayerStats a, PlayerStats b)
{
PlayerStats newStats = new PlayerStats();
foreach (FieldInfo fi in typeof(PlayerStats).GetFields())
{
object aVar = fi.GetValue(a);
object bVar = fi.GetValue(b);
if ((float)bVar == 0)
bVar = 1;
fi.SetValue(newStats, (float)aVar * (float)bVar);
}
return newStats;
}```
Are you not able to turn an int object into a float?
Is there a way I could make this work?
System.Type type = bVar.GetType();
if ((type)bVar == 0)```
Im getting the error that I cant use the varaible 'type' like a type
I tried this:
float aVar = System.Convert.ToSingle(fi.GetValue(a));
float bVar = System.Convert.ToSingle(fi.GetValue(b));
if (bVar == 0)
bVar = 1;
fi.SetValue(newStats, aVar * bVar);```
But now Im getting this error:
```ArgumentException: Object of type 'System.Single' cannot be converted to type 'System.Int32'.```
~~Kinda want to suggest templating your GetValue function if possible, so you'll end up with something like this: ~~
Scratch that, GetValue comes from the reflection namespace...
Ok now Im very confused
Am I using fi.SetValue() wrong?
foreach (FieldInfo fi in typeof(PlayerStats).GetFields())
{
if (fi.FieldType == typeof(int))
{
fi.SetValue(newStats, fi.GetValue(a));
continue;
}
float aVar = System.Convert.ToSingle(fi.GetValue(a));
float bVar = System.Convert.ToSingle(fi.GetValue(b));
if (bVar == 0)
bVar = 1;
Debug.Log(fi.Name + (aVar * bVar).ToString()); // Damage1
fi.SetValue(newStats, aVar * bVar);
}
Debug.Log(newStats.Damage); // 0```
It seems to be setting every value to 0
It's because it's a struct. When you pass it into SetValue, a copy of it is being made and boxed into an object.
So its not changing newStats?
No, you'd have to box it into an object first, pass that to SetValue, then cast it back to the struct
But I don't recommend using Reflection for this kind of thing.
Well I donβt see any other way than writing out basically what I already have but 10 times
Not very DRY
Reflection is very slow btw. If you do this often per frame, it will bog down everything else
Well Iβm glad you told me that because I was in fact doing this multiple times per frame
Back to the long way then
public static PlayerStats operator *(PlayerStats a, PlayerStats b)
{
return new PlayerStats() {
val1 = a.val1 * b.val1,
val2 = a.val2 * b.val2,
//etc etc
}
}
Yeah Iβll have to add an if statement for each one as well to convert any b zeros to ones
any floats or doubles, you might want to check them for "almost" 0 instead of exactly 0 in case of floating point errors
Good point thanks
i was wondering - when rewriting some code for multiplayer, the best way would be to copy everything i need and put in another namespace and edit there, right? Or is there a better way?
How can I first make a check and then wait for the online to be true?
I mean it may have been true from a past call but I need to check it again before waiting
The call of the method is:
InternetManager.instance.CallCheckConnection()
// Wait the internet check to become true
yield return new WaitUntil(predicate: () => InternetManager.instance.online);
Can I add the first code in the yield somehow? before the check online?
or even better make another yield for it to wait until CallCheckConnection() is finished?
yield return new WaitUntil(
() => {
InternetManager.instance.CallCheckConnection();
return InternetManager.instance.online;
}
);
``` maybe?
or (as you probably always want to get the current status when you access .online )you could make it a property that always runs the connection check
how is that possible exactly?
hey, any idea why this works
Vector3 currentVelocity = transform.forward * z * Time.deltaTime + transform.right * x * Time.deltaTime;
velocity = currentVelocity;
rb.MovePosition(transform.position + velocity*speed);```
but when I try to normalize vector to get always same speed, it gets only in one direction and super fast
```cpp
Vector3 currentVelocity = transform.forward * z * Time.deltaTime + transform.right * x * Time.deltaTime;
velocity = Vector3.Normalize(currentVelocity);
rb.MovePosition(transform.position + velocity*speed);```
Hi folks, does anyone know how to draw in the editor scene view? Not as a gizmo, all the time. Preferred 2D, but if I have to unproject I guess that's ok
I have a camera "proxy" following the scene view camera but it's not really ideal to position 2D graphics that way lol
Because normalizing cancels out all the deltaTime multiplications on the previous line. #π»βcode-beginner next time
I don't have an answer per se, but my first guess would be a combination of OnValidate() and gizmos
Thanks, I know how normalization works but just forgot that I should multiply it later by delta time
Ooo hopefully OnValidate is faster than Update, thanks
seems it's called at the same rate as Update in the editor
I've tried forcing updates every way I can find and think of and it's getting to the point that I'm considering faking user input lmao
Updates 2 sec after camera rotation or translation, but immediately upon scrolling
In this, will the line InternetManager.instance.CallCheckConnection(); be called once? and then it will stick to the online bool till it gets the true value?
it'll be called until the predicate returns true
so it will keep sending internet signals. alright
thank you
are you trying to quickly place objects into a scene? is that what the goal is?
if so, look into the GameObject brush. It's a paintbrush for 2D tilemaps, but you paint GameObjects instead of tiles. It takes some setting-up, but it does that it says.
caveat: all painted objects will be as if they are unique objects, and any updates to the prefab will not affected the already-painted objects.
https://docs.unity3d.com/Packages/com.unity.2d.tilemap.extras@1.6/manual/GameObjectBrush.html
the goal is to draw in 2D (window space I guess?) on top of what the scene view camera has drawn (under or over the default gizmos)
I don't actually want to use a GameObject at all
if I could blank out the camera to a solid color that would work too
just need the rectangle of the scene view to be entirely one color
edit: I know it sounds silly but there is a point to it haha
Drawing is usually done by tilemaps and not really anything else. What you're describing sounds like a major A|B problem. I don't know what you're attempting to do, but I think that you're most certainly going about it in a difficult way. Perhaps describe what led you to this, and we can suggest a better way to do it?
Hi,
I'm searching about a specific case for naming convention.
I Know possible to set the name of layers and tags this way for better organisation:
NameGroup/SubNameLayer
TagGroup/TagName
EventGroup/EventName
But i have no idea how to get them from C#, especially in my case, were i have an Animation Event Named Obstacle/Head
How do i write it in my code because Void Obstacle/Head isn't working at all ... ?
How do you write what in your code? I'm not sure I understand what you are trying to do? When you make an animation event, you specify the function name in the animation event.
Whatever you write in "Function" should be the name of the function in your script
you can't name functions with slashes in them
just "GeneratorHead"
This part of code is intended to be send to Playmaker
Usually i don't use the / but i think there is a possibility to do it
cause it's the same as tags and layers when you want to write it for better organisation
IDK maybe C# will allow it
try it
Either way whatever is in that Function field needs to match the actual name of the funciton
void Generator/Head()```
try that
kinda doubt it will work
no it definitely won't work
no i already tried of course
Ok then no it's not possible
do what for tag
reach Canvas/Grande Serie
what do you mean by "reach" it?
Get
or set the tag
as a string ...ok
yes, tags are strings
so i'm pretty sure it's possible to get something similar for void
What do you mean?
void simply means "this function doesn't return anything"
maybe void ObstacleHead(string "Obstacle/Head")
argg
what are you trying to do exactly?
Your questions are very vague and confusing
Your use of tags is also confusing π€
I have a feeling you are trying to shove some paradigm from some other game engine into Unity that doesn't fit.
nop, only working with unity
let me explain more in detail
but i think the soluce doesn't exist
In unity you can organise variables, Tags, Layers using /, so you can organise them clearly in the editor.
So i espected to directly Set the same Name To the Animation Event, and use the eventListener script to follow it to the FSM
But as you said, the void will not recognize it because of the /
but after i send a string so i am not restricted this time.
So my error was to try to name the event with /
I'll remove it and then convert it in the function directly
thanks for your help
This / thing you're talking about is unique to PlayMaker. It is not a general Unity thing.
did you already tried to name a tag or layers using this ?
Is it possible to make a Wait until a method is finished?
NOT wait a true value from is and run it until that happens
Methods finish immediately upon calling them
void MyMethod() {
// stuff
}
void OtherCode() {
print("About to call MyMethod");
MyMethod();
print("MyMethod is complete");
}```
So I am inside a Coroutine and I need to wait first for the CallCheckConnection to update the value of online and then call wait for online. If the online is not true, CallCheckConnection has activated a panel with a button that can call it again , until the online is true
InternetManager.instance.CallCheckConnection();
// Check Internet connection and wait
yield return new WaitUntil(predicate: () =>
{
return InternetManager.instance.online;
});
I'm sorry, I can't explain why I need the editor window to be blanked. But rest assured, it is a requirement for what I am trying to accomplish. I wish I could elaborate further.
But hopefully that simplifies the question of "what are they really trying to do"
Combing through internal APIs and gasp memory hacking are next up on my ways in
Hello, i need some help i keep getting the exact same error even after i change it (The Error):Assets\Scripts\InputManager.cs(33,33): error CS1061: 'PlayerInput.OnFootActions' does not contain a definition for 'look' and no accessible extension method 'look' accepting a first argument of type 'PlayerInput.OnFootActions' could be found (are you missing a using directive or an assembly reference?)
not an advanced issue. and i'd be willing to bet the action is called Look and you just spelled it wrong
just to make things clearer, this is what I'm trying to accomplish
go back to #π»βcode-beginner with this. or even #π±οΈβinput-system if you just don't understand how to use the input system
ok
The question is:
Why does it surpass the wait and shows the ad before checking for internet connection
InternetManager.instance.online = false;
InternetManager.instance.CallCheckConnection();
// Check Internet connection and wait
yield return new WaitUntil(predicate: () =>
{
return InternetManager.instance.online;
});
// --------------------------------------------------------------
RewardedAd rewardedAd = adManager.GetComponent<RewardedAd>();
rewardedAd.ShowAd();
What is InternetManager?
When you have the ad show (without internet), what is the value of InternetManager.instance.online?
Is it true?
If so, the problem is probably in the pastebin code
The ad is loaded way before all that so Im kinda safe to say that it can show
The problem is that im not ceratin if without internet that I will get the money
Nor that the show will actually work
I mean when rewardedAd.ShowAd() is called what is the value of InternetManager.instance.online
let me check if it is called with false as well.
Yes it is called without internet as well
just to make sure, added like Debug.Log(InternetManager.instance.online) right before ShowAd()?
and it was false
if false then the yield isn't waiting, if it's true then there's an issue with InternetManager
Sorry gotta jet but hopefully you find the bug π
Thank you mate, I appreciate it. Wlill do my best
Can someone recommend me something, please? I am stuck. I am trying to do a projectiles system. How can I makes it work for both, projectiles (arrows, fireballs, etc) and units. In other words, new objects and existing objects. Since units can dash and jump, it makes sense to have the same system for both because it is the same functionality. Any help would be appreciated
My initial ideas was to have a parent class "projectile" with all the mechanics and then children classes as individual spells. However, I can't come up with a solution to makes it work on existing units.
Anyone else having issues with OnRenderObject when using URP? I've gone to forums and API and not sure how to do it. Need the callback to render a computer shader.
Note It wont call it at all... when I create public void OnRenderObject(){}
I have a single scene called 'Main' that loads my game, all the load process is done syncronously. I thought by adding a 'Loading' scene first and loading 'Main' using
```SceneManager.LoadSceneAsync('Main')````
I would be able to load the game asyncrously while showing some animations in the 'Loading' scene....
But no... the 'Loading' scene gets stuck and all of a suddden goes to 100% and the other scene starts loading the game... I have 2 questions:
- When does the scene 1 considers the scene 2 is fully loaded? when all the GameObjects are instantiated? when all the awakes are called? when exactly
- Why the scene 1 'Loading' it's totally frozen for a few seconds before the next scene is loaded
- Is the only way of achieving an animated load screen to convert all my game load to asyncronous?
How do I debug something like this in a WebGL build without any info? The stacktrace doesn't give me anything valuable
Whatβs a the other end of the trace? You could also check all divisions in the codebase and guard all of them against /0 with a Debug.Assert()
looks like a divide by zero error in the IL2cpp garbage collector
seems like something you don't have control over haha
What is the difference between this:
and this:
yield return new WaitUntil(predicate: () => InternetManager.instance.online);
nothing
you've just used a named parameter in the second one, and a positional parameter in the first
The effect is the same - the compiled code is the same
It does not wait tho and thats super weird
if InternetManager.instance.online is true, it will only wait one frame
the whole code is this:
InternetManager.instance.online = false;
InternetManager.instance.CallCheckConnection();
while(InternetManager.instance.online == false)
{
yield return null;
}
//yield return new WaitUntil(predicate: () => InternetManager.instance.online);
Debug.Log("is online? " + InternetManager.instance.online); // TODO:DELETE
// AD
RewardedAd rewardedAd = adManager.GetComponent<RewardedAd>();
rewardedAd.ShowAd();
And it shows the ad without the Debug.Log for some reason
Yeah you showed this code earlier
CallCheckConnection checks whether there is internet and sets the online
did you ever show the InternetManager?
oh your are the guy from before haha π
let me show it to you just a sec.
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.
here you go , and thanks btw
Ok and where are you calling this code?
hello,
which is more optimized ?
1 - creating an empty gameobject then add a spherical collider on it ( all on runtime )
2 - having a prefab ready of ( empty game object with spherical collider ) and use inistantiate or an objectpool script instead to spawn it
instantiating a prefab is the quickest.
really interestied in how this coroutine is started though
You mean the press of a button? Yeah it is quite a trick i found and used this once. It completely removes the OnClick() logic
what
I have no idea what this means. I was just wondering how you are starting that coroutine
I want to see the code
oh sorry π thought about the wait button press which I thought it was cool
one sec
right afte rthe ad the panel is shown plus online bool returns true. but for some reason it goes to the ad first
I think I fount the problem.
the prob is that the CallCheckInternet call is in the same coroutine.
Any ideas how to hot join using mirror?
What do you mean hot join?
hey,
is it possible to make SphericalCollider more like a flat circle ( maybe with 0.05f thickness )?
if not , could I make a cube collider on raycastHit as an alternative ( thin on the normal axe )?
SphereCollider is a sphere, that's the point.
BoxCollider you can make whatever dimensions you want.
And if all else fails you can use a MeshCollider with any arbitrary shape you want.
this isn't a code question anyway, it doesn't belong in #archived-code-advanced
thanks, well, you are right except, I'm adding a prefab via instantiate command not the editor and I need the collider object ( in this case a cube collider ) to be a substitude of the spherical shape I used to have ( the spherical shape used to have a center, which was easy for me to alighn with the raycast hitpoint ... but i'm not sure if i could get the center of the cube correctly and reduce its width significantly on the normal axe of the raycast ... all via code )
I'm sure it's not that hard, if I could find what parameters of the cube collider I could use, maybe not for advanced codeing i guess.
definitely not #archived-code-advanced stuff
hey guys I am using ummorpg and burny's vehicle addon together for my project. ummorpg has a really robust mount system that can do a lot, but burny's has shooting. how hard would it be to take the shooting from burny's addon and put that on a regular mount?
That's...not reassuring. What's your suggestion on how to tackle something like this?
I am doing an if > 0 check for all denominators but the cause doesn't seem to be in any arithmetic I'm doing as shown in the stacktrace
the predicate: only points to the correct parameter slot if it receives multiple parameters
how can it receive multiple?
i said if, if it's not, then you don't need the predicate:
Hey guys! I had just started using unity for like 6 days and would like some help regarding this. So the situation is that I am able to use quaternions to control camera rotations and, for the meantime, intend to use left mouse click to reset the rotations back to 0,0,0. My issue is that the command works and goes back to the said reset rotation BUT only for 1 frame. Here is my code for that and would appreciate any help that I could get.
{
public float mousesensitivity = 0.3f;
public Transform playerbody;
public Transform currentcamera;
public Transform defaultcamera;
float xrotation = 0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 mouse = Input.mousePosition;
if (Input.GetButtonUp("Fire1"))
{
currentcamera.transform.localRotation = Quaternion.identity;
}
else
{
currentcamera.transform.localRotation = Quaternion.Euler(mouse.y * mousesensitivity, mouse.x * mousesensitivity, 180f);
}
} ```
just be patient instead of cross-posting, not an advanced question. Every frame your button isn't released, it hits the else clause setting the rotation based on the mouse position.
Ahshi that's on me. Grew quite impatient since I've been working on it for almost 8 hrs now. Though I'll take that into consideration. Thanks!
Hello! I have an app that in the title screen checks whether user's credentials are valid. If so, it should load main screen with all the features that the app will have.
With this comes one issue. I wanted to make a loading screen. From YT tutorials, I've figured that creating a persistent scene and then loading other scenes on top of it will be the best approach.
However, even though the app loads into title screen from the persistent scene, I want the program to check for validation of credentials AND then call a LoadUserInfo() function, that will drop user to the main menu. I cannot do that, because I don't know how to reference GameManager object from another script and call its public method
Here is the GameManager which is meant to handle scene changing
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
public static GameManager instance;
[SerializeField] private GameObject loadingScreen;
[SerializeField] private GameObject gameLogo;
private void Awake()
{
instance = this;
SceneManager.LoadSceneAsync((int)SceneIndexes.WELCOME_SCREEN, LoadSceneMode.Additive);α²Ό
}
public void LoadUserInfo()
{
loadingScreen.gameObject.SetActive(true);
SceneManager.UnloadSceneAsync((int)SceneIndexes.WELCOME_SCREEN);
SceneManager.LoadSceneAsync((int)SceneIndexes.MAIN_MENU, LoadSceneMode.Additive);
}```
but I have no idea how to use it in another script
so I've tried a couple different approaches like this:
if (connectionResultCode != UnityWebRequest.Result.ConnectionError)
{
if(result.Contains("0"))
{
SaveSystem.DeleteCredentials();
}
else if(result.Contains("1"))
{
GameObject obj = new GameObject();
obj.AddComponent<GameManager>();
GameManager gameManager = obj.GetComponent<GameManager>();
gameManager.LoadUserInfo();
}
}
}
}```
or simply just finding the object
but it doesnt seem to work
or I get this error NullReferenceException: Object reference not set to an instance of an object GameManager.Update () (at Assets/Scripts/GameManager.cs:30)
which i suppose is because of the approach with attaching a script without reference to the loading screen and icon objects
but either way, I just wanted to know, how can I just call the LoadUserInfo() function from another script
How is this advanced? NREs are the most basic exception, and calling functions is basic too.
- Use the debugger. 2. Go through the singleton
okay sorry wrong channel
Unity facebook instant game stuck after 90% on loading screen.
Please help me out if anyone know about it.
thanks
Hello!
declaring a "var" object does not have a new reference on memory when you declare it with the actual class name, for example, "ThisClass" ?
Question unclear, but there is no difference between var and using the actual type, other than the increased risk of shooting yourself in the foot
File a bug report
Another thing is reduce your usage of the garbage collector, which is a net positive for performance anyway
Hi, I need help to change the size of the box collidor on this sprite to fit exactly according to the size of my sprite. I'v already tried so many ways and nothing seems to work. Can anyone help me?
I can't profile in WebGL, so I can't check my usage of the garbage collector
Don't cross-post your question. keep it in one channel.
<@&502884371011731486> cross-posted in #archived-code-general #archived-code-general message
and #π»βcode-beginner #π»βcode-beginner message
@slate thorn Please don't crosspost #πβcode-of-conduct. This is a #π»βcode-beginner.
sorry, I'm new to here and didn't know I wasn't allowed to do this
Guys i have this problem The type or namespace name 'FormatOptions' could not be found wtf is this
this is a question for #archived-code-general
you dont have either the using directive or the a assembly reference is missing
no shit how do i make it not missing
I would upgrade or downgrade the burst package until everything compiles
ok
anyone have experience with unity cloudbuild?
particularly around deployment to testflight automatically
you can use a fastlane config to do it, or there's a postbuild script floating around somewhere that uses altool that would probably work
so i have this script ```platform :ios do
desc "Push a new beta build to TestFlight"
lane :testflight do |options|
upload_to_testflight
end
I guest im more confused on how the unity cloudbuild enivronment variables work and how i would access them via script
hey, does anyone have any idea how to get mouse delta with a locked cursor using Cursor.lockState = CursorLockMode.Locked?
or is it not possible
cuz right now I get no delta, no matter how I try to get the data
alternatively, is there a way to have a cursor position set cross-platform? I'm on linux
Locked cursor shouldn't affect mouse delta readings
anyone has issues with coroutines stopping when yield endofframe used, but null is fine, with editor 2021.3.5f1 ?
Most likely your object is being disabled or destroyed before that end of frame time window.
null works, I don't do destroy I just tested the coroutine it and coroutine dies, if you didn't try with editor 2021.3.5f1 no point of answering
Unfortunately, when I try reading it with either getaxis or input.mouseposition, locking the cursor breaks things
Breaks things how
have you tried with 2021.3.5f1 ? if you didn't just don't answer me, I'll file a bug if others having the same issue or I'll revert to previous editor.
I am on linux tho, which could change stuff
I use an API key. There's an option to use a session id that you generate with spaceauth, but it expired too fast to be useful in my experience. Look at app_store_connect_api_key in fastlane, and pass options through env, i.e. one of the steps in your lane would be
app_store_connect_api_key(key_id: ENV["ASC_KEY_ID", ...etc)
then in the cloud build environment type in the environment variable of ASC_KEY_ID
as one of the variables?
yep, you'll need the kid, issuer id, and the contents of the key you generate. See: https://docs.fastlane.tools/app-store-connect-api/
last question for you. will unity cloud editor support blend files? I jsut created a build and the player failed to build and im guessing its because we have .blend instead of .fbx
did you have some kind of import error? I think the sneaky way Unity supports blend files actually runs blender in the background so it's entirely possible cloud builders wouldn't support them
yeah i did. Im guessing its the main cause for my cloudbuild currenlty failing
so thats fun lol
back to the old jenkins that has a heart attack with arkit
for some reason arkit always gets disabled whenever I build with it
Can I programatically download a zip file from a Url ? Or do I need to extract the contents ?
I mean you are basically downloading byte data, you just need to convert at the end with an appropriate API
Well what I tried doing is create a dynamic byte array and then just saving the data into a folder as .zipπ
Which clearly wont work xD
Hmm you could use the System.IO library from c# to convert byte array to zip file path and use a library like DotNetZip to unzip it and access the contents
Would you mind me messaging you in pm?
I wont take long π, I promise
No I will not stay long, but these are suggestions, you can look up each part and you should reach what you need
Alright thanks anyways
Sup could anyone here point me to a solution on how would I override the GIL and get multiple unity-embedded python tasks running concurrently? Pls dm or tag me when replying π thx! π
Googling the first error I get info saying you can't use rigid skinning (in Maya) but instead needs smooth skinning.
That means nothing to me outside of Maya but there must be an equivalent in the FBX SDK you are using
when i call camera.render with deep profiling enabled
why do i see the same stacks on the render thread and the main thread
is there a way to do a camera.render "async"?
Hello.
Does anyone know how to make an array of references to child structures with the Burst compiler?
If I remove the pointer sign, the error disappears. But then it seems that UWS_WaterChunk is no longer a reference, and the object will be contained here.
The reference without an array works, but I need an array.
Yeah, unfortunately C# just entirely disallows using proper pointers as type arguments.
One simple workaround is storing a NativeArray<IntPtr> instead and casting those back to the right type when you use them. It loses some clarity and expressiveness though obviously :/
Any Idea why my batching isnt working? I'm instantiating the grass per chunk, so the gameobject count is changing when loading/unloading a chunk. Every grass object is parented to an object call "grassHolder" and I'm using the "StaticBatchingUtility.Combine(grassHolder);" function, everytime a new chunk is being generated, so that the new gameobjects are batched as well.
Thanks. Maybe you know how to allocate memory for a structure and get a reference to it?
btw if you have any other ideas on how to optimize procedually generated objects, just dm me pls
Depends a lot on what you want to do ^^ Where possible it's nice to stick with safe code and just new structs, or allocate them in NativeArrays and pass around indices and such.
If you want to drop down to unsafe pointers, you can either still get pointers to inside a NativeArray (or List etc.) or you can manually allocate the memory using UnsafeUtililty
I'm trying to implement the QuadTree algorithm. Each structure contains references to four descendants. What is the best way to implement it here?
And then:
If you use NativeArray, how do you get a pointer to its element?
If you use Unsafe Utility, how can you use it to allocate memory for one structure? I understand that it allocates memory for buffers.
Good question. Just storing a NativeArray in each node sounds appealing but I think Unity won't let you :/
To manually allocate one struct, I'd recommend writing a simple wrapper like this:
unsafe T* Malloc<T>(Allocator allocator) where T : unmanaged {
return (T*) UnsafeUtility.Malloc(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), allocator);
}
This would be easy to extend to taking a count so you can allocate a buffer of 4 nodes too
Just, uh, be aware that when you get into unsafe code you really do have to be careful and know what you're doing a bit. Things will blow up in hard to debug ways if you write bugs.
As in, I've spent way too much time chasing down bugs like "this pointer write silently corrupts some internal data and then 2 minutes later some other random piece of code causes an editor crash because of it"
What is your goal here anyway? If itβs performance your only option is to store your data in a data oriented way. If you malloc a pointer for each node, no matter how fancy your compiler is, it will be slow and the whole unsafe excursion is wasted
Can I have an example of how to use this? What should I pass to allocator?
It's the same allocators as for NativeArrays and such
Oh, I see
I also agree with Anikki fwiw, most strategies that don't involve a malloc per node are faster than doing one malloc per node ^^
hello, so, I have a ScriptableObject that has other sub objects
and I'm trying to rename them
how could I do that?
changing the name of the object seems to work
but then here it looks the same
I want to make the execution parallel with job, I think it will still be faster than just a standard separate C# thread.
Why do you need unsafe/pointers for that?
I think I found an example of an implementation with an array. But will NativeList be faster than malloc?
That is not how that works
you need to store your data in a way that it can be processed faster by the cpu, malloc and native array are just tools to achieve that. In itself a native array is slower than a plain array because of the thread safety overhead
Then how roughly should I implement QuadTree?
also creating and initializing jobs creates an overhead
My goal is not Collision Detection, but the LOD algorithm, something like those used in Terrain.
since you do not seem to be aware of all this, you should start with a plain c# one and optimize that, then maybe think about a threadsafe one, then maybe make parallelized algorithms for it
An optimized quadtree for that cannot be made βroughlyβ it will be specific to your use case, and not your general use case, the actual one with consideration for size, the read/create/update/delete patterns over time and relation to other systems
spoiler btw. unity already does oct tree spatial partitioning
so you won't gain much from adding it yourself
hello guys
are there any big, feature rich procedural mesh generation libraries available for C# / Unity ?
don't want to waste time implementing my own mesh factory if I can avoid it
tried googling, but results are mostly some simple studies
specifically interested in generating mesh strips (walls) from open or closed paths and generating "caps" for those strips
Hi, why doesn't Unity use .pngs for textures? In that case, you'd get lossless compression instead of lossy, the disk size would go down a lot, and you wouldn't have to spend as much time reading from disk, because there'd be less to read (at least if it's not from a sprite sheet?)
what do you mean why don't they use pngs?
they support png's. and your statement about having lossless compression and simultaneously taking up less disk size is nonsensical
when you build the game it needs a packaged texture asset that can be used at runtime. unless you're saying the game should also pack a png codec with the executable and code/decode them at runtime
(in which case it would massively bloat RAM)
Many systems include .png decoders, e.g. if you make a mobile-only game, both iOS and Android provide it. And .png's are able to take up less disk space while still being lossless because they're not constrained by having a fixed number of bits per pixel
GPUs don't consume PNGs. They consume a wide variety of different formats (DXT, BC7, ASTC, etc). You can use whatever textures you want depending on the loss/memory footprint you want - Unity just makes that easy for most people because the memory bottleneck on GPUs isn't really a or "the" concern
So it sounds like, for systems that provide .png decoders already, the main (and only?) reason not to use .pngs, .jpgs, etc. is to lower memory consumption
One could argue .png decoding is also non-trivial, but I imagine it's also mitigated by not needing to load as much data from disk for .pngs
Bump π
is there any way to map a monobehaviour properly with a non matching filename, or to have a nested type as a monobehaviour?
i think you can addComponent a nested type/mismatched filename directly from code, but I don't remember the rules exactly
man, some of the questions asked on this channel are just gibberish.
example?
@alpine sinew i wanna make a nested class a monobehaviour - so the filename wont match the type. I'd like to have it show up on "add component"
i forgot the rules on how the monobehaviour naming stuff works
no. MonoBehaviours must be 1:1 with files and have matching names
Yes you can AddComponent one from script
but the editor won't like it
is there a reference with info ?
The mathcing filename restriction is about making the scripts into assets which the editor can interact with (MonoScript assets)
theres no file registry or something you can hack up?
No, because this is not really a documented behavior. The expectation is you always match them
To what end?
Oh the Add Componenet menu
nah that's pretty much a nonstarter.
Maybe if you muck around in the AssetDatabase? It's probably in Library somewhere. Seems like a lot of effort for little gain though
It's also bound to be extremely finicky. Scripts on objects in scenes and prefabs are linked by their GUIDs, which are from the .meta files accompanying your assets. If there's no asset file, there's no meta file. I think you'd have to rewrite a large portion of the engine to get that working.
i dont think it cares at runtime if you call direct from script. AddComponent<x>
but yeah I would really like a reference
right that's what I said above.
Is this an A|B problem? Like, do you really need to have the nested class monobehaviour but the parent class cannot? Like, what is the application, because there's gotta be an easier way to accomplish what you're trying to do, other than messing with the Unity engine
i don't need any of it, just would prefer it
that's just not how Unity works Β―_(γ)_/Β―
if i could do something like hook domain reload and map a type to file that'd be great.
if not, then yeah.
Without knowing your exact dilemma, it sounds like it'd be most straightforward to M'B the parent, then store a reference to the child class
its no big deal, just something that always annoys me - especially since i can't monobehaviour private nested types.
you can just serialize and stuff but its not the same
@misty glade does that sound right? That memory consumption is in many cases the only downside of using .pngs
Not sure - I'm definitely not a graphics/pipeline/GPU kind of person, I just know superficially that "it just works" in Unity. π
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
@flint flint any further discussion of the efficiency of textures should probably occur in #β¨βvfx-and-particles since this channel is for code #archived-code-advanced
you're more likely to get an answer there.
Thanks
What can I do if burst compiled function throws errors (and says to turn off burst to debug), but non-bursted runs fine?
whats the best way to make turn based combat
there is no best way, especially since turn-based combat is broad and consists of many different features . . .
i cant even make coding plan for it
you can start with using an fsm for each state of combat then branch out from there . . .
then start with tutorials. look for multiple ones, create a prototype for each, and decide which best suits your needs. use that method and expand into your own systems/designs . . .
got it.
Hi, i had a general question on the exporting of a completed game. So for me when i build (even with low settings) and run the game, it appears to be very laggy. I have also tried to make a simple game with just a character controller and a few objects in the scene and that game also was very laggy on my PC and other PCs. Could there be a reason why this is happening?
I think its something with my export settings or PC cause it happens with anything i make (simple or complicated)...
"laggy" is very vague. That could mean a lot of things ranging from actual framerate issues to issues with your camera setup or your scripts doing funny things
sorry for the double question. Im being helped on code-general. Thanks anyway
I posted about building a C++ plugin to access Open CV a few days ago. Unity kept failing to load the dll for OpenCV because it couldn't find required dependencies. Running a dependency walker tool showed me all of the dependencies the dll relied on were present and accessible to my computer. Here is what made it work: Trying exactly the same thing on a Windows 10 machine, rather than a Windows 11 machine. Food for thought.
is it possible in rider to turn off the "visual" display of playmode unit tests ? i dont want to see them... just run them
hey is there anyone who has experience with mlAgents? i making an AI i need to feed the AI an array but it can only know certain indexes of this array while the others still need to be "locked" till it unlocks them by playing the game. It is important that the the values stay at the correct index, so i cant just feed it a smaller array with the "unlocked" numbers. Does anyone know how i could do that?
hello everybody
ive been studying game development for the past months, and im using the unity api and csharp documentation as major study resources.
however, im heaving a bad time when i comes to how to approach system implementations
like
how to implement an ai or how to make procedural terrain
cutting long story short, im searching for more complex and robust study resources
as i believe the ones ive been using so far are not enough to take game development seriously
i would be grateful if somebody knows about any resource that could help me
Concepts such as these are language and engine agnostic, so if you are limiting yourself to Unity or C#, you are cutting off a lot of available resources. Also, have you looked into textbooks about these concepts? These concepts have some of the more readily available resources. Also, you can look up syllabuses for game development courses taught in schools if you want a more regimented approach, as they may list textbooks or concepts that you can further research. Also, if you are able to find source codes for games you are interested in, you can see how their systems behave and the design architecture
i have searched for books like csharp players guide for the programming language fundamentals. Learning how the approaches to systems implementation takes place in unity is the problem
Well, you can still abstact things away from the Unity framework while staying in the environment, you can set up whole FSM without the need for monobehaviors or create a procedural generation algorithm in its own class, and use Unity as a rendering layer. Unity just provides the tools to operate within its environment
i feel like my workflow is evolving to something along those lines too
so the best way to go about it is to find material for each system?
Personally, if there's a textbook for the concept, it's a gold mine of information compared to scattered blog post snippets, so for AI, there's Programming Game AI by Example by Mat Buckland, maybe you can start there
okay thanks a lot @hoary pendant
does anyone know a good way to impliment a card hand holding system similar to slay the spire / floppy knights? Ive been trying to work with unitys horizontal group layout, but it still feels unintuitive
I'm unfamiliar with UI but it would probably help others that might answer if you describe the look you want or even make a drawing showing what you want. Even if someone is familiar with a game you referenced they might not be aware of which particular details you want to emulate.
right sorry, let me visualize it
the players hand of cards would look semi-rounded, as if holding a hand of cards IRL
but when hovering over a card, the others would move out of the way so the player can clearly read the bottom half of the card
i was hoping maybe someone would know of a tutorial for this kind of "hand of cards" implimentation since i cant find one online, which is surprising given the popularity of playing card games
I would use some curve/spline to put the cards on with different spacing based on your second image state etc. I think there are some assets on asset store if you want to inspect their code, probably paid.
hi should i use start courutine for a timer or time.deltatime?
coroutines are more readable and don't look ugly if you have multiple, Time.deltaTime is negligibly more performant because of the overhead coroutines have. I use my own Timer class though, which just has a callback for when it completes and uses Time.deltaTime
anyone worked with flatbuffers ? getting error when it should work fine since im following the docs ? i understand the error but does that mean the version im using has been changed ?
private Table table;
public void init(int _i, ByteBuffer _bb)
{
table.bb_pos = _i; //error here : Property or indexer 'Table.bb_pos' cannot be assigned to -- it is read only
table.bb = _bb;
}```
Are you using hte official wrapper?
If so, I can very much recommend FlatSharp
Much better than the official API
i've used it before and im back to flatbuffers now , there was changes in the api , fixed it already but thanks for the info
hello, I wanna get a list of all variable types available in System;
something like this
'var alltypesname = typeof(Type).Assembly.GetTypes() .Where(x => x.IsPrimitive).Select(x => x.FullName).ToList();' this to get all primitives, typing this on my phone, untested.. question remains, why the heck you want to do this!
I'm trying to make a visual scripting method like VRChat's Udon
Also thank you!!
Anyone familliar with Negamax/minimax algorithm implementations?
yes sir
I'm trying to implement alpha-beta pruning but my program isn't doing the same thing with alpha-beta enabled compared to disabled
show with alpha beta
{
if (depth >= MaxSearchDepth)
{
return board.Evaluate() * (board.WhitesMove ? 1 : -1);
}
var value = int.MinValue;
var legalMoves = board.LegalMoves;
foreach(var (from, positionsTo) in legalMoves)
{
foreach(var to in positionsTo)
{
board.UnsafeMove(new Move(from, to));
value = Mathf.Max( value, -Negamax(depth + 1, board, -beta, -alpha));
board.UndoLastMove();
alpha = Mathf.Max(value, alpha);
if (alpha >= beta)
{
return value;
}
}
}
return value;
}```
note that legalMoves is a dictionary of positions from as the key and a list of positions to as the value
it's making (I think?) worse moves
I can show you if you'd like
the game it's for is Antichess
(chess but if you can take you have to take)
hmm
Do you guys know the name of the program where he created it
so this slime
vs off
well the only thing i can notice is that you're for some reason doing max on value and -negamax, it's usually like this ```
negamax(board, depth, alpha, beta) {
if depth == 0 {
return queisce(board, alpha, beta);
}
for (all moves) {
board.makemove();
score = -negamax(board, depth - 1, -beta, -alpha);
board.unmakemove();
if score >= beta {
return beta;
}
if score > alpha {
return alpha;
}
}
return alpha;
}
(pseudocode)
I created that on this website: https://www.piskelapp.com/p/create/sprite
Thank you
the pseudocode that I was trying to implement was the following:
if depth = 0 or node is a terminal node then
return color Γ the heuristic value of node
childNodes := generateMoves(node)
childNodes := orderMoves(childNodes)
value := ββ
foreach child in childNodes do
value := max(value, βnegamax(child, depth β 1, βΞ², βΞ±, βcolor))
Ξ± := max(Ξ±, value)
if Ξ± β₯ Ξ² then
break (* cut-off *)
return value```
is there a way to sort a list of transforms by the x position of the transforms?
look into LINQ
there's a method called OrderBy which takes a predicate to sort the list by
why does your queisce take alpha and beta as arguments?
alpha beta can be applied to queiscence search as well
oh queiscence search I'm doing a much more basic eval function atm lol
I'm eventually gonna make it search until no move can take
well, i'm sure the code i posted works, since that's what i'm doing
pub fn search(
pos: &mut Position,
depth: u32,
mut alpha: Evaluation,
beta: Evaluation,
) -> Evaluation {
if depth == 0 {
return q_search(pos, alpha, beta);
}
let moves = MoveGen::new_legal(pos.board());
for m in moves {
pos.make_move(m);
let score = search(pos, depth - 1, -beta, -alpha);
pos.unmake_move();
if score >= beta {
return beta;
}
if score > alpha {
alpha = score;
}
}
alpha
}
(rust)
I'll implement this and see what it does
aight, hope it works
if it doesn't, then it's not the algorithm
it could for example be your evaluation function
that's doing a dookie
objects.OrderBy(t => t.localPosition.x);
should it work like this with linq? @hollow garden
surely the evaluation function shouldn't matter, as long as it returns the same thing for the same board?
well that just produces a new list
so you need to assign it to something
the evaluation function should matter, because your score depends on it
so it could be playing worse moves on purpose
cause that's what the evaluation function is telling is good
it should matter in terms of the overall eventual analysis, but Alpha-beta pruning is supposed to return the same move regardless of wether it's enabled or not
it's just supposed to be an optimisation
idk
my evaluate is literally just this
private int Evaluate ()
{
var total = -_wPieceLocations.Sum(pos => (int) PieceAt(pos).Value)
+ _bPieceLocations.Sum(pos => (int) PieceAt(pos).Value);
_numPositionsAnalysed++;
return total;
}

it's good enough for now lmao
well, alpha beta pruning
it prunes nodes it finds undesirable
without it it just searches it raw
and if that's your only metric
the point is that those undesirable nodes wouldn't end up affecting the final evaluation anyways
hence why they're prunable
it's supposed to result in the same value for each eval just with fewer needed evaluations
for all i know it could just be looking at nodes with the exact same score and picking it arbitrarily
eh?
does Application.targetFramerate = -1 result in a 30fps target on DirectX 11, 60fps on DirectX 12?
should i always use 999, -1, 60...
I figured out the issue
I think
The negation of int.MinValue is still int.MinValue
the reason being that int.MaxValue is one less than the absolute value of int.MinValue
expose it as a user setting?
ah yeah that
i use a special Evaluation thing instead of just ints
it has a predefined range of i32::MIN + 1023 to i32::MAX - 1024
yeah it works now with my code
ok now I need to implement multithreading, move ordering, fixed search times instead of search depths and transposition tables using zobrist hashing
The default value of Application.targetFrameRateΒ is -1. In the default case, Unity uses the platform's default target frame rate.
Usually that means unlimited fps, on mobile devices it can be lower tho
is anyone familiar with a private network vendor?
the objective would be to deal with issues illustrated here - https://qz.com/790208/how-the-company-behind-league-of-legends-rebuilt-its-own-internet-backbone-so-that-its-faster-for-gamers/
So I have an
list<IService> _services;
//and a
public GetService<T>() where T : IService
How do I see if the list contains a T, and return a T not an IService?
does that make any sense?
Just (T) the result.
return (T)_services.Find(s => s is T);
Np, you know what is happening in that line?
linq y Lamba timey wimy
I'm not 100% on 'is', but I got the rest
but it feels pretty intuitive
is is pretty intuitive, it returns a bool whether the instance on the left of it is of the type on the right.
oh nice
Fun thing, you can actually cast with it too
if (service is T result)
return result;
Same as
if (service is T)
return (T)service;
(The top one is a tiny bit more performant iirc since it only needs to do the check once. I could be wrong though)
C:\Program Files\Unity\Editor\Data\il2cpp\build\deploy\il2cpp.exe @Library\Bee\artifacts\rsp\7559046136821863181.rsp
Fatal error. Internal CLR error. (0x80131506)
at Unity.IL2CPP.DataModel.Awesome.CFG.TryCatchTreeBuilder.ProcessTryCatchInfo(Unity.IL2CPP.DataModel.Awesome.CFG.TryCatchInfo, Unity.IL2CPP.DataModel.Instruction, Unity.IL2
CPP.DataModel.Awesome.CFG.InstructionBlock)
at Unity.IL2CPP.DataModel.Awesome.CFG.TryCatchTreeBuilder.BuildTreeWithExceptionHandlers()
at Unity.IL2CPP.DataModel.Awesome.CFG.TryCatchTreeBuilder.Build()
so... why might this happen
IL2CPP devs did an oopsie
are there are bunch of side effects that il2cpp needs from opening a project in an editor at least once?
i see this error in my attempts to automate il2cpp windows inside containers
docker containers?
yes
in all my CI scenarios
i have seen issues where a project has to be open "at least once"
like outside of containers
so much unity code assumes that the editor has opened the project
why is my unity hub black screen all of a sudden I am facing it for the first time
This isn't a code question, and do not cross-post
π so where to ask
#π»βunity-talk . There's probably an answer on the forums though
ok
anyone ever had the issue that a gameobject (in this case the playeR) gets destroyed on build? OnDestroy doesnt even get called, but the player is destroyed for some reason..
Is it used ? Maybe this : https://docs.unity3d.com/Manual/ManagedCodeStripping.html
let me check, sec
its disabled
what's the difference between the models it works on vs doesn't work on? works on no or single parents, but not models with multiple ancestors?
also doesn't localToWorldMatrix pretty much tell you the matrix to undo the transformations from all the ancestors?
hey, is it possible to disable physics between layers when the object enter certain trigger and re-enable it when it exits it?
also, which way is the best to check for primary number ?
it sounds like you have a bug in code you alone authored
Hello, i am trying to learn how to add properties to something that already exists, would anyone be able to assist me with this?
It's not possible for properties, if you don't have edit access to the class. You can use extension methods instead.
I am wanting to add more colors to the Color...
You can make a static class that holds a bunch of your own Color values.
The source struct, Color, has been compiled and cannot be modified
Yeah i know i was just trying to learn how to extend what was already there. π
hello is anyone able to help me with my problem?
https://dontasktoask.com/ (also if this isn't an advanced issue, try beginner or general code instead)
well ive asked about 3 times and had no response anywhere so its a bit frustrating. basically im trying to get a prefab to spawn next to a block. its a projectile so it needs to be facing in the same direction as the block. Ive managed to get it spawning next to the "ship" but it's not facing in the right direction
not an advanced topic. take it back to #π»βcode-beginner
if you don't get a response immediately then just wait a little while and ask again.
Hi I need help, I'm developing with the XR interaction toolkit and I have multiple different scenes, all of which I want the XR interaction with a canvas (so I can press buttons) to work. The problem is when I change scenes something bugs out and it stops working. Does anyone know how to help me?
It's very little information about a problem that can have lots of different causes. π¦
Oh okay i donβt know how else to explain it or what to add
hey guys
I'm generating meshes for mountains separately for each world chunk and it all behaves as expected, except the chunk seams
vertices there are perfectly aligned, but you can see a very visible seam
my guess is that is caused by Unity's normal calculation specifics
is there a way to make Unity's calculation aware that normals should be calculated as if the mesh continues further ?
meshes for terrain itself do not have this issue by the way
ok, nvm that, now that I think about it, it makes perfect sense
I guess I need to make an additional pass on the seams after the automatic normal calculation and calculate seam normals myself
Sure, with a bit of Reflection, something along these lines
using System.Reflection;
Assembly a = typeof(UnityEngine.Object).Assembly; // get an object in the assembly to search
Type[] types = a.GetExportedTypes();
thanks lots!
Anybody knows why this code gives different results in Debug mode and in Release mode? In Debug mode it gives the expected result. ```cs
using System.Runtime.CompilerServices;
P p = new P(10);
System.Console.WriteLine(p.i1.data);
System.Console.WriteLine(p[1].data);
readonly struct P
{
public P(int value)
{
i0 = new I(value);
i1 = new I(value + 1);
}
public readonly I i0;
public readonly I i1;
public I this[int index] => Unsafe.Add(ref Unsafe.AsRef(in i0), index);
}
readonly struct I
{
public I(int data) => this.data = data;
public readonly int data;
}```
In Debug mode it writes 11 and 11, while in Release mode it writes 11 and 10.
Here is an interactive version in SharpLab: https://tinyurl.com/yzpfsy96
C#/VB/F# compiler playground.
what is your objective?
There might be a bug in the C# JIT compiler with Unsafe.Add
i cannot make heads or tails of what this is supposed to do
why are you trying to modify read only fields this way
or
i don't even know
what the hell you are trying to do
do you mean debug versus release il2cpp?
Both p.i1 and p[1] reads from the i1 field, however they result in different values
Nothing is modifying readonly fields, it is only reading from them
what's your objective?
No, the C# JIT compiler on the main branch of the dotnet runtime repo
reading a field with an index
okay... why not do it this way?
I this[int index] {
switch (index) {
case 0:
return i0;
case 1:
return i1;
}
}
which is exactly what grpc does
i assume you can't do what you're doing because it's wrong, not that it's a bug
Well, both the Unsafe.Add and the Unsafe.AsRef invocations do exactly what they are supposed to do
Doing it with a switch statement neither inlines nor performs well
It might work when index was passed as a constant and the JIT compiler was able to detect that, but when index is no longer a constant performance problem will arise
A switch will yield an unnecessary jump table when it can simply use an LEA instruction
In release the JIT inlines the hell out of it lol. It does not even access the indexer, it just loads 10 and 11 onto ecx for printing. You might have fallen upon a compiler bug, indeed
Exactly, that is why I posted it here to see if others have noticed something similar
Unlikely, something that advanced isn't common sighting here
You could file an issue on their GitHub after reproducing it on your own system (that will eliminate a potential "online compiler bug")
Hey, I'm curious if it is possible to download a file into a nativearray w/ a unitywebrequest. My main goal is to create as little garbage as possible - Unfortunately I'm dealing with a Unity version where nativeData doesnt exist on downloadhandlerbuffer.
well touchΓ©
Yes I think I will do that. Thanks for the discussion.
does the bytes[] field create a copy?
i don't remember
zip files
Pretty sure I should be able to do the unzipping with little or even no alloc, its just about getting the bytes
I'll go on with the bytes field for now and see how bad that is
maybe its fine who knows
i think don't worry about it
you will allocate in order to decompress a zip file
making use of streams and unmanaged memory unzipping seems to not create garbage at least
okay... but just think about it. you want to take something of length X, and then you do something that does math that turns it into length X+Y
where is Y more bytes of space going to come from?
Well yeah it will of course allocate memory, its primarily about not creating garbage as mentioned above
yeah i think it'll all work out
I shall proceed, thanks
Anyone use switch statements with bit fields? Trying to figure it out. Say I have the following:
[System.Flags]
public enum State : byte
{
None = 0,
Happy = 1 << 1,
Laughing = 1 << 2,
Confused = 1 << 3
}
If I want to switch this with some logic for permutations of interest, I've found I can sort of do it:
return state switch
{
State.Happy => SmileValue,
State.Happy | State.Laughing => JoyValue,
_ => DefaultValue
};
What would I write to achieve a switch condition of "Has Happy and Not Confused"?
You probably would have to use pattern matching to achieve this.
which is basically a glorified if statement
I was under the impression switches were already glorified If statements
To a certain extend, some switch statements can be compiled into much more performant jump tables or binary searches
They are mostly but sometimes there's a jump table optimization
Hrmm, fascinating. I'll have to look more into that. Maybe I'll be best served just using if statements to get the value I need in this case.
Yes, if you can, you should still use pattern matching because it is designed to be more readable
hrmm, using things like and and and not?
haven't really used pattern matching, looking into the docs quick
yes, or use the when keyword so you can put conditions inside switch statements
Cool, thanks for showing me this -- probably will fit the bill best!
hey, what is this error all about InvalidOperationException: Collection was modified; enumeration operation may not execute.
I have a list List<> that stores all objects, but when new objects is too close to another one, it combines into one ( meaning removing that old object and creating a bigger one double in size ).
and if the entire box has too many objects, it destroys everything in it and disable itself.
that error occured while it was in the process of destroying everything on the list
public Pool pool; ///////////// Pool also has a similar list ( has list for all obj in all boxes )
foreach (Object obj in objList)
{
int i = pool.objManagerList.IndexOf(obj);
pool.objManagerList.RemoveAt(i);
objList.Remove(obj);
}
Most collections in dotnet cannot be modified while they are being enumerated
You need to keep track of a list of objects to remove, and remove them after the foreach loop is complete
or you can use the for loop rather than the foreach loop, however it is more difficult to get right
maybe this would work?
pool.objManagerList.RemoveAll(x => objList.Contains(x));
objList.Clear(); *
well I dont understand then, should I use Emulator to destroy the box after 1-3 sec for example ?
how could I know if it's being enumerated or not ?
I can use for loop if that would fix it, but you don't seem to be sure about that ..
I could give it a try
you are enumerating through it with the foreach block, but you are also invoking Remove inside that block, which is not allowed for a List<>
Yes you can use a for loop to fix it, however it is not easy to do it correctly when you are new to programming or C#
either way: this is a #π»βcode-beginner problem
@nocturne tusk @dusky carbon thanks a lot, I dont know few/some basics but I'm not new to programming, either way, thanks, that would do π
the channel has more to do w/ the actual problem and not experience in programming. I have been programming for 10+ years but I still hang out in code-beginner because I'm new to c# and unity libraries (and still learn stuff from there)
me too!
FYI I opened an issue on dotnet/runtime here: https://github.com/dotnet/runtime/issues/71601
pretty great detective work
Can anyone help me ? I want to import .jar file into my project. How can I do it?
lo and behold https://docs.unity3d.com/Manual/AndroidJARPlugins.html
it is not mentioned in the docs, it won't work if the .jar built from older java version
Hi I need help, I'm developing with the XR interaction toolkit and I have multiple different scenes, all of which I want the XR interaction with a canvas (so I can press buttons) to work. The problem is when I change scenes something bugs out and it stops working. Does anyone know how to help me?
I'm attaching a video showcasing what happens
maybe use 1 scene
you don't need to change scenes
use prefabs instead
all the dont destroy on loads
it's hard
But then I have multiple other scenes later
like individual maps
and if I kept the player in the main scene, whenever I reloaded it it would create a duplicat eof the player
Do we need the latest version then ? Actually we extracted the .jar file from .aar file. Will it work?
i don't mean to be unhelpful
it'll make things easier in the long run
by older there, I mean, much older version... us modders love to bring back prehistoric jars from ancient times
I know, but I can't have all the maps in one scene
you can prefab them out
and load them that way
Actually we extracted the .jar file from .aar file. Will it work?
I guess, but isn't there a way to fix my problem across scenes?
you, I, and our lovely doggy dog pet would not know, unless you try it π
it's hard
there are so many things that could be wrong
you are using so many dont destroy on loads
oh should that be kept to a minimum?
it is just one of many pitfalls
I have getting error when I call the method from .jar - Exception: Field currentActivity or type signature not found
I'm using Photon Network for my game, and when I call JoinRoom with what should be an existing room name, nothing happens, it doesn't send me to a room
Debug something in on joined room
that's the thing
Probably better to ask in #archived-networking btw.
oh ok thx
How to deserialize a string like that: "{\"0\":\"1\",\"1\":[\"4\"]}"?
I'm using newtonsoft
Tuple<int, int[]> responses = JsonConvert.DeserializeObject<Tuple<int, int[]>>(response);
but it returns only (0,)
your json has a string[] not an int[]
no#
why would it, this aint javascript
you can however add a custom converter that would try to convert them
now thats the result: (, ) it is maybe worst xd