#archived-code-general
1 messages ยท Page 19 of 1
see if i can get a demo of this idea down
if i cant ill resort to more simplistic and straightforward methods
sounds good
ray marching is neat, neat way of raycasting
well thats one way of doing it, only issue is that itd be heavy on the CPU, and a GPU shader wouldnt really allow for collision changes, neat regardless
Is there any way to reserve a layer for my framework? Kinda what unity does with their "built-in layers"
Maybe you can combine object pooling with low poly voxel collisions if that makes any sense
so like you spawn 100 box colliders at the beginning and just move them as needed to cover the area
yeah, but the issue there is that ill have alot of collision inside that i dont need, if theres a way to decimate the collision on the inside i bet it could work
Not that I know of. Because it would be hard for the engine to differentiate code bases that are your framework and aren't
what about resizing the colliders as well as changing their position
@void basalt you could have an error print to the console that checks if that layer exists
could work, but wont i still have collission faces inside?
ill consider this all tomorrow, i feel super sick today
thanks for the ideas tho
Minecraft tackles this problem. the Technique is called 'Meshing', generating a Mesh from a bunch of voxels
https://0fps.net/2012/06/30/meshing-in-a-minecraft-game/
im getting the Since 'pipespawnscript.spawnTargetPipe()' returns void, a return keyword must not be followed by an object expression error, how to fix that?
{
float lowestPoint = transform.position.y - heightOffsetTraget;
float highestPoint = transform.position.y + heightOffsetTraget;
var buttonspawns = new[] { Random.Range(middle.transform.position.y, -17), Random.Range(middle.transform.position.y, 17) };
var idx = Random.Range(0, 2);
return buttonspawns[idx];
Instantiate(targetPipe, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
Instantiate(button, new Vector3(transform.position.x - 2.5f, buttonspawns[idx], 0), transform.rotation);
}
Don't return anything.
fair enough
Or change the return type of the function
will it work if i just remove the return line
It will compile.
As for wether it would work, depends on your code and what you try to achieve with it. I'd assume that if you added the return, it had some purpose..?
honestly it was just my attempt to fix the code
my goal is to spawn the button anywhere in the y pos except for specific coordinates
never really had an occasion to experiment with that sort of thing so yea
Hi so I have this player prefab setup for my multiplayer top down shooter game. (I'm using Photon as a multiplayer solution btw). The player is made to face the cursor, and will be able to shoot at it later.
My problem is that in the tutorial I am following, the person attaches a camera to the player prefab. When i do this and the player spawns, the camera begins rotating with the player, what could I do to solve this?
don't attach the camera to the player. you're using cinemachine to control the camera anyway so there's no reason to have it attached, just make the player the follow target for the vcam and the camera will follow the player without needing to be a child of it
but how will i manage that with multiple players?
because I can create 1 camera to deal with 1 player, but idk how to do so with more than 1 player
delete the vcams for the networked players so that only the vcam on the local player exists
oh i spawn the players at runtime
well obviously. you can still do that though
just replace the word "delete" in my message with "destroy" if it's too confusing for you
or even just "disable"
ohyea sorry im still new to multiplayer i should have mentioned
im not really sure what you men by local vs networked, could you please explain
since you're using photon i'll put it in super simple terms: photonView.isMine == local player, everyone else is a networked player
well you have to write the code that does that, but yes. disabling or just straight up destroying the non-local player's vcams will make it work
hey there.
i have a ui that display "Step" and its "Required Tools" using one text gameobject.
for this example, the Step is [0] Jack and its Required Tools: should be wrench sz and atlanta grease
but on the text only display the atlanta grease
so what i want is on ui is:
[0] Jack
Required Tools:
- wrench sz
- atlanta grease
how do achieve that? thank you in advance ๐โโ๏ธ
hey everyone, I got this weird thing where I want my player to transition to a sliding position, during which I need to change the capsule collider's direction from the Y axis to the Z axis and lower the center. Though when I do this I can Lerp the Center position but not the capsule direction? so the player ends up moving upwards before the capsule flips. Any Ideas on how to solve this dilemma?
void Update()
{
Ray ray = new Ray (cam.transform.position, cam.transform.forward);
RaycastHit hit;
Debug.DrawRay (cam.transform.position, ray.direction * distance);
if (Input.GetKeyDown (KeyCode.E)) {
if (Physics.Raycast (ray, out hit, distance)) {
if (hit.collider.gameObject.tag == "Door") {
isOpen = !isOpen;
playedAnim = false;
}
}
}
if(!playedAnim) {
if(isOpen) anim.Play("dooropen");
else anim.Play("doorclose");
playedAnim = true;
}
}
I have this code, my animate to not loop, but the door appears to be repeating the end of my door open anim
my code is now
if(isOpen) {
anim.Play("dooropen");
} else {
anim.Play("doorclosed");
}
and now it loops just the door opening
i read somewhere i was supposed to hit apply after turning off loop time, i dont see no apply button
shrink the collider no ?
so wait, why are mesh colliders expensive?
like if you have a cube mesh with a mesh collider, just 4 verts, how is it different from a cube collider
i have this, and im watching it loop on doorclose
The mesh collider uses a general purpose mesh collision algorithm which involves basically making planes out of every triangle in the mesh and checking which side of the plane points are, etc... It's complicated.
A box collider has a known shape and can use a much simpler mathematical formula to test points
A Cube mesh is not 4 verts
It's usually 24 vertices and 12 triangles
Verts are usually duplicated per face to achieve flat shading
i am aware
i used the term 4 verts to simplify what i was trying to say
cuz you can have a cube split in half, that still visually looks like a cube
just specifying it was a basic cube, 4 points
6 sides, whatnot
Regardless of how many vertices, the computer doesn't know it's cube shaped.
8 points*
right
why doesnt it?
How could it
it cant see the mesh, it just knows how much verts and such it has
well if you have 6 faces that all have pretty cube-looking normals.. wouldnt it look like a cube?
Do you think Unity is running some algorithm on every mesh to check if it's cube shaped?
How would such an algorithm work?
Would it be worth running that algorithm on every mesh Ahead of time?
Oh course not
It's just a mesh
Like any other
As far as the program is concerned
Computers don't look at things and draw inferences. They simply do as they are programmed
i know
OBB collision check is way easier than arbitrary polygon collision check
i suppose i was just figuring that if drawing that inference would change a heavily expensive mesh collider to a more recognizeable cube collider, that maybe it would be able to cut down on costs
like a mesh made out of 3 cubes, drawing that inference and having 3 recognizeable cubes... idk.. dumb question
Right but to do this they'd have to write an algorithm to detect that and then check every incoming mesh to see if it's a box.
Isn't it easier to just allow the user to use a BoxCollider when they want box collisions and use a general purpose algorithm for all mesh colliders?
And what about sphere ๐
That would be wasted work for every mesh that isn't a box, which is most of them
And yes what about sphere, and capsule, and so on. Now we're doing like 8 checks for various shapes on every mesh and it's all wasted when it's none of those shapes
Which is most of the time
yeah i know, it was a bit of a stupid question
I mean it's not a stupid question
yeah it was
in retrospect it had an obvious answer, no matter how much costs are cut using cube colliders for certain meshes, its going to cost alot more just to check if they are cubes
i just need sleep
That's a one time cost though vs potentially checking the collision many times. It's really not a stupid question
wouldnt it be more than a one time cost
if the collider is altered in any way, wouldnt they have to check again and again and again
MeshCollider needs to be recomputed any time the mesh changes anyway
Basically like anything else it's a tradeoff which could make sense under the right conditions
But, most conditions are not that ๐
yeah, well i guess i have a new question
whats the best way to go about making raycasts the most efficient they can be?
im using capsules for my players collision and i fear that the collider might make raycasts a bit expensive, especially for how much i want to use them
i want to have simulated bullets, which right now use raycasts, but its many raycasts and i fear that it might become an issue
Unless you've profiled your game and found a problem I wouldn't worry about it
Don't prematurely optimize
i just get scared that my game will wind up like tf2, lots of potential, but the issues stack up because they werent adressed from the start
You're scared your game will end up like a huge success?
Unless you mean something other than team fortress 2
a huge success financially, but bug wise, tf2 has many
i like to optimize everything so that going into the next step i dont have to worry about the stuff i did in the past
Games donโt need to be perfect
Surefire way to introduce bugs is to increase the complexity by trying to prematurely optimize
yeah, but i like to make them atleast pretty good, best i can atleast
Regardless, all software has bugs
i guess..
but like
bullets in this game will be a huge part of it
right now im testing out firing like 5 a second, it works fine
This is not realistic. You WILL have to revisit and refactor your old code many times
yeah, but im trying to make that as minimal as i can is what im saying
Your best bet is writing clean, understandable, maintainable code
To make that process painless
and thats what i got so far
but on the topic of bullets.. whats the best way to simulate them?
im figuring its raycasts
i dont need the bullet to be wide or have any kind of parameter for width
but i wonder how optimized unitys physics engine is, and if optimization wise its better to use raycasts or physics
Itโs about speed and amounts
If you just need one frame hit check you use raycast.
Of you have slow moving bullets and there isnโt ton of them you can use colliders. With faster moving you would need continuous or speculative collisions and even with them it will never be as accurate as linecast.
If you need moving bullets and colliders donโt work, you do linecast / distance limited raycast between position of this and previous frame. Apply gravity manually if needed. Starting from inside the collision donโt work so you either do it from a bit more behind or two way, if they are reeaaally fast. In extreme situations nonallocating version of raycast, since this generates garbage.
If that is too heavy you go and create your own bullet projectile system.
How do I limit the range on a raycast?
beginner is busy rn was wondering if yall could help me
@cinder kindle linecast is exactly that - raycast between two points, but raycast also has maxDistance parameter
what does it measure in?
Same units in coordinate system everything else uses
Is it possible to call a void with more than 1 parameter via button?
For example :
void Set(int health,int armor){}
If you call the void for too long, the void starts to call you.
Please don't use the word "void" for methods/functions. It's not correct.
A button like any other type of event or listener expects to be implemented properly, unless you use a delegate - which has no parameters
Think about it this way: How is the button supposed to understand how to set the parameters of something it doesn't implement?
What you probably want is to implement the button normally, and then call your Set method manually after getting the values it requires
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("ground"))
{
GetComponentInParent<player>().isJumping = false;
}
}
void OnCollisionLeave2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("ground"))
{
GetComponentInParent<player>().isJumping = true;
}
}
Would this work, or is there a scenario where this could enter and leave on the same frame or anything that would cause it to break?
Anyway, I did it with Button.onClick.AddListener();
Seems it's not possible via inspector
correct, the inspector for the onClick event does not support multiple parameters and really only supports a few types of parameters anyway
imagine you jump and the player's head hits a platform above them that has the ground tag. suddenly it's considered grounded despite not being on the ground. you're better off using a physics query like an overlapbox or something.
also OnCollisionLeave2D doesn't exist, but OnCollisionExit2D does
this is attached to a groundcheck
and yet it's still not a very good way to check if the player is grounded. Whoops, i bumped into that object that has the ground tag while walking on the ground and then moved away from it. guess i'm not grounded anymore
I tried creating an overlapboxall, but it doesnt seem to work. is there way to display the box in the scene?
also, is there any difference / preferred use for new Vector2 (x, y) as opposed to (Vector2) x, y ?
you'd need to either draw the box yourself with drawlines or gizmos or grab a visualization library like one of these two:
https://github.com/nomnomab/RaycastVisualization
https://github.com/vertxxyz/Vertx.Debugging
go with the first one, it's more clear what you are doing and is a more sane way to create a vector2. i honestly didn't even know that second one was possible (if it even is)
All prefabs in Resources folder are loaded at the start of game.
How do prefabs not in Resources folder work? Are they only loaded when you instantiate them, or are all prefabs referenced in a scene loaded at start of game?
wait I am dumb. the second one was in a tutorial, but it really just interprets X which was a Vector3 as a Vector2.
yeah that makes more sense and is perfectly fine
They are loaded when the scene is loaded
Loaded whenever something that references them is loaded
Addressables is the way to handle that sort of thing if you want control over memory
Hello, my question is about new input system and best practice with it. So u can auto-generate a new script with all configured actions, then u should create an instance of it and then u can enable/disable action maps or subscribe to events. The question is, how do u create an instance of this script? Do u create it in every class that depends on the input system? Or do u have a god class that just gives everyone access to it? And if second, then maybe it would be more convenient to do the enable/disable logic in the god class as well, so the transactions between game modes would be easier to understand?
dunno if it's "best practice" or whatever, but i typically go with the first option of creating an instance for each object that needs to use the input and only enabling actions that object depends on, although i also don't typically have a whole lot of objects that need input
So that's is an option too, hmm. It's just felt weird to create it over and over again, I felt like I'm missing the point of having multiple action maps in the first place, when I'm using only one in every class.. The project I'm working now will have multiple input devices in the end and a lot of different button events
(C#) Hello, I have a quick question. Using a repository in a (view)model, is this valid MVC?
I don't understand the question regarding repository and MVC. Anyhow, this seems to have nothing to do with Unity, pinned in the top right here, at the bottom there is a link to an actual C# discord server.
hey guys. I have a drag and drop function in my game and when I have an object over a trigger zone it snaps to the place it's supposed to. I've made a silly script that works given the time sensitivity of it. And basically I want it so that when it's let go it returns to its original position unless it's in the trigger zone.
iDragComponent?.onEndDrag();
if (ObjectInBounds == true)
{
MaskObject.transform.position = MaskPosition.transform.position;
}
if (ObjectInBounds == false)
{
MaskObject.transform.position = MaskOriginalPosition.transform.position;
}```
Here's the code where it checks if it's in the bounds. For some reason it works if it's true (snapping to the desired location) but it doesn't if it's false (returning to its original position)
ObjectInBounds is updating just fine
given a pos & normal of a face, how do I know if it is facing a camera or backface?
https://docs.unity3d.com/ScriptReference/Vector3.Dot.html
Where forward is the normal, and the toOther is the camera position should work I think.
it does not because you need the position - a face to right of camera may be backface but on left of camera is visible - I can't remember the maths on this!
is it dot of face pos - cam pos & the face normal maybe...
used to know this but google not helping me!
I was right - chatgpt to the rescue, damn that is helpful...
i downloaded a zipped file and i apparently i cant delete it even if i did it from cmd and it says its in the desktop and when i go to the location its not found i only can see it recent page so i pinned it so i can see it if its gone from the recent page any help plsss
i downloaded a zipped file and apparently i cant delete it even if i did it from cmd and it says its in the desktop and when i go to the location its not found i only can see it recent page so i pinned it so i can see it if its gone from the recent page any help plsss
Change Z to Y pretty sure
hmm
ok
help pls
i m making my own transformers game and my question how to combine transformation animation to transform button
Dead
i downloaded a zipped file and apparently i cant delete it even if i did it from cmd and it says its in the desktop and when i go to the location its not found i only can see it recent page so i pinned it so i can see it if its gone from the recent page any help plsss
how th did u make the message into a file lmao
You start a region with #region but don't end it with #endregion like the error message says
discord wont let me send it
too many letters i think
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
make a notepad file then attach it discord
thats not what i meant
if u look at the file u can see he ended it with three
`
`
`
yes, that's where you start the region
#region Movement
i didnt use #endrigion
#endregion Movement
you need to, thats the error
oh
and that's exactly the problem
thats the error
Do you mean play an animation when you press a button?
This means that inputHandler is returning null or returns with no value..
how would i give it value
https://gdl.space/gorocabiro.cs
inputHandler = GetComponent<InputHandler>();
this object apparently does not have an InputHandler component on it
Hi im having some problems when trying to use untiy UI and UI Toolkit I explained the problem in this reddit post, would be glad if someone could help: https://www.reddit.com/r/Unity3D/comments/10g1cz2/unity_ui_not_working_with_ui_toolkit_because_of/
0 votes and 0 comments so far on Reddit
not the right place for this... #๐งฐโui-toolkit
however check your UI toolkit document
Ok right, i've created a emptyobj called player with the child Player (model) and i've used these 3 scripts to try make it move
https://gdl.space/rociduhiya.cs input handler
https://gdl.space/qevuraroka.cs Playerlocomotion
https://gdl.space/hoporohebe.cs AnimatorHandler
I've gotten 0 errors on VS code and unity console
and my player still cant move or do anything its just stuck in a T pose
should be able to make the background for it non-interactable which probably fixes it
how can i put lives next to my text?
Does anybody know how to rotate/flip a particle system in Unity 2D? I want the particle system to rotate/flip to the direction that my character is facing, but I haven't been able to figure it out.
Concatenate it to the string text
can you destroy other object? Destroy(other.gameObject);
ya
it gives you the collider you collide with
so if this function is on your player
you probably want to see if the collider is ground, not the player.gameobject.collision(which I find unlikely to exist)
remove player game object
doesnt work
Sure it does, why wouldn't it.
Ok so i've created a player action map and a playercontrols script, i've made sure all my composites work
but whenever i play
nothing happens
the name other does not exist in content
i've created a playerlocomotion script
https://gdl.space/qevuraroka.cs
but still nothing happens
How can i display my text and score next to eachother? void OnGUI() { GUI.textScore + ": " + score; } }
Should result in collision.collider.CompareTag
You've clearly got other issues unrelated to Destroy.
i dont understand, i got a error here
The code isn't yours if you've not got something called other in that scope
Hi Guys
I have problem. I have piano in the scene where every key is seperated GameObject.
Piano has script and in this script i first convert all keys into dictionary so i can access them from code easly. I invoke function on event when signle note in MIDI file is being played but when i try to access single key Animator it give me error that GetComponentFastPath Can be only use in main thread. Help !!!!
Here is code:
Need help with my player movement
if player collides with a gameobject of tag Ground the bool is true
why i get gui doesnt not have definition for scoreText void OnGUI() { GUI.scoreText = scoreText + ": " + score; }
you know i didn't think of just making a short, long collider instead of swapping the axis. it should work all the same though right?
is GUI a monobehaviour reference? what's the variable you've named for the text script?
also you can do $"{scoreText}: {score}";
public static float score = 0;```
scoreText.text = $"{scoreText}: {score}";
hi i need help with playermovement
void OnGUI is a build in function of Unity
Don't remember exactly what it does tho
i was asking about GUI.scoreText
Ah my bad
[CreateAssetMenu(menuName = "ItemList")]
public class ItemsList : ScriptableObject
{
public List<ItemReqs> CommonItems;
public List<ItemReqs> RareItems;
public List<ItemReqs> EpicItems;
public List<ItemReqs> LegendaryItems;
public List<ItemReqs> MythicItems;
}
[Serializable]
public class ItemReqs
{
public string ID;
public Sprite sprite;
public MyItemRarity rarity;
[Dropdown("GetItemTypeValue")]
public MyItemTypes itemType;
private DropdownList<MyItemTypes> GetItemTypeValue()
{
return new DropdownList<MyItemTypes>()
{
{ "armor", MyItemTypes.Armor },
{ "helmet", MyItemTypes.Helmet },
{ "jewelery", MyItemTypes.Jewelry },
{ "weapon1h", MyItemTypes.Weapon }
};
}
[ShowIf("itemType", MyItemTypes.Armor)]
public string IDHelmet;
[ShowIf("itemType", MyItemTypes.Armor)]
public Sprite spriteHelmet;
}
Not sure what I'm doing wrong
the ShowIf condition isn't working
thic should be with two c's, so thicc
Wait is this from the Odin Inspector?
NaughtyComponent
but they are pretty similiar
pretty sure the docs say Im doing it right
shoot, that again
anyone knows why i get the whole tmpro.text.mshproug i dont need that.
thanks @late lion
so its nested because the code is inside of another list basically?
So im making a souls like movement using this video https://www.youtube.com/watch?v=LOC5GJ5rFFw&list=PLD_vBJjpCwJtrHIW1SS5_BNRk6KZJZ7_d&index=3&ab_channel=SebastianGraves
and i've done everything however nothing is happening when i press play
โบ ANIMATIONS
https://drive.google.com/drive/folders/1j2HicZMabg4h2Oe8ocxGNuKBHY5kzFJA?usp=sharing
โบ PLAYER MODEL
https://drive.google.com/file/d/1KdBzSiz0rDiZ9X-g2SdfAnj9ebIRVXlV/view?usp=sharing
โบ EPISODE TWO
https://youtu.be/c1FYp1oOFIs
โบ SUPPORT ME ON PATREON!
http://www.patreon.com/SebastianGraves
โบ ASSET STORE PAGE (Animations & Models)...
define nothing
Yeah, it's considered nested because the field is not directly in the MonoBehaviour or ScriptableObject.
maybe Im missing something but I haven't seen any code
awesome thanks!
these are the 3 main scripts he uses in the video and a playeractionmap which i've done already (WASD)
i press play and the character just falls to the ground slowly and whenever i use my WASD keys he doesnt move like hes supposed to
define like he's supposed to
move around the plane without any animation and rotate whenever i press s (to move down) or w (to move up)
this SO has "headers" like Equipment and Body
how do I do that in code?
(this script is DLL so can't see how he did it)
yes
anyone can help with ui problem
hmm
[Header("Weapons")] was what I needed ๐
How do you rotate a Tilemap's placed tile at runtime?
e.g.:
_tilemap.GetTile(worldCellPosition).rotation = ...
Solved
var tileTransform = Matrix4x4.Rotate(Quaternion.Euler(0, 0, someArbitraryValue));
var tileChangedData = new TileChangeData()
{
position = ...,
tile = ...,
color = ...,
transform = tileTransform
};
_tilemap.SetTile(tileChangedData, false);
Hello there!
I have a parallax effect script that I would like to use while I am in the editing mode of my game. Any idea as to how I should implement it to work in editor?
public class ParallaxEditor : Editor
{
[SerializeField] private Parallax parallaxObject;
void Update()
{
parallaxObject.UpdateParallax();
}
}
Anyone now how to change an enum value from a Unity event on another script or object?
dont ask if anyone knows. Just show your issue/attempt and ask for help
I don't have an issue attempt as its not something I can do currently. Whish is why I'm asking for help by saying "does anyone know"
can you explain what you mean by "from a unity event"?
I can give an example
please
Say you have a script with an enum, doesn't mater what it is Dog, Cat, Reindeer, etc. What ever. Then in a unity event for example on the ones on a button that fire on click. In that event you add the script with the enum by dragging it on and then you have a drop down in the unity event and you can chose things like Gameobject set active(bool) or EnumScript bool enabled.
But how can you select the enum and switch it or pass it a string to change the enum?
you define a method that takes in an enum, then you assign that method to the onClick event. There should be a field that allows you to select what enum that button's onClick will send
I think so, at least. I havent tested if enum parameters will show up
keep in mind you will need to drag in an object that has that script with that method attached, not the script itself
There is no way for me to make LineRenderer segments dissapear and reapear as needed other than creating a LineRenderer per segment or writing a complex shader, correct? Nothing like "disable segment" or "change texture for segment (to invisible)"? I'm asking becuase I'm already managing a 32x32 array of line renderers in my code and solving this problem by adding MORE line renderers would make the flow quite incomprehensable ๐
Yes I understand Unity events and have dragged on the object with the event and can select the script in the dropdown but I don't see the public override bool event in the list of options to change the enum with the btn click.
i dont understand what you mean. please show a screenshot of the inspector
what's the script and what's the method you're looking for?
The script is HVRGrabSideLimiter
Looking for
public override bool CanBeGrabbed(HVRHandGrabber hand)
It uses
public HandOptions AllowedHands;
To set an enum Hand Options with Left Right or Both.
honestly am not sure. but I wonder if it's because of the bool return type
I couldn't find what the limitations are on UnityEvents in inspectors in the documentation
you can test by just defining a method that has a void return type and no parameters
then one with a void return type and that same parameter
Yeah its a odd one. Thanks for taking a look at it.
would be interested to know if you do figure it out
public static void PlayAnimReversed(this Animation Anim, string animationName, float Speed = 1f)
{
Anim[animationName].speed = -Speed;
Anim[animationName].time = Anim[animationName].length;
Anim.Play();
}```
Tried smth like this, didn't play anything
show the inspector of the object that has this script on?
it's a public static Utility class
Here's the MonoBehaviour class ```cs
if (GetKeyDown(NextWep))
{
ChangeWeapon(GetNextWeaponIndex());
}
if (GetKeyDown(PreviousWep))
{
ChangeWeapon(GetPreviousWeaponIndex());
}
}
void ChangeWeapon(byte index)
{
Weapon wep = WeaponsInInventory[index];
Utility.PlayAnimReversed(wep.wepAnim, wep.WepData.drawAnim.name);
Debug.Log("Changing Weapon");
}```
debug log prints with no errors
Hi, I was asking for the inspector
uhh okay
WeaponsInInventory gets filled when the game starts
where's the animation component
can you show me the inspector of ak74_shoot?
I'm using the legacy animation player
does a log print if you put it in PlayAnimReversed?
If there really is no error message, then no clue ๐คท
anyone have any idea what unity is trying to tell me here? it's a fairly fresh project with not a whole lot in it. 2022.2
yeah lol it's pretty weird, I'll try using normalizedTime instead
It's trying to tell you that... it has UI bugs ๐
it doesn't seem to be causing trouble, so I assume it's safe to ignore?
I should try updating. i'm on 2022.2.0f and it looks like there's a 2022.2.2f
probably yeah
and yeah upgrading may help
it may also introduce new bugs ๐คฃ
sweet, thank you Praetor
If you want the most stable Unity experience stick to LTS versions
any idea on
{
Mesh _mesh = new Mesh();
List<Vector3> vertices = new List<Vector3>();
List<int> triangles = new List<int>();
int size = 20;
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
Vector3 a = new Vector3(x - .5f, 0, y + .5f);
Vector3 b = new Vector3(x + .5f, 0, y + .5f);
Vector3 c = new Vector3(x - .5f, 0, y - .5f);
Vector3 d = new Vector3(x + .5f, 0, y - .5f);
Vector3[] v = new Vector3[] { a, b, c, b, d, c };
for (int k = 0; k < 6; k++)
{
vertices.Add(v[k]);
triangles.Add(triangles.Count);
}
}
}
_mesh.vertices = vertices.ToArray();
_mesh.triangles = triangles.ToArray();
_mesh.RecalculateNormals();
MeshFilter meshFilter = gameObject.AddComponent<MeshFilter>();
meshFilter.mesh = _mesh;
MeshRenderer meshRenderer = gameObject.AddComponent<MeshRenderer>();
}```
its simply not creating any mesh
any errors in console?
also noting you haven't assigned a material to your MeshRenderer
yeah, object reference not set to an object from the mesh filter
mesh is just not creating
Does your object already have a MeshRenderer
it creates it in the code
or does it need to create it before
the error is meshFilter.mesh = _mesh; this line
also if i asign the component in the inspector it just loads infinitely and crashes unity
This means the AddComponent failed
the only reason that would happen generally is if there was already a MeshFilter on the object.
Are you running this multiple times ont he same object?
i accidentally had it on a for loop ._.
ok mb im dum
ty
when should I use c# pointers in Unity?
i dont think C# has pointers
C# doesn't have pointers, not directly
it has
Only in unsafe contexts
If you have to ask, the answer is never tbh
Are you trying to set the state to DEAD or find all players whose state is DEAD? = is assigning, == is comparing.
hmm ok thanks
I'm trying to update an object's position with transform.position = Vector3.MoveTowards(transform.position, targetPos, Time.fixedDeltaTime); this is inside the Fixed update method along with some other physics stuff. The distance between the current position and target position is always relatively small, however the position is updated way too slowly and it makes the object seem almost floaty. If I multiple Time.fixedTimeStep by some speed value then the speed is fine but the problem now is that it's really jittery and not frame rate dependant
Switch to Update
And use deltaTime instead of fixedDeltaTime
It looks like you're trying to use Find like a foreach. It's expecting you to return a boolean in that method and it will give you the first element where that method returns true for.
You're using find incorrectly
Find returns a item based on your predicate
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.find?view=net-7.0
ok my mistake
So either switch to a foreach or use Find as intended.
Thanks, that hasn't completely fixed my problem but it is working better and has pointed me in the right direction
If MyContainer is a struct that's the issue
you would need to switch to a normal for loop, pull the struct out, modify it, then write it back
for (int i = 0; i < GM.playerarr.Length; i++) {
GameManager.MyContainer x = GM.playerarr[i];
if(x.player == obj.GetComponent<NetworkObject>()) {
x.state = GameManager.PlayerState.DEAD;
GM.playerarr[i] = x;
}
}```
for example
Hi there!
I'm currently wrapping my head around the following issue and I need some input for solving.
Scenario is the following: Imagine a Tower Defense game where you have a catapult that can shoot a bullet in a ballistic way to a target, I've done the ballistic calculation with this method:
public static Vector3 CalculateAdjustedBallisticVelocity(Vector3 launchPoint, Vector3 target, Vector3 weaponForward)
{
var h = launchPoint.y < target.y ? target.y + 1 : launchPoint.y + 1;
var gravity = Physics.gravity.y;
var displacementY = target.y - launchPoint.y;
var displacementXZ = new Vector3(target.x - launchPoint.x, 0, target.z - launchPoint.z);
var time = Mathf.Sqrt(-2 * h / gravity) + Mathf.Sqrt(2 * (displacementY - h) / gravity);
var velocityY = Vector3.up * Mathf.Sqrt(-2 * gravity * h);
var velocityXZ = displacementXZ / time;
return velocityXZ + velocityY * -Mathf.Sign(gravity);
}
My issue is the following: The method calculates the direct velocity needed to reach the target from a certain launchPoint.
However, the catapult sits on a rotating platform that may need some time to adjust.
The catapult should still fire its payload with the same force but in the direction of the platform rotation (that is the weaponForward parameter that is unused yet).
My issue is, that I can not think how to adjust the return value of the function so it uses the calculated force vector but fires that in the direction of weaponForward.
Anyone got any idea?
Thanks!
I managed it with a bunch of functions to just force the enum switch based on what I need set
public EnumExample myEnum;
//Some function to do things based on the selected enum.
public enum EnumExample
{
1,2,3
}
//Functions to change enum at runtime
public void option1()
{
myEnum = EnumExample.1;
}
public void option2()
{
myEnum = EnumExample.2;
}
public void option3()
{
myEnum = EnumExample.3;
}
Those public void options then show up in a unity event and you can just call the one you need to switch the enum in use at runtime.
Hi, I am unable to use any UnityEngine.U2D components with assembly definition. Do I have to add any references to the assembly definition? If so which references do I have to add on assembly definition.
yes add dependenies to any packages you want to use
Which one? There is no UnityEngine.U2D.
that's a namespace
the package is whatever package the classes are in
looks like they're from the 2d pixel perfect package
That one is not the one I'm using but thanks to you I was able to figure out the correct one.
Does it not work with an enum parameter?
Hello, Iโm trying to create a custom obstacle avoidance script using an ik chain attached to a skeleton, I need to be able to find the position a bone will be updated to originally as if my script hasnโt changed it any clue how to get it? Itโs to blend it with my ik target so it follows the normal foot animation
Is this same as what you are trying to do?
https://github.com/cathei/RotationMath/blob/main/Packages/com.cathei.rotationmath/Runtime/RotationMath.cs#L180
Hmm actually it seems like you have the velocity as result
Not sure. The initial speed is the thing I want to calculate with the given start, end and angle.
Oh so it's kinda the opposite I see
Anyways so you only need Yaw from weapon forward and apply same pitch/magnitude for final result?
Itโs just rotation on y-axis that needs to be adopted
Yes so yaw
If your weaponForward has 0 for Y and normalized then I think it is as simple as
return weaponForward * velocityXZ.magnitude + velocityY * -Mathf.Sign(gravity);
If weaponForward has Y or not normalized first do this
weaponForward.y = 0;
weaponForward.Normalize();
I wasn't able to get the Unity event to have a drop down of enum parameters if that is what you mean. Not to say its not possible I just didn't find a way. But calling the needed function and setting the enum at runtime is working for my needs.
Thoughts on scriptable objects to store game state to replace a singleton? Downside looks like having to assign the reference in the inspector to every relevant object. If every enemy needs to know game state to decide to attack, this downside likely outweighs the potential benefit of eliminating a singleton. Does this sound accurate?
It's not the worst idea. It's the subject of the famous austin talk
the nice thing about it is it lets you not worry about which scene the state management object lives in
and whether it will survive scene loads etc
it's just always there
btw that talk also spawned this project which formalizes and expands the idea into a nice package:
https://github.com/unity-atoms/unity-atoms
That talk is actually what got me thinking about this. The systems described in there seem different because they don't seem to use individual scriptableobjects to influence as broad of a group of things as I use my game state. A comment on the video planted the seeds of doubt for this use case.
Definitely going to check out that package.
What do I do when Unity is pretending there is Input which is not ocurring
if(Input.GetKeyDown(KeyCode.Tab));
{
ToggleVisible();
Debug.Log("TAB!");
}
keeps getting spammed even though nobody is touching the key lmao
you have a semicolon after your if statement
making the if statement useless
your IDE should be bugging you about this
You're an absolute Godsend though man, I have no idea what I'd do without you
Of course, it's always Unity's fault with you. So insufferable lol.
As Praetor said, you need a configured IDE to ask questions here. Then you wouldn't need to blame Unity, because Unity would be blaming you for your clear and obvious mistakes.
#854851968446365696 has the guides for it.
Anyone know a runtime Fuzzy Search library I could use that would be somewhat similar to the Editor space one Unity already has?
https://docs.unity3d.com/ScriptReference/Search.FuzzySearch.FuzzyMatch.html
Hey! Has someone here managed to rip an Escape from Tarkov scene and patch up the terrain? ๐ค
Probably not a good idea to ask a bunch of game devs if anyone's stolen assets from a published games
Uhm, it is to make a small animation, I am sorry
I'm trying to make my rotation more gradual but having trouble figuring out how to do it. I think I need to use slerp, but I'm not sure what to use as t. I have a character that looks generally the same way as the camera, when the camera moves I want the character to rotate towards the same way, but not instantly. I was doing this:
rigidbody.MoveRotation(Quaternion.LookRotation(forward, up));
but I figure I need to do something more like this:
Quaternion targetRotation = Quaternion.LookRotation(forward, up);
Quaternion finalRotation = Quaternion.Slerp(transform.rotation, targetRotation, );
rigidbody.MoveRotation(finalRotation);
but what to use for t?
I figured it out by the way, I was just googling for the wrong thing ;-;
Turns out just using .GetPreferredValues does exactly everything I need
So it's just one line box.size = text.rectTransform.sizeDelta = text.GetPreferredValues(); of code that fixes all of my issues
Tiny bit salty
Hi I have a quick question how can I create a 2d array for audio clips
AudioClip[,]?
Whats your use case, i've never seen someone need that before?
I tried that one but didn't appear on inspector. I am trying to make a footstep system.
yeah, unity doesnt serialise multidimensional arrays
just use array/list of a class which contains what AudioClips you need?
i don't really get why you need it to be multidimensional
I dont know
How can I get the closest point to my player character? I've been using an physics.OverlapSphere to get a list of nearby colliders, then getting the closestPoint of each collider, then finding the one of those that is nearest to my character position. However, you can only get closest point from a collider if it is convex, and I would like this to work with meshes that are not convex. I was thinking a spherical point cloud of raycasts, but is there a better way?
just a really lokey tmp function sitting in docs. wow.. figures unity shenanigan
Yap ;-;
I have this newly created TEST script which first wasn't included as part of the project, now I included it, so what's wrong?
- #854851968446365696 on how to post code
- Provide more context, such as what is the error
๐น
No class IEnumerator
Test and UnityTest are not attributes
cannot resolve symbol void
that's it
nvm
Anyone know of a good FuzzySearch library that works with Unity? Trying to find one is just bringing me the UnityEditor FuzzySearch libraries and Odin, but I want one that can work at runtime
Preferably one I can add through the package manager, even if I have to add a github repo to the package sources
https://www.dotnetperls.com/levenshtein
might help you
or just using Levenshtein distance as a term in general to find a implementation
What mocking frameworks are popular with unity now?
i just use the built in testing stuff, and just use interfaces alot to make tossing in mock implmentations easier
How about mocking transforms and stuff?
have not had much to any need to mock transforms
I have never used a mocking framework with Unity but then again I've only done unit testing in a couple projects
most of my test coverage is not in things where i will need to mock a transform
What should I test and what I shouldn't test?
that is up to you
thing is lots of thigns are games are hard to test
since you really can only easily unit test deterministic stuff
"Vector3.forward can not be accessed with an instance reference; qualify it with a type name instead."
I understand that the error is trying to tell me exactly what do but I don't understand it entirely in this context.
float inputY = Input.GetAxis("Vertical");
if (inputX < 0.3f && inputX > -0.3f) inputX = 0;
//else rb.AddForce(camTargetObject.transform.right*inputX*ballForce);
if (inputY < 0.3f && inputY > -0.3f) inputY = 0;
//else rb.AddForce(camTargetObject.transform.forward*inputY*ballForce);//TODO: diangonal input makes player move faster!
Vector3 moveDir = new Vector3(inputX,0,inputY);
moveDir = moveDir.normalized * Time.deltaTime;
moveDir.forward = camTargetObject.transform.forward;
rb.AddForce(moveDir * ballForce);```
moveDir.forward?
what is that supposed to be
did you just write this in reverse?
moveDir.forward = camTargetObject.transform.forward;
Did you mean to do:
camTargetObject.transform.forward = moveDir;?
I need to make MoveDir face the same direction as camTargetObject.transform.forward, essentially
that's just moveDir = camTargetObject.transform.forward; but then that makes all the calculation before it pointless
also would use LookRotation to make a quaterion for that
what you actually want I believe is this:
moveDir *= camTargetObject.transform.rotation;```
you don't want it in the same dirtection
you want to rotate the input according to the camera perspective
Vector3s can not be multiplied
Operator '*=' cannot be applied to operands of type 'Vector3' and 'Vector3'
good thing that's not a Vector3
it's a quaternion
you typed what I wrote wrong
same error regardless
moveDir = camTargetObject.transform.rotation * moveDir;
definitely not the same error
it would say something about quaternion
this will work tho
float inputX = Input.GetAxis("Horizontal");
float inputY = Input.GetAxis("Vertical");
if (inputX < 0.3f && inputX > -0.3f) inputX = 0;
//else rb.AddForce(camTargetObject.transform.right*inputX*ballForce);
if (inputY < 0.3f && inputY > -0.3f) inputY = 0;
//else rb.AddForce(camTargetObject.transform.forward*inputY*ballForce);//TODO: diangonal input makes player move faster!
Vector3 moveDir = new Vector3(inputX,0,inputY);
moveDir = moveDir.normalized * Time.deltaTime;
moveDir *= camTargetObject.transform.rotation;
rb.AddForce(moveDir * ballForce);
"Operator '*=' cannot be applied to operands of type 'Vector3' and 'Quaternion"
^^^^
Quaternion * Vec3 works
not the other way around
If you sent a line that doesn't throw an error I'm not seeing it
right here sir
Ah I left the *=, my bad
That did it, thanks for the timely response.
I had to massively increase my force value but I assume that's because I wasn't normalizing or multiplying by time before this. Thanks again.
you should pretty much never multiply forces by deltaTime
and you should also only be adding force in FixedUpdate
not Update
This is fixedUpdate. Time multiplier is not necessary for adding force in FixedUpdate?
No because fixedUpdate is already frame-rate independent
Alright, makes sense. Thanks.
nope
AddForce already assumes it's happening once per FixedUpdate
multiplying it in again does nothing except divide all your forces by 1 / Time.fixedDeltaTime
Ideal coding right here
parameterController.SetInteger(this.typeof(STATES).Name, System.Convert.ToInt32(this.getState()));
I have probably made a mistake using enums instead of some wrapper class but hey, it technically works
It feels morally wrong to have an essential part of my code be controlled by getting the name of an enum type
don't you just want:
parameterController.SetInteger(nameof(STATES), (int)this.getState());```
or whatever the enum type is actually called
rather than STATES
nah STATES is a generic enum so taking nameof just returns "STATES"
i need it to be the name of the passed enum type
i can never remember if i am using the right vocab, its this
public class StateMachine<STATES> where STATES : System.Enum
let me check again, it definitly wasnt working with just that but i could have been wrong
you can definitely simplify the int casting part at least
for some reason it was throwing an error when trying to cast directly like that, i will check again tho
yep just tested it, it gives "STATES:
name = nameof(STATES); //name is a public property of the statemachine class
Debug.Log(jumpMachine.name); //jumpMachine is a statemachine
i dont think it likes casting it when the state is generic. If i had to geuss its because it doesnt know if the associated value with the state will be within an int but IDK i havent done too much with that in c#
This is because although the generic type is constrained to an enum, the backing type isn't guaranteed to be Int32.
oh huh neat, so then its treating it as if i tried to do (int) somethingOfTypeObject, essentially?
Enums can be backed by any integral type, so it doesn't know you're dealing with an int, or even types that have less precision. There's nothing stopping that from being an enum whose backing type is a long
Though I'm not sure the generics can infer any of that, but at least know that there's a lot of values it could actually be that isn't just int
oooh so its not sure if its a short or a long or any of the other integer types?
And yet this works ๐ค
longs can be explicitly cast to int i think in c#
well that is honestly a surprise to me, but I suppose it's explicit
Works for byte enum as well.
well yeah I know they can be cast
Kinda feels like the generic way should work too
maybe with a warning about potentially losing precision?
But yeah I guess it's less explicit
/shrug Just an interesting quirk of the compiler and/or language spec I guess
does the (int)(object)state way of doing it box, or is it a way to just bypass the pain
is there a way to restrict the type of the generic enum to be backed only by ints?
ill try it looks goofy as hell tho lol
very sad
boxes yea
also how do you see the bytecode like this?
Rider IL Viewer
C#/VB/F# compiler playground.
or that
oooh neat
if you really cared about boxing, the collections package has an UnsafeUtility.As method that'd probably bypass that
wait can u just cast it to system.valuetype instead of system.object to avoid boxing?
my understanding of boxing is that its really slow right?
well it makes an object on the heap which needs to be garbage collected later
unfortunate this is being called ~every frame so i probs shouldn't be doing that then
that's still boxing
huh I misunderstand what value type is then a bit
wait so then does Convert.toint32(state) also box stuff?
Yes
I am trying to rotate the parent with the children moving to face the direction of the parent but what happens is that the parents rotates and the children each individually rotate but don't move to face what the parent is facing
i think i know how to grab microphone input but what about transcribing it?
space.world instead of space.self?
if that rotation code is on the parent
it is doing the same thing
no difference
do you have the same script on the children by chance? because it should only be on the parent
nope
it is only on the parent
hey, so i have multiple instances of the same gameobject (pipes from floppy bird) and i want to spawn another gameobject right between two pipes. how can i code it so vector2 measures distsnce only between two pipes spawned next to each other
interestingly if I rotate it using the inspector, it seem to work fine
huh wierd I would expect what you have there to at least change their position a little
nope just rotates them but doesn't move them
if i grab input from my microphone, how would I transcribe ir?
this might be the thing for you
https://bitbucket.org/Unity-Technologies/speech-to-text/src/master/
in general search for "Speach to text" + Unity and you should find some interesting stuff
hey bois quick question
what is the max value for TMP_Text.alpha (to set fully visible)
looked through the documentation and couldnt find
1f
thanks ๐
whats the best way to go about making colliders for a map segment
i need to load in rooms that will be put on the end of eachother in a procedural fashion, but a mesh collider might be unoptimal for the game, and a bunch of cube colliders might be unorganized and messy
from the phyiscs performance side box colliders are probably the best option for this
there should be ways to organize the colliders out of your view when you dont to see them
hm..
is the mesh collider bad if it has a relatively low ammount of verts and the mesh itself is heavily optimized? (like 5 cubes)
because i plan to have one mesh be the actual appearance of the map segment, and another mesh that is heavily dumbed down purely for use with a mesh collider
this is so that i dont have to disable collision for 15 cube colliders just to turn off collision for one map segment
question i have some code here and i was wonder how do you pause a countdown ```[SerializeField] Image image;
[SerializeField] float speed;
public float currentValue;
void Update()
{
if (currentValue<100)
{
currentValue += speed * Time.deltaTime;
}
else if(currentValue > 100)
{
currentValue = 0;
}
image.fillAmount = currentValue / 100;
if(currentValue > 20 && currentValue < 40 && Input.GetKeyDown("space"))
{
//pause the count
}
else if(currentValue > 70 && currentValue <90 && Input.GetKeyDown("space"))
{
//pause he count
}
}```
How would one write code that clamps the rotation of an object to the nearest arc (like in my case I need it to clamp to 45 if its 45.7 or 44.2 or to 90 if it's 71.x or 100.x)
- track the rotation with your own float variable
- divide by 45
- round to int
- multiply by 45
- set the rotation of the object from your float
nvm i figured it out
Thanks ill try that
Hi all, Unity beginner here. I'm trying to use the perception module to generate a synthetic dataset for ML training. I have a cucumber prefab and I want to procedurally generate random peeled areas on this cucumber which I will later try to segment. Is my best approach writing a shader that takes in a randomly generated mask representing the peeled areas for which the default skin color of the cucumber would be changed to a flesh color? Or is there some other method I should use? I'm totally lost here
Also, I'm new to this server so please point me to the appropriate place to ask my question if this is it!
Not sure what segment means exactly in this context, but yes a shader that takes two different albedo textures, and uses a third mask texture to switch or blend between them would probably be a good approach
I recently used that for peeling paint on walls, so it should work for peeling cucumbers too ๐
Thanks for the reply! Segmentation is a computer vision task, basically training a model to segment out a region in an image.
The other thing I need to do is create a new object for the peeled regions of the cucumber that has a transparent material (you might be asking why... it's required for the perception module I'm using). My best guess right now is to duplicate the cucumber object and remove triangles from its mesh that correspond to unpeeled regions. I expect this will be a pretty slow process. Do you think this will even work? Do you suggest I try something else? Will I have to create a new object for each continuous peeled region or can I create an object that has a mesh that is made of unconnected parts (representing all the peeled areas of the cucumber)
Does the peeled part need to have a separate collider?
@vital thorn The unconnceted parts can be a single mesh/object, no need for separate objects
Sorry I'm so new I'm not sure I can really answer this question. My goal here is to create a synthetic image dataset so I just need the cucumber to "look" peeled and have transparent objects that cover the peeled areas. The transparent objects are necessary so that I can label those regions as peeled. Nothing about this needs to behave realistically or collide with objects
Sounds like you could even do it with one mesh that has 2 submeshes
Each submesh can have its own material
They share the vertices, but have different triangle arrays
An alternative is to use vertex colors for the peeled areas, and change the texture in a shader depending on the vertex color. But that requires some shader knowledge
I don't suppose there's an easy way to make overflow from a Layout Group flow into a new containing gameobject, is there? A boy can dream, alas ๐
I'm using unity's spline and I'm wondering how to move a game object along a spline
Would be the simplest way
Otherwise you grab a curve and call Evaluate on it to do custom interpolation
any documentation on this?
temp = velocity[index];
temp += Allign(transform, index);
temp += Cohesion(transform, index);
temp += Seperation(transform, index);
//rb.velocity += PathFollowing();
temp -= Vector2.one * deltaTime;
//temp = Vector2.ClampMagnitude(temp, 5 * maxSpeed[index]);
SteerTowards(temp, transform, index);
returnVec[index] = temp;
}```
I need some help with my code as I cant seem to figure out why the variable Vector2 temp is assigned as NaN, NaN or stuck as 0,0
**Important** this uses the unity Jobs system
How do I find every child and child's children, the whole hierarchy of one GameObject, and unparent everything under it?
you could recursively iterate over the transform and call SetParent(null) on all of them
That's what I'd like to do.
I'm just having a bit of a hard time figuring out the actual things I need to do.
I have the logic, but not enough knowledge of Unity's library.
well you can foreach over a transform to get its children, do that recursively for each child and the loop will traverse its way down the hierarchy
๐ค
for example, this is an extension method i wrote to change the layer of all child objects for a GameObject:
public static void SetLayerRecursively(this GameObject obj, int layer)
{
obj.layer = layer;
foreach (Transform child in obj.transform)
{
child.gameObject.SetLayerRecursively(layer);
}
}
I see.
so you could do something like that, iterate over the transform in a method and recursively call that method on all the children while assigning a null parent to each one along the way
I was calling this sort of stuff within another function, but it makes a lot more sense to just wrap it in its own function and call the one function in the original function.
Makes a lot of sense now...
Thanks. ๐
I'll try it out!
Does anyone know why I always get these errors whenever I install URP on my project or use the 3D URP template? I'm using Unity 2021.3.14f1 LTS
Try updating/downgrading shader graph via the package manager
How do I set up a website that can use UnityWebRequestโs POST
There are no other versions apart from the current one though
Slight update... mine only went down by about two layers before ultimately giving up, until I moved the recursive call to be the first thing that happens within the foreach loop.
Thank you for your help. ๐
Alright, new question...
... is there a way I can apply random rotational velocity to an object?
AddTorque?
I found modifying the Rigidbody component's angularVelocity variable worked just fine.
Also, I found out there is such a thing as an angularVelocity variable. ๐
Thanks tho.
there are differences between using the Add methods vs setting the velocity directly
googling "setting velocity directly vs addforce unity" will give you some results
linear velocity to AddForce is the same as angular velocity to AddTorque
GL with that
anyone know why my camera won't go closer to the player even if it is through a wall?
https://hastebin.com/pedokimemu.csharp
and yes my layers are set
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
What is the expected outcome
fixed it nevermind
Plane gets reset to XYZ 0
This is a #archived-networking question.
ok thx
i got an empty game object with 4 objects placed around it at X -90, 90, 180, and -180. my problem is that the first click works but any click after shows the wrong item does anyone know what im doing wrong here
using UnityEngine;
public class RotateY : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
Debug.Log(hit.transform.gameObject.name);
if (hit.collider.gameObject.CompareTag("Item"))
{
transform.LookAt(hit.collider.gameObject.transform);
}
}
}
}
}
When you rotate a parent with transform.LookAt every child will rotate with it. So the whole setup changes when you run this code once.
yeah i had a feeling this was the issue.
do you know what a better method of rotating the parent GameObject based on which object i click? or would i have to move the camera itself?
Not really without knowing what your use case is.
You could make the lookat targets not children, and just set the position in LateUpdate to the correct spot near the empty game object for example.
You could also reset the positions of the children objects to the correct ones after rotating.
And a lot of other things... No idea which is best for your use case.
okay! thank you! i appreciate the help! i'm not to sure what i need either for my case but i think i can work with the second opinion and the information i have now.
im doing a project where i have to replicate wordle but add drag and drop to the tiles
and im stuck because im not able to achieve replace (where u take a block and place it on top of a slot thiat is occupied and the tile in the slot goes to its original position and the new tile snaps into place) im using drop handler for drag and drop
can someone help me figiure out how to do it
i can send project file if u want
pls help
I think it'll help if you separate the data and the view
Dont think of it as swapping the physical blocks, think of it as applying a new data onto a block, and refreshing the visuals of the block
hey, im having an issue when making a load game function, where my data loads in before the scene changes any clues how I could try and fix it?
Is there anyting built in in to obtain all substrings between specific braces.
For example Example {0} {test} {lul}
From this I need to obtain string[] {"0", "test", "lul"} as result
they're already variables ๐ค
no, I only have string
and I need to obtain those substrings
Yes, you can if you assign the interpolated string to FormattableString instead of string:
FormattableString formattableString = $"Example {0} {test} {lul}";
I don't own the source string instantiation
I only have string
but
I think I already figured a solution
it's a bit nasty
but no allocations at least
So I misunderstood, it's not an interpolated string, it just happens to look like one?
yeah
I am later doing interpolation myself, but I need to obtain keys properly
https://dotnetfiddle.net/JYeDt1 but with less linq
Yeah, this works
public static string[] GetFormatKeys(string str)
{
var count = 0;
foreach (var chr in str)
{
if (chr is '{') count++;
}
if (count > 0)
{
var resultInd = 0;
var result = new string[count];
for (var i = 0; i < str.Length; i++)
{
var chr = str[i];
if (chr is '{')
{
i++;
var substr = str[i..];
var ind = substr.IndexOf('}');
result[resultInd] = substr[..ind];
resultInd++;
i += ind;
}
}
return result;
}
return null;
}
but a bit nasty looking ๐
hello, please dont DM people from the server to ask for help. it's against the rules. If you want help, you can get it here
ok sorry
I was trying to build my project but I got this error:1 exception was raised by workers. I researched a lot but couldn't find a solution to it. Here is the full error:
I googled "Duplicate class com.unity3d.ads.BuildConfig found in modules jetified-UnityAds-runtime.jar"
and the first result has [SOLVED] in its title. check it out
okay...
Is it weird that Iโll be playing a game and Iโll see an npc walking or something and Iโll get excited cuz I know exactly who write a line of code that
I think I understand my problem, but couldn't figure out a solution. The problem is I have multiple SDK's for ads. I only want to use Unity Ads, not mediation admob etc. How can I do that?
i dont know, did you try any of the suggested solutions in the thread
public class PlayerListInv
{
public List<Items> ArmorList { get; private set; }
public List<Items> WeaponList { get; private set; }
public List<Items> JewelryList { get; private set; }
//Helmet, Armor, Weapon, Jewelry
public Dictionary<ItemType, Items> EquippedList { get; private set; }```
If I send this to a JSON (Items are able to be serialized) everything will be saved except the dictionary right?
wanna make sure that having a dictionary doesn't just cause nothing to save lol
why wouldnt the dictionary be saved?
cause json doesn't save dictionaries ๐ฆ
If you use the Unity json serialiser it doesnt
hey everyone, I have a very strange issue, vsync is making lag in the game so I deactivated vsync from every single place possible, however after 5-10 minutes of gameplay while profiling the game, i noticed vsync turning on by itself for a few seconds making an insane lag and then turning it self off and then game runs as normal, what is going on?
how do you use that?
public void SaveInv()
{
PlayerListInv test = new();
json = JsonUtility.ToJson(test);
File.WriteAllText(path, json);
}
this is what I have rn
ask in #๐ปโunity-talk. doesnt seem like a code issue
(you are right, I have no clue how to use newtonsoft json tho)
then please look that up
how to add newtonsoft json to your unity project
thanks , will try there
oh its not already built in?
guess that would be part of the issue lasttime
and refrain from such obnoxious emotes
i like them
I see why I never added it
I can find how to add to project
but can't find anything about how to actually use it
"how to use newtonsoft.json in unity" has 0 useful results on googles first page
Newtonsoft.Json (Json.NET) 10.0.3, 11.0.2, 12.0.3, & 13.0.1 for Unity IL2CPP builds, available via Unity Package Manager - GitHub - jilleJr/Newtonsoft.Json-for-Unity: Newtonsoft.Json (Json....
really
Installing the package
just because you dont get it, doesnt mean they're not useful
thats for installing the package, not how to use it once its installed no?
in that link
and look what this link has
documentation
try that
yeah it was a third party thing that was.. absorbed in
I think newer versions have it in the unity package manager, not sure
but it's a much better json serializer
I assume I should be using the top one and not the bottom one?
not sure why Unity has one if I have to grab it from package manager to use
i'm not sure either, top one should be fine
public struct Timer
{
public float Duration, TimeStamp, Speed;
public Action onTick, onFinish;
public bool DeltaOrFixed;
public Timer(float duration, float timeStamp, float speed = 1f, bool deltaOrFixed = true)
{
Duration = duration;
TimeStamp = timeStamp;
onFinish = null;
onTick = null;
Speed = speed;
DeltaOrFixed = deltaOrFixed;
}
public void Tick()
{
if (TimeStamp < Duration)
{
TimeStamp = DeltaOrFixed ? TimeStamp + Time.deltaTime : TimeStamp + Time.fixedDeltaTime;
onTick?.Invoke();
}
else
{
TimeStamp = Duration;
onFinish?.Invoke();
}
}
}```
I've been thinking about making a timer because I'm too tired of always writing the same variables, I worry about the action invoke's performance though
Invoke() will probably hit it hard
have you looked into coroutines?
not sure they would apply here but those are great for "timers"
I've heard about them generating garbage so I didn't check them
how do I add an API key to this?
public static class ApiHelper
{
public static Root GetDefinition()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://wordsapiv1.p.mashape.com/words/hello/definitions");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string json = reader.ReadToEnd();
return JsonConvert.DeserializeObject<Root>(json);
}
}```
ahh looks nice
thank you
yeah np
I had no idea about that so gunna go change my coroutines now too ๐
hey, quick question.
{
float lowestPoint = transform.position.y - birdscript.heightOffset;
float highestPoint = transform.position.y + birdscript.heightOffset;
int QueueLength = 2;
Queue<Pipe> pipeQueue = new();
Pipe newPipe = Instantiate(pipe, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
pipeQueue.Enqueue(newPipe);
while (pipeQueue.Count > QueueLength) pipeQueue.Dequeue();```
it puts a namespace not found error on the Pipe, how can i modify this code so i dont have to create new classes and whatnot?
does pipe exist rn?
technically the Pipe doesnt, and im trying to bypass that somehow to make this code as simple as possible if you know what i mean by that
could just declare the other class at the bottom of the script
ex of my offers SO
using NaughtyAttributes;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
[CreateAssetMenu(menuName = "Offers")]
public class LimitedTimeOffer : ScriptableObject
{
public OfferIconTrees iconTrees;
public List<OfferData> limitedOffers;
public List<OfferData> dailyOffers;
public List<OfferData> weeklyOffers;
public List<OfferData> monthlyOffers;
public List<OfferData> hollidayOffers;
public List<SpecialOfferData> specialOffers;
}
[Serializable]
public class OfferData
{
public string offerText;
public int numAvailable;
public float price;
//public bool showInt;
//[ShowIf("showInt")]
//[AllowNesting]
public float initialPrice;
public List<OfferIcon> offerIcons;
}
//limted offer extends offerdata
[Serializable]
public class SpecialOfferData
{
public string offerName;
public Sprite backgroundImage;
public SpecialOfferTypes specialOfferType;
}
3 small classes in one file
yea i have done that but for some reason then it starts erroring the whole instantiate
its my first time making queues so yea lmao
float test = fireCooldown - 0.15f;
how would I make it so test auto-changes whenever fireCooldown changes?
you could make test a property with a getter based on fireCooldown
look into C# properties
really useful stuff
it's like a variable, but with customised behaviour when you get or set their values
so there isn't some sort of super easy way to do it like this?
float test = ref fireCooldown - 0.15f;
was hoping I was just doing it wrong lol
properties are easy
public float fireCooldown { get => _fireCooldown; }
set {
_fireCooldown = value;
test = _fireCooldown;
}
}
you know that's a property, right?
yeah, just haven't messed with them enough to have understood how to do it...so not a "super easy way" like I wanted
but that kind of seems simple to understand thanks ๐
haha okay
i changed the code a little and it still doesnt work, so i have a question on the oher hand. do i even need that with vector3 center = vector3.lerp(pipe, pipe, 0.5f
please learn some basics, Stephen. you're wasting everyone's time. including yours
there are plenty of resources on Unity Learn. there's the roll a ball tutorial, and beginner scripting course
What most use are variables
public Sprite sprite;
A property allows versatility
This can be got and set by anyone calling the script
public Sprite sprite { get; set; }
This one can be got by any other script but only set privately
public Sprite sprite { get; private set; }
i told you i dont wonna do that thing
and dont get me wrong
init is new to me, wow
i want to learn
doesnt seem like it
I have to admit I've not tried init in unity, I generally develop other languages
ah cool thanks
what i dont want to do is go with the whole "your doing something in practice for the first time so clearly you need to read c# tutorial for the 20th time"
yeah I have used getters/setters like that
but never actually setting anything like this with more code inside the getter/setter
listen i understand and i trurely respect that you want to help but realistically what your doing is making me and likely other ppl reluctant, or even scared to ask about anything
Yeah just checked, init not available with unity.
so just please dont do that
that kinda beats the point of this server in the first place
what I have a problem with, is you're not open to accepting that you're going way too far into something without understanding what's going on. When shown a possible solution, you go "let's just not do that". So you're ignoring help.
Again, it's extremely difficult to help someone write an essay, when they refuse to learn the alphabet
you're going at this in a needlessly difficult fashion for everyone involved
List<Items> tmpList = new();
switch (item.iType)
{
case ItemType.Weapon:
tmpList = WeaponList;
break;
case ItemType.Armor:
tmpList = ArmorList;
break;
case ItemType.Jewelry:
tmpList = JewelryList;
break;
}
tmpList.Add(EquippedList[type]);
will this be adding to the "correct list" each time? not 100% sure its passing the Weapon/Armor/Jewelry List as a reference
it'll add to WeaponList if itemType is weapon, yes
List is a reference type
awesome thanks!
I was like 90% sure, but never actually done anything by reference like that before ๐
it's only going to be a separate List if you did tmpList = new List<Items>(WeaponList);
something like that. just typed that roughly
sweet thanks ๐
im not ignoring the help, im just trying not to get demotivated. i really am asking for help here only if i really need it. im not making a super game im gonna do god knows what with, im trying to make my floppy bird with as much stuff as i can, so i can learn and easly remember (end eventually look back if needed) as much as i can.so if someone would just tell me how to do that, i would know next time. again, i do apprecieate the help, but what i do not apprecieate is sending me to c# tutorial every time i ask for something, even if its not, as in this case, so basic
it is.. really basic
so basic this shouldnt be in #archived-code-general
You are trying to use the type Pipe
but Pipe does not exist
so declare a type called Pipe. seems like it's a class
and if you dont know what a class is, https://learn.unity.com/tutorial/classes-5
i do know what a class is
ive done that and it started erroring out a whole instantiate line
then how about you show that error?
and also ive watched all those unity tutorials + ive spent couple hours doing the whole w3schools c# course
i'm too frustrated now, i'll leave you alone
okay have a good day
maybe im missing it...why even make a queue
yea i actually simplified it a little tho it still doesnt work, now the code is just
pipespawnscript secondmostrecent;
float lowestPoint = transform.position.y - birdscript.heightOffset;
float highestPoint = transform.position.y + birdscript.heightOffset;
pipespawnscript newPipe Instantiate(pipe, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
secondmostrecent = mostrecent;
mostrecent = newPipe; ```
basically what im trying to do is spawn the powerup right between two pipes
im using this do set the center to spawn the powerup in, but it doesnt work at all
you basically got to define a pipe somewhere or stop using the keyword ๐
so i thought, that maybe its just not taking the pipes its supposed to
so basically this whole thing is just my attempt to set pipe a, pipe b lmao
pipespawnscript newPipe Instantiate(pipe, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
how do you have this line in your code without your IDE being lit up with red squiggles?
Hello, is this an appropriate channel to ask about Oculus integration- specifically the Oculus Lypsync SDK? I'm hoping to find someone to answer a few questions.
i dont honestly
i also know its missing the =
made a typo
the whole thing works fine without the whole recent mostrecent thing
@tawny jewel configure IDE first :/
except for the mentioned powerup spawning whereever it feels like
i have, its updated and everything
basically did everything from #854851968446365696
you might be frustrated about being told to start with tutorials or basics, but you really are running into as many issues as you are because you haven't - you can help yourself considerably by first configuring your IDE and reading the warnings/errors you receive in your code. If that line is not showing red squiggles, it's not configured, and you're making things so much harder for yourself than they need to be
it is showing in red
and i do have multiple errors with it
Do show the error message
so start with the errors, things simple to fix yourself before showing it to other people - you already mentioned you know it's a typo, so why would you share it with other people and ask for help when it's in that state?
i realised it is after i shared it, thats how it looks now
with the errors shown
as i said i did every single thing in #854851968446365696 in vs
Most recent is unassigned as the error 1 says
And newPipe Simply doesn't exist as error 2 says
alright - this looks fine as far as configuration goes, do you understand the errors?
You can't assign unassigned variables to something else
i do... mostly, as i said i did all the tutorials, just really lacking actual expirience with doing stuff
do you suppose it will even fix my code?
i just need this to work properly
vector3 center = vector3.lerp(pipe, pipe, 0.5f
Without fixing the other errors? No
i was thinking about calculationg the position to spawn the powerup at with vector3 but then i got suggested this
hi how can i change the color of an prefab image
welp i ment without the whole mostrecent secondmostrecent thing, just instantiate pipe line
Gameobject.color = new Vector4
thats how it was at start, then i feel like i got lost trying to make that work
ok i made a system that whenever the game starts the prefab gets cloned to the amount of times i said it to i want it when ever i touch an object it changes the color of these cloned images
generally speaking learning isn't about just being told what to do and copying it, I'd suggest going back to basics and thinking about the problem yourself from the start
Two questions to start with, so you can approach the problem with a solution by yourself:
How do you spawn an object?
How do you position an object?
build up what you're trying to do piece by piece- another important question:
How do you get the position of an object?
Then change the object collor whenever your condition to touch it happens
can you explain more pleasae?
OnCollision or whatever you are using
welp i am trying best i can to analise every line of code i dont specifically type myself and dont go any further until i understand it
but they are clones
i will look through tutorials again though
clones are basically a new individual objects
if you change the color of a single clone, the other clones dont care
i want to change the color of there prefab
how do i do that
when ever the player touchs something
dm me
if you're reading other peoples code and "understanding" it, but you aren't sure how to answer the question of "How do I position an object?", you're not really understanding it
learning is not the process of just copying and nodding your head in agreement to a tutorial - try watching a tutorial all the way through, then closing the tutorial completely and writing the code again just from your memory and understanding of the logic involved
if you can't do that and get stuck without making any significant progress, you may want to start on simpler tutorials until you can
it sounds to me like you're missing the absolute fundamentals of both C# and Unity here, and copying tutorials without understanding is going to be a struggle to get anywhere meaningful
it's not the help you want, but it is the advice you need
@tawny jewel I'll tell the fix of what I do know but yeah you need to look at tutorials or break your problem in multiple steps
Like "how to instantiate an object" then learn "how to use instantiated object" etc
As for mostRecent, you need to give it some value to use it
And check spelling of newPipe, or need to create a variable named newPipe (and assign value) to solve that error
alright, ill just try to go though tutorials again, learn something more. thanks for help yaal
public void UnEquip(Items item)
{
List<Items> tmpList = FindList(item);
foreach (var items in EquippedList)
{
if(items.Value == item)
{
EquippedList[items.Key] == null;
}
}
what am I doing wrong here?
if the value of the dict = item
I want to set that dict value back to null
==?
๐ญ
thanks
no clue how I kept overlooking that and quick fixes didn't catch it lol
Is your IDE configured?
Your IDE should shout at you for doing something like that
#โ๏ธโeditor-extensions probably?
yeah it was throwing errors
Thanks i will ask it over there
but the quick fix solutions weren't actually solutions
I mean this error should say enough tbf
doesnt tell me enough since I barely understand what it means ๐ญ
a statement can only be an assignment:
x = y;
a call:
SomeFunc();
increment/decrement:
x++; x--;
await:
await something;
or new object expression:
new MyClass();
if your line of code is not any of those, it's not legal.
that makes sense thanks!
x == y; is just a naked expression (returning bool). It doesn't fit into any of those categories, so it's not legal.
bool b = x == y; < this is now legal because it's an assignment
I'm surprised I can't find something like this on vertx's site
maybe worth a new page
Probably yeah
what site is that?
ah cool thanks!
if I have a SO called ItemsList from a script called ItemsList is that fine?
I know a lot of the time you shouldn't duplicate names so wasn't sure
If you mean just the asset SO in the files having the same name as the code behind it, yeah that's fine
sounds good thanks!
yeah like this
Yeah that's fine
I like to have a folder for SO's separate though but that's preference
What you can do to clarify that it is an SO is just do SOItemsList
But it's not needed
public class ItemsList : ScriptableObject
{
[Header("---Armor---")]
public List<ItemReqs> CommonArmor;
public List<ItemReqs> RareArmor;
public List<ItemReqs> EpicArmor;
public List<ItemReqs> LegendaryArmor;
public List<ItemReqs> MythicArmor;
}```
public ItemsList myitems;
public void ExampleInvAdd()
{
foreach (var item in myitems)
{
}
}```
little confused how this doesn't work
do I need to make the SO an instance or something?
figured I could do a foreach for each List inside my SO
scriptable objects live as a asset
https://docs.unity3d.com/ScriptReference/CreateAssetMenuAttribute.html
would use that on the ItemsList class so its lets you create them from the add asset menu in unity
then in your 2nd script you click and drag in the reference
sorry forgot to show this...already have this line also [CreateAssetMenu(menuName = "ItemList")]
so should be able to create said assets in the project view
then after that you can click and drag them into public or serialized fields like prefabs
also you are trying to loop the asset
the asset is not a list, it contains lists
foreach (var item in myitems.CommonArmor)
gotcha thanks
so is there a way to loop through all lists?
or do I need a foreach for each list?
no, if you wanted to do that would have a list of lists
if you want to loop all of them
and each list contains the same type, why not just have 1 list
then in ItemReqs have a enum value or something that defines if its Common or rare or what ever
figured it was easier to manage if I had a list for each rarity
[Header("---Armor---")]
public List<ItemReqs> CommonArmor;
public List<ItemReqs> RareArmor;
public List<ItemReqs> EpicArmor;
public List<ItemReqs> LegendaryArmor;
public List<ItemReqs> MythicArmor;
[Header("---Weapons---")]
public List<ItemReqs> CommonWeapon;
public List<ItemReqs> RareWeapon;
public List<ItemReqs> EpicWeapon;
public List<ItemReqs> LegendaryWeapon;
public List<ItemReqs> MythicWeapon;
[Header("---Accessories---")]
public List<ItemReqs> CommonAccessory;
public List<ItemReqs> RareAccessory;
public List<ItemReqs> EpicAccessory;
public List<ItemReqs> LegendaryAccessory;
public List<ItemReqs> MythicAccessory;
you could make a enumerable that loops all of them for you
you would just need to keep it up to date as you add new lists
Is there any way to add to the duration of a coroutine?
out here runnin on fuuummemessss but is there any way to add a coroutine to an array, and switchup the waitforseconds in the coroutine?
public IEnumerator ApplyPotionEffect(PotionEffect potionEffect, float multiplier, float duration){
switch (potionEffect){
case PotionEffect.Armour: {armourMultiplier = multiplier; break;}
case PotionEffect.Speed: {speedMultiplier = multiplier; break;}
case PotionEffect.AD: {attackDamageMultiplier = multiplier; break;}
}
yield return new WaitForSeconds(duration);
switch (potionEffect){
case PotionEffect.Armour: {armourMultiplier = baseArmourMultiplier; break;}
case PotionEffect.Speed: {speedMultiplier = baseSpeedMultiplier; break;}
case PotionEffect.AD: {attackDamageMultiplier = baseAttackDamageMultiplier; break;}
}
}
public void ExtendPotionEffect(PotionEffect potionEffect, float duration){
}
public bool IsEffectActive(PotionEffect potionEffect){
switch (potionEffect){
case PotionEffect.Armour: {return armourMultiplier == baseArmourMultiplier;}
case PotionEffect.Speed: {return speedMultiplier == baseSpeedMultiplier;}
case PotionEffect.AD: {return attackDamageMultiplier == baseAttackDamageMultiplier;}
}
return false;
}```
have it pull the duration from another source
like a member variable or some data in a collection
and change that source
public List<List<ItemReqs>> Armor
{
public List<ItemReqs> CommonArmor;
public List<ItemReqs> RareArmor;
public List<ItemReqs> EpicArmor;
public List<ItemReqs> LegendaryArmor;
public List<ItemReqs> MythicArmor;
};
throwing lots of errors for this
that is not valid syntax
right
but but mess ;-;
lol ill do that dankee!!!
can't find how to declare public lists inside a list
you can't do this
you can only use public for class/struct members
this doesn't make sense
side note, any way to get the time elapsed? or shall i just start a timer when the coroutine starts?
what are you actually trying to do here
Make a serializable class of lists and make a list of that class
if you really want to keep indvidual lists you could do something like this
public IEnumerable<ItemReqs> IterateItems() {
foreach (var item in myitems.CommonArmor) {
yield return item;
}
foreach (var item in myitems.RareArmor) {
yield return item;
}
// ...
}
then calling that would return you a object that loops over all of the lists for you
trying to make it so I could use a foreach loop to iterate over all my armor lists without having to make 5 foreach loops to do all 5 armor rarities
foreach (var item in myitems.IterateItems())
Could also implement IEnumerable on the SO directly - then the original calling code would work.
how would that look?
sweet thanks ๐
so doing it this way would just iterate over each item in every list?
I think a cleaner way to do this is:
return CommonArmor.Concat(RareArmor).Concat(...)... etc..```
and not just return the 5 lists to then do foreach on?
see the function i wrote before
this one yeah
can also Concat if doing it that way so nothing is coppied
yeah sorry was literally editing my post for that as you said it ๐
public IEnumerable<ItemReqs> IterateItems()
{
return CommonArmor.Concat(RareArmor).Concat(EpicArmor).Concat(LegendaryArmor).Concat(MythicArmor);
}
like such...and this would just return every item for the foreach right?
fair enough ๐
but yeah that when you loop over it, would loop over everything you concated in
When I try to build for Android or Addressables I get these errors: error CS0103: The name 'LoadingManager' does not exist in the current context, but it all works fine in playmode.
Usage examples:
LoadingManager.Instance.SetLoading(false);
LoadingManager.Instance.SetLoadingLog($"Ping: {(time - startTime) * 100:###}ms");
The complete "LoadingManager" script: https://pastebin.com/pN3NG107
What can it be?
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.
What @quaint rock gave you, but with your type implementing IEnumerable<ItemReqs> and its function IEnumerable<ItemReqs>.GetEnumerator () => IterateItems ().GetEnumerator ();
also keep in mind with the Concat and the yield methods you are not getting a list back, the Enumerable it returns is mostly only good for using in a foreach loop or with linq
sounds good thanks!
Im only using this for testing so getting back every armor and every weapon an item at a time works great ๐
its still doing more or less the same thing as manually running the loops for each list back to back. just hidden away in a function
I made changes to my SO and my VS didn't pick up the changes
