#archived-code-advanced
1 messages ยท Page 138 of 1
imo, since you're so close i wouldn't change much
but you probably should have started with something from the literature to do this
meshing a grid of points
vhacd is very fast - https://github.com/Unity-Technologies/VHACD
you would have to modify it for 2d
I do something similar to what he's doing with my tilemaps, and there's already a library he could use. It's available in the 2d extras somewhere, but you can copypasta it from here:
https://github.com/Unity-Technologies/2d-spriteshape-samples/blob/master/Assets/Unity Technologies/2D SpriteShape/Extras/Scripts/Clipper.cs
yeah
"a translation of the delphi clipper library"
kind of how this stuff goes
@frail dock bakecollider from here
i want to remove a property and value from a json string that makes my deserialization puke. How do I do this?
you can parse the json string into a JObject, then remove the offending property before deserializing into the final type... or you can make a custom converter that just ignores the offending type. If you can change the original type that got serialized, you can add a [JsonIgnore] property on it.
All this assumes you're using newtonsoft
I have spent all day to figure this out, yes I am using newtonsoft, its driving me mad
JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TokelToken]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
seems like you are trying to deserialize an object into an array or vice versa
can you show the source json and target property?
its like nested
sure
so, I am grabbing from this endpoint (no worries, its all public data)
https://explorer.komodoplatform.com:10000/tokel/api/tokens?cctxid=bb69cc6d5a16b459f8b3c4c83e74f619b212830adfa331c051694e3604710146
in Unity
Tokels mytokeltoken = JsonConvert.DeserializeObject<Tokels>(getTokenData.downloadHandler.text);
Debug.Log(mytokeltoken.tokens[0]);
here are my classes
[System.Serializable]
public class Tokels
{
public List<TokelToken> tokens;
}
[System.Serializable]
public class TokelToken
{
public string tokenid;
public string owner;
public string name;
public int supply;
public string description;
public TokelData data;
public int version;
public string IsMixed;
public int height;
public string ownerAddress;
public int blocktime;
public string blockheight;
public int syncedHeight;
}
[System.Serializable]
public class TokelData
{
public string raw;
public TokelDataDecoded decoded;
}
[System.Serializable]
public class TokelDataDecoded
{
public int id;
public string url;
public int royalty;
public string arbitrary;
}
@compact ingot
The JSON needs Tokels to be this: ```
[System.Serializable]
public class Tokels
{
public TokelToken tokens;
}
And deserialize multiple Tokels, if needed, into a List<Tokels>.... but mind you that the root of the json source you linked is a dictionary/object, and not an array!
:S
Hey I am using a new Input System and for some reason if I am going right or left I can't overweight the right and left with up or down buttons, could anyone guess what am I doing wrong?
@compact ingot I don't understand how to fix it
because a part of it works, except the data property
@compact ingot
IEnumerator FetchAndUpdateTokens()
{
UnityWebRequest alltokens = UnityWebRequest.Get("https://explorer.komodoplatform.com:10000/tokel/api/tokens");
yield return alltokens.SendWebRequest();
if (alltokens.result != UnityWebRequest.Result.Success)
{
Debug.Log(alltokens.error);
yield return null;
}
Tokels tokeltokens = JsonConvert.DeserializeObject<Tokels>(alltokens.downloadHandler.text);
for(int t = 0; t < tokeltokens.tokens.Count; t++)
{
if(tokeltokens.tokens[t].ownerAddress == myTokelAddress)
{
if(!mytokens.ContainsKey(tokeltokens.tokens[t].tokenid))
{
Debug.Log("current tokenid: " + tokeltokens.tokens[t].tokenid);
UnityWebRequest getTokenData = UnityWebRequest.Get("https://explorer.komodoplatform.com:10000/tokel/api/tokens?cctxid=" + tokeltokens.tokens[t].tokenid);
yield return getTokenData.SendWebRequest();
Debug.Log("fetched: " + getTokenData.downloadHandler.text);
// HERE I GET THE ERROR
Tokels mytokeltoken = JsonConvert.DeserializeObject<Tokels>(getTokenData.downloadHandler.text);
Debug.Log(mytokeltoken.tokens[0]);
}
}
}
@compact ingot
fetched: {"tokens":{"tokenid":"bb69cc6d5a16b459f8b3c4c83e74f619b212830adfa331c051694e3604710146","owner":"03353ec0e845ab678e8efaa3f50e96163da0eb....
first endpoint returns an array, second an object
JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TokelToken]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
...
Path 'tokens.tokenid', line 1, position 21.
but you deserialize into the same type... that cant work
so I need to create a different one for the next object?
second one needs the edit i showed you
first one works with what you had
best just make the edit i suggested and deserialize the first one into a List<Tokels> variable
@compact ingot got it working thanks!
lol! damn where were you two months ago before I started writing all this mess? ๐
ty mate this seems like something i could use
yeah, has to be cause it's only one thread so it should be all executing one after the other, funny thing is i tried drawing the exact shape what i did when i was going slow and that works, but if i try the exact thing fast it bugs out instantly
it's baffling me
so i think i found the issue
i set it out to print the order of execution
it goes
BUTTON EXECUTE
START METHOD
START PATH
but for some reason button execute is called twice when i draw fast at some point
if (Input.GetMouseButton(0)) {
if (finX >= 0 && finY >= 0) {
// print("PLACE " + wp.x +" "+ wp.y);
if (tScript.chunks[(finX - finX % blockSize) / blockSize, (finY - finY % blockSize) / blockSize][finX % blockSize, finY % blockSize].type != 2) {
print("BUTTON EXECUTE");
tScript.chunks[(finX - finX % blockSize) / blockSize,(finY - finY % blockSize) / blockSize][finX % blockSize, finY % blockSize].type = 2;
// tScript.squareX = finX;
// tScript.squareY = finY;
tScript.squareX2 = finX % blockSize;
tScript.squareY2 = finY % blockSize;
tScript.chunkX = (finX - finX % blockSize) / blockSize;
tScript.chunkY = (finY - finY % blockSize) / blockSize;
tScript.squareType = 2;
tScript.update=true;
}
}
}
how could this execute twice before finishing the rest of it? ๐ค
unless that boolean i'm flipping is messing with it somehow
Check the callstack of each message
Also maybe use GetMouseButtonUp/Down. So that it's not executed twice if you hold it for 2 frames somehow.
is there any directions where I can look at for having place nodes automaticly in a grid like webbing?
I ment like having a nodes automaticly connect when placed on the scene
hmm, so i had a bunch of booleans i was flipping to trigger each other, i put them all in a single boolean update flip and that seems to have reduced it but it still seems to trigged if i leave print outs there and execution takes too long ๐ค
you mean flip a boolean on up/down?
No, I mean use GetMouseButtonUp instead of GetMouseButton
how can that work? i want to draw all the time while mouse button is pressed
Aaah
Okay
Then maybe you have 2 instances of the script in the scene?
Add this as the second parameter of the debug.log and see if it points to a different object.
no that can't be it, i only have one map object with one script attached to it
strange, i can't seem to trigger it now even with the prinouts
this is gonna haunt me knowing the possibility is there ๐ฅฒ
fixed! i just added a boolean to not trigger if the other code isn't finished ๐
it's so fast i can make my player into a rocket by placing blocks now ๐
fresh
Does anyone have any best practices or strategies for managing transitions between scenes, like going from a lobby to a match? Seems like there is a lot of info out there on potential ways to solve this, but I'm curious if any have been found to be lacking once a project gets to certain complexity.
Good morning all.
I have a need to search for specific fields within a class, retrieve its value (to compare it against another value).
Its a function within the AI that runs when it decides what skills to use in any given situation. The skills on each mob can vary, and so can the conditions set for those skills.
The conditions can be both int values like strength, intelligence, HP, mana but also bools like isKnockedDown or isFloating.
public class MobData : MonoBehaviour, InterfacePersonality, InterfaceDamage
{
public Mob thisMob = new Mob ();
}
//THIS IS THE CLASS I NEED TO RETRIEVE A VALUE FROM
public class Mob
{
public int health;
public int walkSpeed;
public int runSpeed;
public int jumpForce;
public int baseAttackValue;
public int attackAccuracy;
public int attackPhysicalAttackPower;
public int attackMagicalAttackPower;
public int atackArmorPenetration;
public int attackCriticalChanceValue;
public int baseDefenseValue;
public int defenseEvasion;
public int defensePhysicalDefenseValue;
public int defenseMagicalDefenseValue;
public int defenseDamageReduction;
public int Intelligence;
public int Bravery;
public int Authority;
}
======================================
private bool CheckConditions(ScriptableMobSkill mobSkillData, StateController controller, PlayerCharacter targetCharacter)
{
foreach (var condition in mobSkillData.SelfConditions)//SEE CLASS BELOW
{
//HOW TO RUN THROUGH EACH TRAIT, RETRIEVE THE FIELD AND THE VALUE IN THAT FIELD THAT CORRESPONDS TO THE TRAIT?
}
}
===================================
public class MobSkillCondition //this is used as an array in an scriptable object (Public MobSkillCondition[] SelfConditions)
{
public string CharacterTrait;
public int CharacterTraitValue;
}
If I understood this correctly just add them to a list
Wait, that won't be necessary, I just saw the Mob class
let say one of the conditions read
CharacterTrait baseDefenseValue
CharacterTraitValue 5
In the for each loop, I need to run through and retrieve the field "baseDefenseValue" at controller.thismob and then compare the values to know if it should return true or false
was thinking of using controller.thismob.getfield() ? but someone warned against using reflection at runtime?
I'm trying to think of an optimal way to handle this other than the obvious way of just checking trait by trait like:
...
else if(characterTrait == "baseDefenseValue")
{
return baseDefenseValue "condition" CharacterTraitValue;
}
...
indeed, thats why I am here. Cause I want to do the same with the PlayerClass, and it contains more like 40 different values that it should be checked against xD
Interesting, now I want to see the solution to this too. I'm not sure how I would do it.
think I got it
private void CheckConditions(ScriptableMobSkill mobSkillData, StateController controller, PlayerCharacter targetCharacter)
{
MobData mobData = controller.gameObject.GetComponent<MobData> ();
foreach (var condition in mobSkillData.SelfConditions)
{
int retrievedValue = GetPropertyValue<int> ( mobData.thisMob, condition.CharacterTrait.ToString () );
if (retrievedValue >= condition.CharacterTraitValue)
{
Debug.Log ( "retrievedValue for condition " + condition.CharacterTrait + " " + retrievedValue );
}
}
}
public static T GetPropertyValue<T> ( ClassData.Mob mobData, string propName )
{
Debug.Log ( propName );
var type = mobData.GetType();
Debug.Log ( type.ToString() );
var field = type.GetField ( propName );
Debug.Log ( field.Name );
var valu = field.GetValue (mobData );
Debug.Log ( valu.ToString () );
return (T)mobData.GetType ().GetField ( propName ).GetValue ( mobData );
}
}
all the debugs can and will be removed, that was for me understanding how it worked.
rule of thumb: reflection is about 100 times slower than idiomatic methods. if you "need" reflection outside compilation/code-ceneration/init/serialization/build-scripting/optimization you need an architecture change... reflection is like replacing C# with the safety of JavaScript and the efficiency of a python REPL
Since this is an AI thing, i'd suggest you look into the Blackboard Pattern
The Blackboard is just a shared collection/database that can contain multiple types (i.,e. your class fields), stored as anonymous object references together with their type such that getting a value from the Blackboard can be handled by a Strategy pattern, common, type-safe interface and casting instead of reflection... you can however use reflection for initializing/building the blackboard... or you can build GUI inspectors for all blackboard properties and consumers that handles the type safety at design-time with everything stored as plain objects in a dictionary. Or you can just ignore type safety and live with cast-exceptions.
If you really want to use reflection you can create value-getter delegates for each specific member when you first search for it, those are then on subsequent use much faster than using relfected member name lookup. You can combine that with the blackboard pattern.
Also relflection produces the ugliest code possible.,
hi, i have these 2 scripts https://pastebin.com/2Cdm2FNx (shader), https://pastebin.com/p4bNBkRR (mesh c#) that uses a compute shader to generate a grid mesh just as a test. I want to end up doing marching cubes on the gpu but i cant figure out why my mesh loooks like this.
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.
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.
triangle indexes are wrong
i realised lol, do you know how i could fix it?
double check your understanding of the datastructure for meshes
also mind that vertex order in a triangle matters
could also be that your vertex order is different than you assume
i.e. x/y flipped in a for loop or something like that
off by 1 error
stuff like that
ye ive done a lot of mesh systems before using the unity job system and c#. I understand the math but the exact same math i used in the shader is what i use in the job system. Im stuck on why it dosent work. and also im not seeing massive performance gains. that could be because im useing unity meshes instread of draw procedural but idk.
ill see if i can implement your advice
thanks
Thanks for your reply. Balckboard structures are a new concept for me yet, so diving right into it! thanks alot! ๐
do you think it could be a shared data issue, since you are building the tri indexes together with the calculations in separate threads? doesn't seem likely though.
could just do the pos-calc in threads and the triangles after a join... i don't see an issue in your code... maybe a rounding error between gridDetail and gridWidth?
hm, I might be missing something, but I think your indexing is wrong in some places
e.g. where you write to TriangleIndices in the shader
You write to everything from ThreadIndex to ThreadIndex + 5
But the thread for one cell over in the y direction is going to write to most of the same indices (because its index is ThreadIndex + 1)
Missing a * 6 I guess
that makes a lot of sense
yep fixed it, basically the issue was that the triangle indicies and the vertex indicies are supposed to be different. the triangle indicies corrolate to the amount of triangles that have been added while the vertex indicies are indipendednt of eachother.
๐ฅฐ concurrency bugs are the best
If you want to avoid reflection you could just do a big switch statement like this...
ref int GetField(FieldType type) {
switch (type) {
case FieldType.Attack: return ref attack;
case FieldType.Defence: return ref defence;
GetField(FieldType.Attack) += 2;
I think you can return ref in the new versions of C#
Otherwise you can do a Set/Get separately
yes, that is my backup solution. One of the classes contains up to 40 different values it could be checked against, so Id thought to try and avoid that ๐
I guess so... but passing strings around isn't great either.
The other option is to not have fields at all
And instead do this:
enum FieldType {
Attack,
Defence,
Speed
}
class Attributes {
int[] fields[Enum.GetValues<FieldType>().Length];
ref int Field(FieldType type) => ref fields[(int) type];
}
@foggy elk โ๏ธ
That way there's no duplication
You'd just always use the Field accessor instead
It might make defining inital stats a bit uglier though.
interessting approach. Would be some work restructuring parts of the code, but I am already using an Enum for the charactertraits.
You can make a custom inspector for the Attributes class
so that it shows up in the editor like a normal struct
Hard to know whether this would be a help or a hindrance without knowing exactly what you're doing with it.
But it's an option!
this might be a newbie thing, but the class I want to retrieve values from, is a class created with updated variables when you start a new "game".
and then this class are updated each time a change is made. So everything in my code that needs information on the player variables, retrieves it from this class. A bit unsure if deleting it and making an enum out of it would be wise
that switch thing aint looking so stupid anymore xD
So I have an issue with the voxel graphics where the landscapes are highly detailed and after optimization (combining cubes on the same plane etc) the resulting triangle count and vertex count is drastically reduced but still too high for oculus quest. At certain points in the game the vertex count exeedes 400k which is 4X the recommended by oculus.
The landscape is created in MagicaVoxel and imported with the MagicaVoxel Tool from the asset store that converts and optimizes the mesh. Problem is that this isn't enough. Is there a way to have highly detailed Voxel landscapes (or voxel graphics in general) where I could optimize the tris and vertex count into acceptable levels without having to let the artist reduce the detail level?
Currently landscapes come in chunks that have anywhere from between 5k-30k verts and 4k-15k tris give or take. About 12-15 chunks are visible at the same time. It seems that Voxel graphics (albeit nice looking) is very demanding performance wise.
How about a LOD system that uses lower quality meshes the farther they are from the camera?
The viewing distance is already greatly reduced to 8 units already. Wouldn't the lodding be very noticeable at that distance?
Donno. Depends on many factors. Are the voxels cubes?
Yes cubes that build the different landscapes
I can't give you any advice about the visual side of things. I don't even know how it looks like now. ๐
After importing from MagicaVoxel and using the Importer Asset that also optimizes the mesh, the tris and vert count is drastically reduced. So from the looks of things, it is as optimized as the algorithm that has been used could do it (e.g combining cubes on the same plane to create one giant cube or rectangle etc)
The issue mainly is that because the landscapes are built with voxel graphics, there is no easy way to reduce the tris and verts count without reducing the level of detail on the landscapes. Every voxel that sticks out creates an additional set of tris and verts and with a high detail level, it seems to scale exponentially.
According do my rough math, if you have around 400k vertices a worst case scenario with unoptimized meshes, it should still be around 150 meters of view distance assuming your field of view is 90 degrees.๐ค
Probably even more
One landscape module is about 3x3 units of lenght.
And how many vertices do they have?
between 5-30k
in 3 * 3 units? With cube blocks?
yes
are you kidding me?
6 vertices per face * 5 faces exposed in the worst situation * 3 * 3 = 270 at most.
How does a module like that look like?
Unless I'm misunderstanding something..?
Are the blocks smaller than 1 unit in length?
I think you are, One landscape module contains say 15k verts. The entire module is about 3x3 units in size. The landscape module is built with voxels. So it could be a small house and a bridge and say a few trees that make up one landscape module.
So the voxels are smaller than 1 unit?
Can you take an example screenshot?
Well, then there's not much you can do. It's kind of a technological limitation. And you're trying to fit it on a platform that has even more strict limitations.
It's like creating a nuclear reactor in your backyard with tools from the garage.
But maybe using lower quality blocks(increased length) for far away chunks could be a decent solution.
I cant share an actual screenshot but I can show you how a module might look like
The player is seeing like maybe 10 of these modules at most
at the same time.
This with a viewing distance of 8 units
Its a VR game
ah
So you have a birds view kinda
Then yeah. A LOD system for the meshes is the only thing I can think of. It can actually introduce a certain artistic effect imho. Where far away chunks have bigger blocks. Although, I imagine it will create more problems in terms of object placement and stuff...
Anyways, you should probably profile the game on the actual device, before making any conclusions about the performance.
I've already done that and after optimizing everything I can think of, I am getting a stable 72 fps, as long as there are not too many dynamic objects on screen at the same time. Like enemies and such that move around. At a certain point the fps could drop below 72 and get back up again. However this just shows me that I'm currently pushing it with the tris and verts count. If there was a way to reduce it or optimize the landscape to give me say 5-10% performance improvement, I could then add more enemies or more dynamic stuff in the scene.
Are you sure that the bottleneck is actually the geometry? What did you see in the profiler?
Rendering is eating most of the performance
If GPU is the bottleneck, then yeah, it's either vertex count or complex shaders.
If it's CPU, then it's not related to the geometry: probably set pass calls or draw calls.
Rendering is not 1 big thing. It has a lot of parts to it.
Its the GPU yes. Profiling with the OVR Metrics tool, the App GPU T is going above 13700 microseconds at certain points which is telling me that the gpu is bottlenecking
If you can't reduce the vertex count any more, try reducing the complexity of the shaders or making the gpu draw less objects.
I am using URP Baked Lit shaders for the landscape, and simple lit for the dynamic objects
I am trying to use GPU instancing and such to reduce the drawcalls
Static batching, Dynamic Batching etc
I've pretty much ticked every box that should improve performance afaik
Can you actually provide a screenshot of a frame from the profiler?
At this moment no
Maybe later today if I have any time left, but from what I can tell from the profiler, the framedrops happen when there are too many dynamic objects in view. But reducing them could be a solution but gameplay would suffer
Would anyone know what's up with this error? I keep getting this for no reason and the code refuses to stop
from what I can find it's something to do with a DLL, but I'm not loading any.
Would be helpful as well if it said what type failed to load.
Types i'm using in the class where the error happens (and the one it calls) are pretty normal
the error is in EnemyPathFinder line 30. What's on that line?
It's calling a static function from a static class.
Is that your script?
public static Path<Vector2Int> Solve(Maze maze, Vector2Int start, Vector2Int end, int limit = 10_000)
Yeah it is
this is the signature
Path is also a class defined in the same file
ive never in my life encountered this error
What's the deal with this:
int limit = 10_000?
ah it enters a while loop somewhere, so that is a safeguard
always do that with while loops
what's with the underscore?
I wonder if that's the problem though
removed it, but didn't help
I think there's something wack going on with the assemblies somewhere but Unity is not telling me which type is failing
What about Maze is it your class too?
yeah, that's just a struct with pure data
And Path?
Are there details to that message btw?
nope
Is there a way to encode a string into a decimal number?
@hidden locust are you using assembly definitions in your project?๐ค
no, not even
that's why im so confused
really wish it'd just give a better error message
Well, try eliminating parameters of that function and return type one by one to see which one is the culprit.
@hidden locust Also, what's the path to the Solver script and what namespace is it in?
I want to hash a string and convert the hash into a numerical value.
byte[] sha256 = Sha256Managed.ComputeHash(Encoding.UTF8.GetBytes(ID), 0, Encoding.UTF8.GetByteCount(ID));
int value = Convert.ToInt32(sha256)```
That last part doesn't work.
The path, you mean the actual directory path? It's in Assets/Scripts/Solver.cs and the namespace is QTea.MazeGeneration
It's a partial class too, but that should work right
Ah, that might be relevant.๐ค
that would be odd...
SHA-256 is 256 bits. It won't fit in a 32-bit int.
nah, that's perfectly valid. You'd get a compile error if it wasn't supported.
Yeah - I realize I've drifted apart.
I kinda want to create a checksum of a string, but it should be decimal not hexadecimal.
Checksum is usually a number.
Hexadecimal or decimal are two different string formats for displaying the number.
But it's stored in binary like anything.
If you want to wrap the checksum into 32 bits just use a modulo
@radiant wave you could also just do this: https://docs.microsoft.com/en-us/dotnet/api/system.string.gethashcode?view=net-5.0
Truncate the byte array into 4 elements and convert that, if it needs to be an int specifically
Although it's probably not a good checksum...
Great! that looks like exactly what I need
that's fine. As long as it's deterministic
Ah, it's not.
The hash code itself is not guaranteed to be stable. Hash codes for identical strings can differ across .NET implementations, across .NET versions, and across .NET platforms (such as 32-bit and 64-bit) for a single version of .NET. In some cases, they can even differ by application domain. This implies that two subsequent runs of the same program may return different hash codes.
See the "remarks" section
hi, i have been using a vertex and triangle array to generate meshes, but now that i am using compute shaders i want to know how i can use graphics.draw procedural or somthn to generate meshes straight on the gpu. i dont need collisions or nothing as its just a test. does anyone know how i can use my 2 arrays to draw a mesh?
damn!
@untold moth omg, i might've found the issue and it's all on me lol. I had a layout cycle somewhere in a struct
layout cycle?๐ค
within a struct you cannot have the same struct referencing itself
but i did that
expected the compiler would give an error about that but it didn't..
Got it, thanks for your help.
Aaah. I see. Interesting.
That makes sense. Didn't think of the implications. Although I guess unconsciously I was thinking of it as a reference.
If I have a mystery build freeze (seemingly an infinite loop), and I attach my debugger, how can I determine where it is? When I pause execution I just get a bunch of stack traces with thread handling stuff and no actual current line in my C# code. (I haven't actually tried pausing during the infinite loop yet because it takes 20 minutes, just experimenting with debugging a build for the first time)
Hey I was wondering if someone here could help me identify a pattern. I first encountered it in this video:
https://www.youtube.com/watch?v=tAbBID3N64A&t=2988s
I'm talking about their bark system. In it they call it a self branching dialog tree, but also state it can be extended to do other things.. I made my own implementation in unity, I simplified and allowed it able to run multiple states/behaviours at the same time. The behaviours can also be updated in runtime so you can add and remove behaviours dynamically. In the video they call it a self branching dialog tree so I was wondering if extending it to control behaviours would make it a self branching behaviour tree? It also resembles utility function, but the conditions are all bools rather than floats and rather than analyze all cases then compare them, it returns the 1st match. In my research I have found the Fuzzy State Machine (FuSM) which might be a fit.. I'm trying to write about the pattern, but not sure how to label it.. Thanks.
In this classic GDC 2012 session, programmer Elan Ruskin shows a simple, uniform mechanism made for the Left 4 Dead series for tracking thousands of facts and possibilities, allowing intelligent characters to remember history, cascade from special to general cases, and select the optimal dialog, script, behavior, or animation for every situation...
is there a way to make all of the objects be the same size even when theyre further from teh camera relative to another object ?
or appear to be the same size
They are the same size. If you don't want perspective, use an Orthographic camera
idk what that is
it's the "projection" setting on your game camera
change it from "perspective" to "orthographic"
looks right
they all look the same size on screen now
that's what you asked for
no , i mean i want them all to look the same size
they do...
they now look completely different , for example the white looks way smaller than the green 1
it looks exactly the same
am i blind ? XD
you might be getting confused by the outlines
I made these two 'H's the same size
well , ty man , idk why i think the red 1 looks way bigger
am asking a friend for their opinion
its a well known optical illusion
what's your objective?
to make video game dialogue?
build freeze, you mean, a freeze during the build of your project in the unity editor?
haven't watched the full video but i get a strong feeling of logic programming (i.e. prolog)... which basically takes facts and infers possible world states by constructing and solving horn clauses. That can be combined with fuzzy and other modal logic operators to create all kinds of extremely fancy symbolic AI systems... theorem provers, action planners and the like... its the brainiest branch in academic artificial intelligence research, in Uni, 80% ultimately failed that class ๐
All good. It turns out that I'd just been a silly and had an endless loop. I got it!
Hey!
I want to make a small, loop-based music creation tool in Unity. Any tips on how to visualize audio/enable on and off on a grid type system to enable/disable sounds?
can you give an example of what you're aspiring to do, and what is the smallest version of what you want to do?
Like a midi editor?
i would start by looking at the asset store ๐
I already used it for dialog and extended it for character behaviour, but I mostly I'm trying to figure out what to call it ๐ in the video they called it a self branching dialog tree..
I'm testing out development for the Hololens 2, and want to test out a loop based audio creation surface, similar to this: https://youtu.be/7Ki27CK5Je0?list=PLpyotFCx2oS9XNAFHB13V0xe7KcQzROPo&t=21
Yarr! Here you go - TWO tunes in ONE video. Grab your Octavia and use these songs when you are to farm Hydroid Prime!
I am the creator of this cover, my name in game is ShineShield
Contact me
Steam Group:
http://steamcommunity.com/groups/r666sv
VKontakte (for russian users):
https://goo.gl/ERiqQj
Facebook:
https://goo.gl/J6rnPd
Just curious where I'd start in creating something like that. Any tips at all are appreciated!
what's your experience with unity?
I'm actually learning about prolog now too ๐ but I implemented this system with abstract base classes of Acts that each have a list of Conditions, that each return a bool, and if all conditions are met the Act executes. It similar to a utility function, but a lot simplier
Medium, have done five projects in it before so I know the ins and outs.
when you say character behavior?
you mean like a screenplay?
are you familiar with Ink?
you should probably use Ink for Unity if you want to write a dialog-and-action screenplay
like a screenwriter would
you can use UGUI or Runtime UIElements to build a UI, VFX Graph to visualize things in 3D, and an audio mixer or sequencer from the asset store
@arctic robin for example https://assetstore.unity.com/packages/tools/audio/stepp-69113
Awesome, thanks! What do UGUI and VFX Graph add that base Unity doesn't have?
i'm concerned you're at "medium" and you don't know that UGUI is the name for unity UI ๐
I have finished the whole system and works well, but I really don't know who to categorize it.. the basic pattern, I made it in unity with scriptable objects, the main core of it is a loop through a list of acts that are sorted by the number of conditions, all the condition must me met for an act to be executed and acts can be run in series or parallel, which makes me think Fuzzy State Machine possibly..
Hahah whoops
so have you looked at ink?
I haven't developed in it for a couple of months tbf
have you looked at unity timeline too?
I have looked at it before. But this does a lot more than dialog it's a whole dynamic behaviour pattern, I used it as a character controller, that controls Players and Ais
I was thinking of writing an article about it, but then I'm not sure what it is called or classified as..
in the video they use have a list of dialogs that have conditions and the number of conditions is also a condition.. but I simplified this by sorting the list by the number of conditions. Then it selects the first to match all conditions using simple fuzzy pattern matching. Acts them selves are coded to run one at a time or concurrently, which fits Fuzzy State Machine(FuSM), but if it is set up to only run one at a time I'm not sure if it would still qualify as a FuSM.
What is the best tool for working on a Unity project on multiple computers?
Does Task.Run(async () => ...); called in unity use the UnitySynchronizationContext or the default one (ThreadPool) as it would in a regular .net app?
i have no idea**, but its implementation is toxic
as in "not allocation free"?
no
but?
UnitySynchronizationContext always Thread.Sleeps(1) on the main thread which has toxic behavior in unity, whereas UniTaskSynchronizationContext uses SpinLock which has better behavior (it sleeps 0 most of the time)
this is why people report really weird super slow performance with UnitySynchronizationContext
in some cases
right, was thinking there was a problem with Task.Run
i think it's because it uses unitysynchronizatoncontext
whereas UniTask.Void (a kind of run) doesn't have to
Have u tried amplify impostor?
I have around 150 different stats, and i just keep them in a dictionary with an enum StatType as key
GetStat(StatType stat) => return stats[stat]
Conditionals are done with making formula. >=1 results is true, else false
Will keep this in mind. ๐ Thanks!
Materials saving as black (default colour)
Is anyone able to help with rotating a 2d array in C++? I am doing doing a blit function on pixels on the screen, and I have reference to the original sprite sheet and when I blit it to the screen I need to be able to perform an x rotation on the sprite when copying
C++? This is the Unity Discord
haven't you heard? unity and unreal have merged now
both c++ and c# are fully supported
๐
I mean doing it in c# would be fine I just am trying to understand the theory
Of copying a 2d array to another while performing a rotation
It's really not complex. Just swizzle the indices. I can't be bothered to think about what the effects would be but output the indices differently and you'll get a rotation
e.g.:
[y, x]
[xMax - x, y]
[x, yMax - y]
[xMax - x, yMax - y]
etc
Would that be able to support all rotations or only like 90, 180. 270?
90 degree rotations
or reflections
if you want anything else you'll need to do some kind of multi-pixel sampling
it's not possible to rotate the indices of an array say 15.7 degrees bc the indices are stored in a grid formation
Right, but they are pixels so some loss is expected, the same if you rotate an image in photoshop the pixels distort a little but keep the same scale and general shape
i thought we were talking about switching indices in an array, not rotating an image
The issue I'm having is I need to rotate one matrix by n degrees when copying it into another matrix
right but if it's not a visual representation that you're rotating, it's impossible to rotate an arbitrary number of degrees bc arrays are stored in memory in grid-based rows
it gets a lot more complex if you need n degree rotation. The result won't even fit into the same dimension matrix because the diagonal rectangle will need a bigger rectangle to circumscribe it
I shouldn't be rotating the source image, only performing a rotation in the process of copying each element
i'm still confused, are we talking about an image or an array
I have an image that has been converted into a 2d array of pixels, and I need to copy that to a bigger array and perform a rotation in the process
oh i see
why don't you just copy normally then rotate the image component
why do you have to rotate the array representation of the pixels in memory
just rotate the final image
Maybe this will be helpful? https://www.sciencedirect.com/topics/computer-science/image-rotation
This rotates the source then copies, I need to copy and rotate at the same time. If you do what this article suggests, it will lose the corners because they will go outside the bounds of the array before copying
it's a starting point though
you can't do two operations at the same time, there has to be an order
also that
What I have set up is a sprite sheet, which is a 2d array of pixels, and I have a 2d array of pixels on the screen. I need to take a specific chunk of the sprite sheet, copy it to the screen while performing a rotation.
Would a solution be to cache the image I need to copy, expand the array in both dimensions and then do this rotate you linked Praetor, then copy?
what's your objective?
gameplay objective*
you can if you use concatenation
have you looked into matrix concatenation? There is a chapter on it in one of my old programming books, but you can combine many matrix operations into one operation.
The goal is that I am copying pixels over using blit. I need to be able to blit the sprite from the spritesheet with any given rotation
I got all the info from this book
I'm not too familiar with it, what is the book?
Thank you for that resource
ah good point
i'm still learning linear algebra so i forgot about that lol
it's old from the 70s, but it has all the math for combining 2d or 3d matrix operations, such as rotation, translation and scaling into one matrix operation.
I'll definitely check that book out, thank you so much for that.
what's the gameplay objective?
This is not for gameplay, its for a pixel graphic rendering engine
sorry what i meant was, for like a retrocomputing thing?
if you need to transform graphics efficiently you should use a material and the methods in Graphics
the material can rotate, flip, etc.
everything you need
using a shader
Its making this image from a console application
is this unity?
Yeah exactly
No this is console application
Does anyone happen to know a good BVH implementation? I mostly just care about built time and test time. I don't need it to support dynamic objects.
I have implemented most of one my self, but it doesn't quite work and I have looked at the code so many times and can't figure out why.
(Mine uses binning and SAH, but it will always split on the first bin for some reason)
what are some of the things you want to achieve?
have you seen https://github.com/nobnak/FastConst-SAH-BVH
i'm not sure how realtime CSG package represents geometry
which is way more general than BVH
and maybe that's interesting to you
@urban warren https://www.youtube.com/watch?v=bRkFezG-uno
I am going to make a BVH of my mesh terrain and use it to generate heightmaps.
*terrain and object meshes.
I am making a pseudo procedural vegetation placement and rendering system.
what's the big picture algorithm here
for how to use this datastructure to help you
I would use it to generate height maps for the terrain and objects(large rocks, cliffs etc) on the terrain and then use the height maps in compute shaders to generate points to place the vegetation.
how is the terrain generated?
isn't the terrain already a height map?
Manually. Mesh terrain.
got it
so spell it out for me a bit more, just so i can help you
it'll be helpful
because it sounds like you can do
- generate mesh terrain
- generate a height map by applying a shader that shows world y height at the uv coordinate
- ...
you can use a triplanar material that renders y at xyz
or use a uv projection
Ehh, no, let me explain.
at y = -1
is the terrain concave?
and you want to like, fill in concave space?
and your goal is to "voxelize" the terrain so you can sample this concave space?
you have an overhang or whatever, and you want to spawn vegetation under the overhang
or it's just a cliff that's concave
There will be a 'master' component that has a list of terrain meshes, it will generate a BVH for them and then shoot down rays at set intervals in order to get the height of the terrain and generate the height maps.
Those height maps would then be passed to Compute Shaders that would generate points (using the height maps to get the y position for the point) and meshes would then be rendered at those points.
okay, so you're trying to do LOD for terrain?
No... I am trying to spawn vegetation.
is the mesh concave?
Just so we are on the same page, do you know what a Compute shader is?
It can have overhangs and such, I already have a plan on how to solve this though.
and you'd like to sample positions on the mesh, that happens to be a terrain mesh?
No, I am doing it my self with Graphics.DrawProcedural
I basically just need to cheaply get the height of the terrain at a given xy position.
the cheapest way to get the height of terrain at world xz is using a shader that renders world position y
using whatever camera you want
it would be basically instantaneous
You mean like a camera facing down?
yep
it would look like
camera.targetTexture = yourUtilityRenderTexture;
camera.Render(heightMaterial);
that's it
if you use vfx graph to place the vegetation you can get this directly using https://docs.unity3d.com/Packages/com.unity.visualeffectgraph@13.0/manual/Operator-SampleMesh.html
which, btw, vfx graph uses Graphics.DrawProcedural under the hood
so it's basically exactly the same
you can also use the same thing VFX graph uses to get the mesh
which is in the Graphics namespace
you can also look at its source for how shader graph will render a triplanar world xyz material
if you just want to use that
but that might be a waste of time
render textures are used as "utilities" all the time
consider you'd just need to get the texture once
you could certainly run it in real time if you needed
Hmm, I would need to put the terrain on a separate layer.... maybe I would need to move the camera from location to location to get the height for multiple terrains... it wouldn't support overhangs...
well, so that's why i asked
in that case, use VHACD to generate a group of approximate concave collision meshes, or as accurate as you'd like
because your real problem is that spooky warning about convex meshes having a limit of 256 polys
you can definitely just make a convex mesh collider at runtime using the built in physics collider, and you'd just be Done
Interesting to know, I don't think it supports things like occlusion culling, or lods and what not, but it may be worth looking in to.
it won't work with collisions
you need concave colliders to work with collisions, which VHACD creates for you
imo this BVH thing sounded like it was off the mark ๐ฆ
it doesn't help you advance your goals
of course, if you only need to spawn stuff from the player's point of view
you can add a render pass in URP / HDRP that does world xyz
with your material, then spawn, and then it's occluded and LOD automatically
and simply look at that render pass from time to time and add in vegetation on demand
VFX graph already supports occlusion though
It lets you do overhangs which is what I like about it. And you don't need to mess about with layers (physics and rendering both using the same layer system... just why...) But maybe it is worth giving up/working around that for the camera system....?
but a regular physics collider will
let you do this
like if you add a mesh collider
and leave convex unchecked
you can raycast and get the multiple intersection points
you don't need a BVH if you just want to raycast a mesh
What do you mean raytrace the mesh?
sorry raycast**
you can raycast against a concave collider
so i don't know, you're talking about sampling this at regular intervals
just do it with a regular unity physics raycast
Ah, I could just do a bunch of raycasts using the physics system to get the heights and then not touch it again (maybe use Jobs if I need to do something at runtime)
but it depends what you mean by heights, because the height shader will do this instantaneously
if you don't need cliffs, that is far and away the absolute fastest method
it will be fast enough for realtime
you can also do it from any perspective camera, if you want to do a local effect
you can use a cubic camera if you want
anyway
i think you get it
I think this for me is a bit of the project having evolved over time and what I actually need and how I am doing things has changed.
Thank you @undone coral this was most helpful! I am going to think over what I need exactly again and how I want to do it. Also reread some of this stuff. Would you mind if I @ you again if I have some questions about some of the things you mentioned?
(Also thanks for the Github link at the start, I had not seen it)
sure
I figured I'd ask this in here. I have a super simple game that I wanted to add some simple cosmetic upgrades to. I just want to be able to spawn into a level with a hat, glasses, etc that I selected before loading into the level.
I had 2 ideas, and let me know what you guys think. Idea 1, is just make a character prefab for each costume, because there would only be a handful of costumes, and I could just spawn the prefab in depending on the player selection. I'm assuming I could just apply an int value to the prefab, and spawn it in.
Idea 2 is having one player prefab, but having a script that applies the cosmetic to the prefab at a certain local transform point upon loading in the level. I'm assuming that is possible.
What do ya'll think? Am I over thinking this?
both work
Hi so im also gonna place vegetations soon and using RT to get height map
Mechwarrior mentioned about the layer problem. But i do layer change before certain raycast and restore it all the time. Is it not the same with rendering?
Like, u change the layer right before .Render, then restore it
(And yes the physics n render layer being the same is kinda annoying..)
Can someone give me code of getting keyboard height in iOS. Thanks ๐
is this a regular terrain?
It could be. It's anything that's in "Terrain" layer
Yes if it's terrain i can just use the terrain's heightmap
If it's mix-and-match then go with version 2 I think
Managing prefab variants sucks
how would i make 2 objects snap together if they're close enough to each other through code? been trying to figure this out for a while now but couldn't find an answer
@dusk gyroSomething like that..?
if( distance < some distance)
{
tempPos = objec1Pos;
object1Pos = object2Pos;
object2Pos = tempPos;
}
wouldn't that just mean the 2 objects will swap positions?
Yes. But you can also add rotation and what not.
Oh wait
I thought you said "swap" lol
If you want them to snap... Well, how do you want them to snap? Just get close enough so that their colliders collide? Snap certain vertices? There is more than 1 way to snap things together.๐ค
so im making a script where you can place down objects, but before you place down the object there would be a silhouette of the object you're trying to place wherever your mouse is, but i want the silhouette to snap to the ground instead of hovering wherever your mouse is
its in 2d btw
Cast a ray down from the mouse(optionally with some vertical offset) and instantiate the silhouette object at that position maybe?
how would i do that
Are you sure it's a question for #archived-code-advanced ? ๐
look up Physics2D.Raycast in the docs.
i mean i know how to cast a ray but i dont know how to make it actually snap to the object
You get the position of the hit and use it to set the position of the silhouette object.
wouldn't that snap the center of the object to that position?
@dusk gyro Then add some offset.
Or change the pivot point of the silhouette prefab/object
it works, thank you
How should you handle unit tests designed to give an error? For example if you were to test that giving a grid class a negative size log errors? For me the log is making the test quit and fail.
Depends on your unit test library. For NUnit I remember being an Assert.ThrowsException<T>() method where T is the exception you expect to be thrown
Ah. Thank you. I was expecting to have to silence the logger or something. I'll have a look at that.
Otherwise making your own generic version of that method wouldn't be hard, a try-catch block where you attempt to catch catch (T) (don't forget the where T : Exception constraint), and after that catch (Exception) if it threw anything else
Maybe, though I don't like the idea I'm having to change the code to do the testing like that.
I would either just manually set it, or just set it right before the raycast and then reset it. Are you planning on handling overhangs and such?
Hey, what would be an elegant way to access prefabs during tests in play mode? Best I could find is AssetDatabase.LoadAssetAtPath, but it stops working whenever the object is moved
There's no way I'm the only one that had this issue
Yet google finds nothing :(
I use addressables for that, works pretty well
For editor tests I use AssetDatabase but I use the GUID of the asset as the key for that (so it won't matter if the path changes, only if the actual asset is destroyed and created again, which is a valid reason to update the test script)
How do I know the guid of an asset ?
open its .meta file and the guid will be there
Thanks!
Hey there. How would you handle mirroring horizontally a 3d character for a 2d platformer ?
- duplicate the whole animations tree for a right and left version (seems tedious)
- mirroring everything programmatically
I suppose 2. is the best way but if someone has a reference for that, I'll be glad to know about it, right now I can't seem to find a solution
For reference something like Ori 2 does
what's wrong with rotating the character 180 degrees on the y axis?
it is angled
so it is no more readable
maybe Street fighter is a better reference
the character is in a fighting stance, when rotated 180, his face is hidden and strong arm is no more visible
nvm found a way => if I invert the z scale of the parent transform it seems to work ... animation is doing strange things though
i forget the technical term for that kind of scaling, but you shouldn't use it
so I need to duplicate every animation ?
no
I've tried something else and animation is less weird : inverted x axis scale and rotated on y by 180
i think you need to bake a mirrored version of your character
or look up if an asset does this for you
in maya you can do this
it supports a real mirror operation on bones and geometry
Can you explain a bit more about that or point some ref ?
yes, there's an operation in maya called Mirror, which mirrors the geometry instead of scales it
then for bones animation, you need it mirrored too
but then I would need to duplicate every animation still isn't it ?
yes
hmmm ...
well ... I'll keep on digging then
I'm pretty sure there's a way to handle that without duplicating every animations
my DRY sense is in high alert
what's the issue
think they're gonna say that
how to set notepad into foreground?
it's very important, not with notepad, but another software wich is running
because I'M developing a non-game experience and I need to change between windows
https://www.codeproject.com/Questions/279441/Bring-Process-to-the-front
you can try this out
no guarantee it will work in unity
thanks
generally i don't think unity is the best for non game experiences
something like a wpf app could work better
and it also uses c#
agreed, that's what i was saying
my program has to display 3d graphics
use c++ then
I'm more familiar with unity ๐
ok so get more familiar with c++
at some point you weren't familiar with unity and now you are
so you can get familiar with the tools you need
not true at all
i don't think i've seen a single normal application made in unity
give me a few examples and i'll take back everything
pretty sure wallpaper engine runs on unity
https://dis-da-moe.itch.io/ulina
here's a map i made
that's bc it allows you to turn a unity project into a wallpaper right?
yes, which implies some sort of unity integration
right so that doesn't count as a normal application that has nothing to do with unity
regardless, there are plenty of non game companies that use unity for non game related things, no point gatekeeping how people use it
yeah i guess
i just hadn't seen any, and regardless, c++ is much more widely used for everyday applications
My literal job is making an architecture visualization tool in Unity ๐
my job uses it for visualization too
damn
C++ scares me
i like it more than unity for a lot of things but c# is a better general-purpose language imo
just not as flexible for applications all the time
But I'm totally fine using Java to convert an AutoCad drawing into a GLTF model and dynamically loading that into a Unity scene at runtime for realtime 3D visualization of a blueprint ๐
https://quadspinner.com/ (uses unity for the 3d view)
thanks but i've already been disproven lmao
(but btw both of those apps relate to games)
so you mean don't use unity for apps that do not leverage media... i'd agree
but i know a company who wanted to just do that.........
oof
yeah..
took them a year to realise it is hopeless
the guy who initiated it now has 1 year of unity experience
Quixel Mixer.
Sorry, didn't mean to pile on.
I have made own developer console in my game (I needed it because it is multiplayer game), is there some way to catch Debug.Log functions executing and "redirect" it for my own console logging?
nice! thanks
Oh I didn't know about that!
I thought you need to use this guy https://docs.unity3d.com/ScriptReference/ILogHandler.html
i'm a little confused on what this has to do with this https://docs.unity3d.com/ScriptReference/Application-logMessageReceived.html
Is it that you dont actually need to call your delegate LogCallback? you just need to match the signature?
Yeah, first link wasn't what I used, but looks like you just need to match the signature
Not sure tbh
But since it's a delegate, you can use
private Application.LogCallback myLogCallback;
void Awake() {
Application.logMessageReceived += myLogCallback;
}
``` to simplify things
Better example: ```cs
public class LogTest : MonoBehaviour
{
private Application.LogCallback myLogCallback = (condition,trace,type) => {
Debug.LogFormat("Condition: {0}, Trace.Length: {1}", trace.Length, type.ToString());
};
void Awake() {
Application.logMessageReceived += myLogCallback;
Debug.LogFormat("Test!");
}
private void OnDisable() {
Application.logMessageReceived -= myLogCallback;
}
}
@sturdy edge
Hell yeah now debbuging on multiplayer will be easier
Was wondering what business I had in #archived-code-advanced ๐คฃ
There are a couple free in game console assets on the store btw, might be worth looking into if for no reason but to look into how they did things
One I used made it very easy to make your own commands too
I dont even try to find something on asset store because when I want to make something I am just doing it to learn my self
I think this is the best way to learn
But maybe I am wrong
I've learned A LOT from tearing free (and paid) assets apart. Often discover things you'd never even think to look into
Maybe I should try this method
thanks anyway
I highly recommend it
I am just doing some game without intention releasing it to public, I very like gamedev and this is not my job. It is just so satysfing and its the way I spend my almost all free time ๐
Same. GL HF
๐ any good math brain can help me with some calculation?
I'm trying to convert world position into pixel position
I've a custom splatMap, and I need to convert object position into corresponding pixel inside the texture
{
if (pos < 0) pos *= +1; // Convert value to positive
var p0 = Mathf.RoundToInt(pos);
var p1 = p0 %terrainSize;
var p2 = p1 / terrainSize;
var percentage = p2 / terrainSize * 100;
return Mathf.RoundToInt(textureSize / 100 * percentage);
}```
this is the non-working code ๐
๐ PLEASE
the idea was to run the method for each axis
something like this maybe (pseudo-code):
// for a flat texture facing World-Y
Vector3 worldPosInSplatSpace = Vector3.ProjectOnPlane(worldPos, Vector3.up) * texelsPerUnit + splatWorldOrigin;
// or more generic, if splatOrigin has/is a transform/TRS-matrix
Vector3 worldPosInSplatSpace = Vector3.ProjectOnPlane(
splatOrigin.transform.worldToLocalMatrix.MultiplyPoint(worldPos),
splatFacingNormal
) * texelsPerUnit;
results are vec3, so you have to ignore whichever component is orthogonal to your tx.plane
WOW that's looks nice ๐
thanks ๐
I guess the former should work, appreciation ๐ป
simplified
Working great ๐
Best practice question. I have a game object which may be disabled in a screen by default. When it's "initialized" (not Instantiated(), but rather initialized by me when I know some details about the object), I get the Image component using GetComponent<Image>() and then set the image accordingly. I can't do the GetComponent<>() call in Awake() since Awake doesn't get called on inactive game objects (I didn't realize that, so this was a fun bug to find ๐ ).
Where do you typically, or best practice make this call to GetComponent? I don't want to create external dependencies on the object to initialize it before initializing it, if that makes sense.
See below. I can just set the "Person" of this display gameobject and everything "works", unless the gameObject is inactive - in which case Awake() isn't called first and I get the null reference exception as commented..
private Person _person = null;
public Person Person
{
get => _person;
set
{
if (_person != null)
{
_person.OnPersonUpdated -= UpdatePersonIcon; //unsub from the old person event
}
_person = value;
_person.OnPersonUpdated += UpdatePersonIcon;
UpdatePersonIcon();
}
}
private Image _icon;
private void Awake()
{
_icon = GetComponent<Image>();
}
private void UpdatePersonIcon()
{
... etc ...
_icon.overrideSprite = Resources.Load<Sprite>($"Graphics/Sprites/People/{iconName}"); // null reference exception if the game object is inactive while trying to set this
}
OnEnable()
I mean, I could make an Initialize() method that gets called in Awake() and before UpdatePersonIcon() i suppose, but that feels sloppy
that's the same as the Awake() problem, though - I can UpdatePersonIcon() before that's called
(in fact, that's my workflow - Create this game object, set the Person, then enable it)
Actually - better (and maybe simpler) question - is there any script activity at all on a monobehavior that's inactive?
like, I could just do:
private bool _isInitialized = false;
private void Initialize()
{
... blah blah blah...
}
// and then anywhere I need an element:
if (!_isInitialized) Initialize();
but this doesn't feel great/clean to me, I suppose?
why do the GetComponent in Awake at all? Make _icon a serialized field. Alternatively, making UpdatePersonIcon a no-op unless icon is set, and call UpdatePersonIcon inside Awake
I guess I was hoping there was an Awake() analog that got called when the actual game object was created/instantiated/whatever
I could make it a serialized field, but I generally try to keep the public/serialized fields to a minimum unless something else in the app needs to set it
you can make it private and serialized
Okay, this is very, abstract.
I Am creating a fighting game. Near the beginning I was convinced that using Unity Colliders for the hitboxes and hurtboxes would be innefficient because of the sheer number of frames and hitboxes displayed each second by each player would make it irrealistic to instantiate all the different Collider Components exactly when I need to, and also the hit detection would be handled by the physics system, which would make hit detection not be handled percisely with update and would be hell to manage both locally and through network.
I ended up creating my own hitbox and hurtbox system which is purely numbers with min and max coordinates to a origin transform position. Its very efficient, but Im wondering if i was correct in my assumption that using colliders wouldve been less efficient. Am I incorrect?
In this case, the Icon itself is an internal detail - the only public element of this game Object is the "Person" - the display element displays a whole bunch of stuff, person name, hit points, rarity, and icon
Ideally I only want the Editor to show "Person" in the fields - my understanding is that even private serialized fields show up in the editor? (I haven't really used them before)
I could do that, though.. I mean, I suppose there's no real reason for me to be GetComponent()-ing at runtime, it's not like I'm adding the component programmatically
That's actually probably the best reason to just serialize it and set it in the editor (so I'm not fiddling with bugs/shit like this down the line)
Potentially, but "premature optimization is the root of all evil" - Using unity's colliders would likely have saved you (or will save you, if you revert) tons of time and effort and may have actually been good enough. I suspect that a fighting game would be totally fine. A physics game with hundreds or thousands of hitboxes might benefit from a roll-your-own approach, but even then, you're gonna be doing a lot of work and ... hard work, lots of debugging physics, etc.
There's also a number of ways you could optimize your collider calculations within the unity framework - disabling colliders that likely "won't matter" for an interaction - whether they're out of range or whatnot
I dont want to use my hitbox system for physics collision though, just player to player hit detection
Yeah - I mean, same thing - you'd just have a collider but not the physics elements (rigidbodies)
would using colliders ensure that I am able to handle hit detection the exact frame that the overlaps happen though?
better use dots for such a use case then ๐
dots? dangit theres still so much i dont know about unity
don't use DOTS imo :p
for your use case, don't use DOTS.
https://docs.unity3d.com/Manual/ExecutionOrder.html definitely - collisions happen before Update()
wouldn't say that. DOTS is after all the future
it's awesome once you get used to it
yeah i mean, I might come back to it someday but I'm ... tied to my architecture and haven't written any threadsafe code
ie - I depend on single-threadedness atm
I already created my hitbox system, and if i set the framerate to 144 and spam thousands of hitboxes per second with no optimization on which hitboxes will actually be eligible I see no framedrops whatsoever, I think im just gonna stick with what i have regardless of what would have/could have been more efficiet.
external libraries generating read only lists and passing them around, etc
Yeah, sorry, to be clear, I meant "more efficient" in terms of your own development time
yea this took a whole month and a half, not worth the development time
Good learning project though
there's a recent post on r/programmerhumor that's like... Computer Scientists write sorting algorithms, Programmers call .Sort(). I want to be a programmer and just call the oncollision events ๐
I don't want to write any trigonometry - I'm getting too old for that now ๐
I just am not interested in debugging really fiddly details and stuff
its purely boxes, I didnt worry about trigonometry
I'm just coming out of writing some debugging statements that are already kind of gnarly because my game state is .. complex
that is a unique hell to live in, good luck to you
match-3 meets hearthstone
(each player has a grid instead of a hand, they can match-3 or "play" items to their field)
but the match-3 programming was .. harder than i expected.. and I believe that I'm a quite good programmer (who doesn't, right?)
recursion bugs ๐คฏ
i honestly have no idea what tf this is this is terrifying
I am by no means an experienced programmer. I am creating a game and learning as I need to.
the paste is my server console output for this:
each player gets a grid, can merge-3 more items, play them to their field, and they attack the opponents "crew" (the 3 guys at the top)
pardon the developer art - the art/UI guy is still working on mockups for this
complicated question, but I'm thinking about how I can code behaviors and then use them as pluggable objects in scripts
for example, say I have a "Wander Area" behavior, a "Flee From Target" behavior, and an "Attack Target" behavior. I don't need these as scriptable objects - I just need a way to reference these behaviors in a script or scriptable object, because let's say we have a deer and a wolf, and both use "wander area", but in the deer's case, it will use "flee from target" when the player moves into range, while the wolf will use "attack target" under that same condition.
I've solved things like this in the past ||using reflection to obtain identifiers for each type of behavior at runtime, then defining each unique entity's behavior graph in a markup file, then creating a parser that reads through that markup file (thinking XML in this case, since .NET includes pretty straightforward XML parsing) and creates a behavior controller. ended up extending this to also define other parameters about the entity, so that all information about "deer" and "wolf" is contained within deer.xml and wolf.xml.|| spoilered for the sake of textwall
my thing with Unity is that it supports SOs and prefabs, and I'd like to take advantage of that (much simpler to use a "deer" prefab with a configured behavior controller attached than to just eschew the entire system and use XML to define npcs)
It sounds like making them just normal C# classes would work, no?
so my question is basically: how simple would it be to load up all coded behaviors to create a behavior graph in-editor? I'm not particularly interested in writing a complex graphical utility - all I really need to do is be able to script a BehaviorController that lets me select a behavior, fill out parameters with property drawers, and define transitions out of that behavior into other behaviors
yeah, all I really need is that chunk of code that defines what the entity should be doing if that behavior is active
delegates would probably be very useful there
what i'm looking at is effectively a scriptable FSM
I could actually probably get away with using a Mecanim animator as a regular state machine graph if I wanted to hack it, tbh, since I plan on using Animancer instead for the actual animation side of things
but the API for the Animator class is uhh
lmao
FSM aren't that great for AI normally.
depends on what you want to do
But beyond that I'm not sure what the question is now?
and what kind of AI you're after
Yeah, that is why I said "normally". It does have it's place depending on what you're doing.
so what I'd like to do is:
- code parameterized behaviors (BehaviorWander, BehaviorAttackTarget, whatever)
- be able to select those behaviors and configure their properties for that instance in a BehaviorController through the editor
- specify transitions into other behaviors from each behavior, if applicable
The alternative to this, which I have experience doing outside of Unity, would just be to define everything in an XML file, parse that, and create templates for entities that are then used when they're spawned.
and iirc you can serialize xml/text file fields, so for something like a spawner, it would be simple enough to just drop in the file
just curious, what do you typically use for AI?
There are a lot of examples online and github of SFMs and Behavior Trees (both with and without UI). I wouldn't use XML, and I think this would be better suited for #๐คโai-navigation
oh i didn't even realize there was a full ai section lmao
nah I don't need code examples
correction - I understand the concepts and how to code them, it's working with the Unity API that I'm having the issues with
ttrying to learn unirx
i am getting this error, can anyone tell me how to properly assign reactiveproperty?
anyone know how to convert Player.Realtime.player [] to player[]
@chrome kraken you might have to pass in a type because from the looks of it that Linq expression returns a ReactiveProperty which seems to be a generic type just going by your public variables
Looks good to me after a quick glance at the doc https://github.com/neuecc/UniRx#reactiveproperty-reactivecollection
what does the error says ?
Looks good indeed except on the website they use actual properties, not sure how much that should matter however
Not familiar with this framework
me neither ๐คทโโ๏ธ
so i tried to use same as gitbut ex to use property isntead of memebr variables
i also tried to cast it
but it crashes after i enter unity
after casting der is no error in IDE.. but once i play the scene.. i get below error
PlayerHealth..ctor (System.Int32 maxHealth) (at Assets/Scripts/Player/PlayerHealth.cs:17)
PlayerController.Start () (at Assets/Scripts/Player/PlayerController.cs:17)```
feeling so dumb... not able to figure out for 2hrs now ๐ฆ
i am really dumb.... i looked everywhere expect pressing f12 on ToReactiveProperty() method... forgot i can access source code LOL..
this solved the issue..seems the github readme is not update
Question. How do I find a game object with a specific tag, if it's a child of a parent object? My script was working when my Camera was just it's own object, but once I attached it to a parent (for other functionality I needed) my script can no longer find the object anymore, and throws a null reference. Mind you, nothing has changed on the Main Camera object, but it's hierarchy.
GameObject.FindWithTag doesn't care if it's a parent or child or anything
It only cares about the tag
What object are you trying to find and what code are you using to try to find it?
I'm trying to delay release of addressables, something like:
` private bool _releasing;
public async void Load()
{
if (_releasing)
{_releasing = false;}
else
{
_handle = _assetReference.LoadAssetAsync<Sprite[]>();
_value = await _handle.Task;
}
}
public async void Release()
{
_releasing = true;
await Task.Delay(TimeSpan.FromSeconds(5.0));
if (_releasing)
{
_releasing = false;
Addressables.Release<Sprite[]>(_handle);
}
}`
The problem is, I want to kill the previous asynchronous call if it tries to re-release after a short load
like release-load-release fast
it should cancel the previous release and restart the "counter"
any tip?
Found this https://forum.unity.com/threads/cancel-async-task-best-practice.805839/ might fit your case
Cancellation tokens is exactly what I was looking for. I knew about them, just didn't remember. Thanks!
This did the trick, so it only releases the addressable after 5s.
`private CancellationTokenSource _loaded;
public async void Load()
{
if (_loaded == null)
{
_handle = _assetReference.LoadAssetAsync<Sprite[]>();
_value = await _handle.Task;
_loaded = new CancellationTokenSource();
}
else
{
_loaded.Cancel();
_loaded.Dispose();
_loaded = new CancellationTokenSource();
}
}
public async void Release()
{
try
{await Task.Delay(5000, _loaded.Token);}
catch (TaskCanceledException)
{return;}
Addressables.Release<Sprite[]>(_handle);
_loaded.Dispose();
_loaded = null;
}`
using System.Collections.Generic;
using UnityEngine;
public class Mouselook : MonoBehaviour
{
// Start is called before the first frame update
public float mouseSensitvity = 100f;
public Transform playerBody;
float xRotation = 0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitvity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitvity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseY);
}
}```
what is the problem i can just look up and down and not right and left even if i see the number in the x is changing
Don't cross-post, and that isn't an advanced code question
ok ๐ฆ
Debugging a nasty issue for 2 days, could use thoughts.
I have a data structure called a GridItemDictionary that has a List and Dictionary internally for holding items on a grid (the dictionary is for fast lookups based on (x,y), the list is for enumerating the items on the grid by Id).
I keep this data object in memory on the server and on the client(s). It's a turn based game, and during a turn, many things can happen to the grid (new items get added at new locations, items get upgraded, etc). It's impossible/illegal for two items to exist in the same (x,y).
When the server sends updates to the clients, it does so in the form of a list of "battle actions" (9 types, currently, I expect there to be many more) - some of which are BattleActionNewGridItem or BattleActionUpgradeGridItem or BattleActionDestroyGridItem. When the message is received by the clients, they update their internal data structure, animate the changes and then destroy/change the game objects (since the animations take time - the game objects aren't destroyed immediately when the server tells them to).
Somehow, and very rarely, I'm getting ArgumentExceptions from the Dictionary when I try to add an item that already exists in the dictionary. I cannot figure out how to reproduce the issue, and I am fairly lost in even knowing what the root cause "area" is (animation delay? network issues? actual game object integrity/logic issues?).
I can provide any source code you want to see.. here's kind of a list of the relevant classes:
- BattleManager (client logic manager)
- BattleScreen (client UI)
- DudeGridRenderer (client grid item - yes, the name is awful)
- GridItemDictionary (data object representing all items on a grid)
- Battle (server "battle" object, contains GridItemDictionaries and all battle-specific stuff)
- ServerBattleManager (primary server logic)
Thoughts/strategies welcomed.
I can't even reproduce the issue 100% ๐
Actually I'll just go ahead and start pasting the code from the above classes in case you're bored and wanna have a whack at armchair debugging.. or feel free to just point and laugh at me. ๐
are your clients applying updates right away, or do they queue them up and replay them client-side?
https://pastebin.com/5iy7TQtK BattleManager
https://pastebin.com/26ShQmwa BattleScreen
https://pastebin.com/eGNyZhTd DudeGridRenderer
https://pastebin.com/Dd0Pu72z GridItemDictionary
https://pastebin.com/iV3ukp14 Battle
https://pastebin.com/rrNySJdL ServerBattleManager
Both - the BattleManager (client logic) maintains the "true" data, but signals the UI to unspool the events (BattleScreen subscribes to the events and enqueues/unspools the coroutine animations)
It's... complicated, unfortunately.. even though I have tried to keep it as simple as possible to avoid bugs like this but... somehow I've stepped in the poo anyway.
Hm.. I did find one small bug that... may be related? BattleScreen.cs line 150 - I should only start the queued coroutines if the queue was empty before adding one, not if the count is greater than 0 - if I queue a bunch of coroutines at once (which I do) then they all start animating immediately. There may have been situations where the grid items didn't get deleted or something, leading to data integrity issues.. shrug
I'm making (or trying to) make a game where the user can build train tracks/stations and I'm having difficulties figuring out how to
a. spawn a train at the station(I could probably make a script and attach to the train station)
b. make said train follow the tracks, and
c. Check if there's a railway connecting two stations, so that the stations know if they should spawn a train(I don't want the train running out of track in the middle of the map)
Obviously this is a major part of the game, so any help is appreciated. I thought about using A*, but couldn't find a way to do a. and b. with a".
It really depends on how you construct the tracks. Using something like A* would be really overkill and not ideal for something like this.
You most likely want to use splines, at least for B.
For A. I'm not sure what the problem is exactly.
C. You most likely want to create a 'node network' where each node is a station and keeps track of all the other nodes it connects to.
Ya I guess I solved a while I was typing it
Iโm kinda new to unity, so could you point me towards a tutorial about splines?
I have a small understanding about splines, but I donโt rly think it fits in this context
So I have two pieces: straight tail and curved rail 90 degree turn
You'll definitely want to model your railway network as a graph data structure, and A* or Dijkstra's would be useful if you have a need for calculating a shortest path on that graph.
The splines themselves are a separate but related concern.
If it is just straight and corners then yeah, splines would be overkill most likely.
The thing is, the user can place tracks anywhere on the plane, except for on top of another track
So how would I tell if there is a path connecting two stations?
So it is not on a grid?
No
Well you would need some sort of snapping to connect the tracks anyway.
If you've modeled your network as a graph these are very easy questions to answer via graph traversal algorithms
I mean itโs precise to 0.25 units
Sorry if Iโm being dumb but how would I do that?
Iโm really stuck
I recommend doing some research into graphs and algorithms like Depth first search
And breadth first search
Once you get an understanding of that you can think about how to model your tracks as a graph and it should become pretty easy
You will want to have a strong understanding of that area to pull this kind of game off effectively
What Praetor said, and for actually connecting the tracks together you will most likely want a sparse matrix. (Someone can correct me if there is a better way)
I have an understanding of dfs but the question is how would I decide where to start it and also when would I do it?
Sparse matrix? Can you link a tutorial pls?
I assume you would want each train station to be a node.
Whenever you connect a track you can do a DFS starting from the new track to see what connections you've made
Would that be processor eficcient?
Yeah
Ok Iโll take your word for it
Well you don't even need to do it every time you place a track, only when connecting two tracks.
It's basically O(n log n)
Ye ok
As long as you don't have 10000 tracks it'll be fine
But how would I tell?
Sparse Matrix. Basically a 2D array where each cell is a track.
The idea is that each time you place a track you convert it's position to a 2D index, and add it in the sparse matrix. You can then do index.x + 1 to get the track (if any) that is next to it.
Huh thatโs smart
Also idk about this assumption but would it also be easier to save player progress with sparse matrix?
Apposed to? Idk what you would be saving so I can't really say. But it would be better than a 2D array.
Well rn Iโm just spawning prefabs I guess thatโs not really smart in all aspects
So sparse matrix is better than GOs
You shouldn't/can't save GameObjects really. Just save the info you need.
Ye
Sorry for late response
I guess since I just started making the fame a week ago I havenโt really been thinking long term
you guys is there any way to get access to the network details in unity?
What kind of network details
i would reimplement grid item dictionary
my guess is that you are moving an object without updating its position in the grid
use C#'s NetworkX
i know how to get the ip but how do i get stuff like network speeds
maybe there's something in the asset store to do this
but what's your goal?
Im currently working on a unity powered os
and a network reading for certain things would be a nice touch
if it's on windows you can read the performance counters for many things
yes
on linux you can stat files
it is
there's lots of stuff on google for this ๐ good luck!
thx ill do my research.
I've been making some phenomenal progress on my current project, thanks to this Discord. I can't thank all of the regulars on here enough for the help.
I had a question regarding level selection/progression. At the end of my level, I have a quit, restart, and next level button. I want the next level button to obviously go to the next level, but what should I do if there is no next level? Should I run a check to see if my string is valid, and then perhaps either grey out the button or return to the menu? I'm trying to make the script modular, so I could plop it in any level, and also work if I expanded my level count.
Edit: And to add on, is there a way to verify if a level name string is valid before trying to open the scene? Would that just be a null check or something?
My implementation has this use case covered (so that any external users of the dictionary to store the GridItems don't need to update both the GridItem and the GridItemDictionary) - the GridItemDictionary treats the X,Y lookup as "bad" and rebuilds the X,Y dictionary if it finds/doesn't find an item - see https://pastebin.com/Dd0Pu72z lines 136-166
I'd probably just not show the button if there is no next level - with .enabled on the game object.
Er, uh, SetEnabled() I believe - i forget the actual property
Are you doing scenes as levels, and the button basically just loads the next scene when pressed?
i'm saying you have to implement Move(int id, int newX, int newY) on the class
because it sounds like right now you are doing move as
the caller has to remove a grid item, then add the grid item back in
No.. the client is free to set the grid items x and y.. the container places no faith in the (x,y) lookup dictionary - if it fails to find on that, then it discards rebuilds that dictionary.. clients don't remove/readd grid items to the container
well, that's why you're getting exceptions
because it's assuming something is immutable that is not
i assume things can move around in your game
aye, can and do
I'm ... not understanding your stance though... like, my game doesn't assume anything in the container is immutable - in fact it explicitly mutates them constantly
a cache key is supposed to be immutable
the container just provides ... extended functionality than List does
which is why i am encouraging you not to use a cache
not to do that as the pattern
you shouldn't "rebuildcache"
cache might be a bad word for the pattern I implemented.. maybe lookup table is better?
you should just set the dictionary's values on Add, Remove and Move
/// <summary>
/// Add a single GridItem to the GID.
/// </summary>
/// <param name="gridItem"></param>
public void Add(GridItem gridItem)
{
_gridItems.Add(gridItem.Id, gridItem);
if (_gridItemLookupCache.ContainsKey((gridItem.X, gridItem.Y))) // cache collision
{
RebuildCache();
}
_gridItemLookupCache.Add((gridItem.X, gridItem.Y), gridItem.Id); // ArgumentException throw is OK - data is corrupted (can't be duplicate X,Y in a Grid).
}
this is very dubious
it's also where you're getting the exception
Hm.. I understand that, I'm just not sure I understand why - since the collision/exception is very rare
everything points to a bug where the caller is mutating grid item
and not update the lookup cache
because it doesn't have to
i can't see if grid item is a struct
Right.. I mean, the caller doesn't have any info about the lookup cache..
is grid item a class or a struct?
it's a class, but could be a struct
public class GridItem
{
public int Id;
public int X;
public int Y;
public GridSquareContents Contents;
public int DestroyIntoId;
public int DestroyIntoX;
public int DestroyIntoY;
public int ChainId;
public int CurrentHP; //
public int MaxHP;
public bool C1; // belongs to C1
}
}```
you probably have a bug of the form:```
gridItem.x = newX
Remove(gridItem.Id) // wrong
Add(gridItem) // bad
GridItem is used extensively through the game - the GridItemDictionary is .. a superset of List<GridItem> where I can perform fast random access on X and Y instead of I
where the Add's error is a red herring
Hm.. so I "can't" remove an item by X, can only remove by Id
yes but you see what i'm saying
you mutate it before you remove it or something
i'm trying to tell you what the bug probably is
you have to implement Move on this class, trust me
Yeah - trying to think it through
this class needs to be rewritten
i would do something of the form
int Add(gridItem) {
assert that the grid item's ID is invalid
assert the position is unoccopied
assign it an id
place it
mutate the grid item's id field
return the id
}
GridItem Remove(int id) {
remove the grid item everywhere
mutate the grid item's id to -1
}
Move(int id, destination) {
move the grid item
}
etc. etc.
you can maybe make the grid item's x and y location only accessible to this class too
Thinking on that - that's a possibility but that would require
that can be a little more cumbersome though
yup
anyway you got it ๐
X and Y would need to become private setters on GridItem, which I think might be OK since they don't exist with an X and a Y when they aren't on a grid, obviously
But I'm still struggling with the "you have to rewrite this" because I'm not sure what I would change right now on the GID
I'm not seeing what's buggy (yet)
I also sorta don't want to do that - because there's a pretty big refactoring cost to implementing Move
I'm talking a 40k line codebase across 3 libraries
that should be evidence that you probably have a bug there
it's not impossible but.. just a big piece of work and I'm not sure the bug is .. there
somewhere, something is changing the position before Remove
and then the lookupcache will remove the wrong item
hm.. it can't, though
why not?
it only ever removes on Id
if (_gridItemLookupCache.TryGetValue((gi.X, gi.Y), out int cacheId) == true && cacheId == Id) _gridItemLookupCache.Remove((gi.X, gi.Y));
i don't know, looks like the Ids might be bad too
i guess, that's what's happening right?
i don't know what to say
Ids are immutable - i could make them explicitly so
clearly the grid item is being mutated in a toxic way
Yeah, I mean, you're not wrong, something smells in this general area
I just .. am not sure what
and the fact that it works 99.99% of the time is what's really getting me
Like I can have a session where I play for hundreds of adds/removes/moves without any issue whatsoever
then randomly get this exception
I mean, I've gone as far as overriding ToString to print out what the grid looks like at any given point in time
ie:
Grid:
+-------+-------+-------+-------+-------+
| | | (4) | (1) | |
| | | ID 12 | ID 16 | |
| | | CID 0 | CID 0 | |
+-------+-------+-------+-------+-------+
| (1) | | | (3) | |
| ID 20 | | | ID 18 | |
| CID 0 | | | CID 0 | |
+-------+-------+-------+-------+-------+
| (2) | | | | (1) |
| ID 11 | | | | ID 13 |
| CID 0 | | | | CID 0 |
+-------+-------+-------+-------+-------+
| (1) | | | (4) | |
| ID 24 | | | ID 14 | |
| CID 0 | | | CID 0 | |
+-------+-------+-------+-------+-------+
| | | | | |
| | | | | |
| | | | | |
+-------+-------+-------+-------+-------+
which looks amazing if I do say so myself ๐ ๐ ๐
but so far haven't tracked down any root cause or issue
Each level is planned to be it's own scene. Just easier for me to implement, or at least I hope so haha.
yeah that's fine, no problem with that
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.GetSceneByName.html and check for invalid scene
and if so, disable/make-non-interactive your button, depending on your preference
(maybe make a special glowy button that goes to the credits, or something)
Hey Sharping, how would you personally set up a function to check the validity of the scene I'm trying to load? I'm searching through Unity's documents and some forum posts with pretty inconsistent or dated results. Could I do IsValid(SceneManager.GetActiveScene().buildIndex + 1); ?
Scene next = SceneManager.GetActiveScene().buildIndex + 1;
if (!next.isValid())
{
// set the button to inactive/different button/etc
}
sorry - isvalid is a method, not a property
Ah thank you
edited to add the ()
So apparently giving us the buildIndex + 1 returns an Int, and is throwing an error error CS1061: 'int' does not contain a definition for 'IsValid' and no accessible extension method 'IsValid'
Mind you I tried both isValid and and IsValid, just incase, with the same result. This is getting silly at this rate, for just wanting some simple functionality.
i was just copying your code - i don't know the actual call for getting the next scene.. lemme dig for a sec
Scene next = SceneManager.GetSceneByBuildIndex(SceneManager.GetActiveScene().buildIndex + 1);
if (!next.isValid()) { ... }
should work
Ah, I'll be totally honest, I didn't think Unity would return a dang int for that function haha. If it worked how we thought, it would be golden haha.
yup.. as always, consult the API docs ๐
It says index, why would it be anything but an int?
Why comment if you aren't going to be constructive in the slightest?
I'm wondering why you would think it would be anything else, I'm not trying to be antagonistic, I want to know
Because I'm not a good programmer? Is that a good answer for you?
That doesn't have any explanatory power, so no
Good lord, how are you a mod lol
Are you alright? I just want to understand your mindset, you're not being attacked here. It helps me to know why you would think something like that so I can help others
I'd like to point that "I'm not a good programmer" is not a great excuse to use in #archived-code-advanced ๐
Here's my thought process. I would think it would return the string name corresponding to the index number. So say index number 10 is "Scene10", so the function would just return that string name, considering you use strings for most of the Scenemanagement API to work. It would just make it easier for both new users and seasoned users to program.
Unity API is either really friendly, or a bit convoluted, and thus far, the scene management is a bit wonky.
Sadly that'd make it more difficult, because then you would have to parse the outcome into an int any time you wanted to perform any maths.
The API is certainly a bit fucky though, you would think you could use a SceneAsset to handle all this, but it's an editor-only thing
So you've got to use buildIndex (ints,) or by name (strings,) to get Scene structs (something you cannot construct without the API). It's certainly jank ๐
He has a website with helpful troubleshooting content for most common Unity misunderstandings. So like he said he tries to genuinely understand people's mindset facing such problems as you had.
No harm intended :)
What is the best way to do networking these days?
"Best" way is always related to context. Describe your project in #archived-networking , then maybe you'll get a satisfying answer
Is this a good place to talk about TextMeshProUG2D?
I tried my question in 2d-code and got crickets lol
I guess I'll try here
You'll get the same crickets here. People who know most about 2d code are in that channel.
Just be patient, this is a slow time here because it's the middle of the night in US
this is really about how the text system works and weird rules about setting up fonts. Like the little bit I could find makes it seem like the font system in unity is a bit persnickity
fair enough
Do you mean TextMeshProUGUI?
The outline is part of the material, you will need to have the right kind of shader applied. But why not set it up in the inspector instead of code?
Then you can just swap the material out as required.
yes
because I am modding
Rough. Okay, well I don't know about those methods.
My guess is that that material doesn't support outlines
/// <summary>
/// Sets the thickness of the outline of the font. Setting this value will result in an instance of the material.
/// </summary>
public float outlineWidth
{
get
{
if (m_sharedMaterial == null) return m_outlineWidth;
m_outlineWidth = m_sharedMaterial.GetFloat(ShaderUtilities.ID_OutlineWidth);
return m_outlineWidth;
}
set { if (m_outlineWidth == value) return; SetOutlineThickness(value); m_havePropertiesChanged = true; m_outlineWidth = value; SetVerticesDirty(); }
}
protected float m_outlineWidth = 0.0f;
This is the source
But TMP developers are advised to use the mobile shaders which do not have outline support.
If so you fix it by assigning the correct shader to the newly created material/
Anyone have idea how to make the MathF.Sin to be added to Y transfom because it starts makes Y = 0
when i add the + Y to the amp it just made it go crazy
Because it's a feedback loop
Hello epic devs
I'm working on a mobile game(In PlayStore) but I want to test the leaderboard without actually uploading it to PlayStore instead I want to test it in my phone when I install it using the APK
The issue I'm going through is when I install the game on my phone using the APK the authentication to google play isn't working, so leaderboard won't work.
I am sure the leaderboard works because when I install the game from play store but won't work from installing it from the APK
How can I solve this problem?
Please tag me onReply