#archived-code-advanced
1 messages · Page 91 of 1
wrong. An Application domain is a Windows concept, an Application can only have 1 domain, You may have many processes (Not threads or Tasks) and each one will be in it's own domain
and, btw, Unity does run inside a .Net environment if you build using the Mono backend
I looked it up and everything is can find says that the process is above the domain, the domain holds the assemblies and threads, and that application domains are a .Net environment concept. There are even pictures with diagrams that show a process holding two domains.
im paying someone nothing to make multiplayer
invoking System.Environment.Exit just freezes the editor for me. Does it not do that on your end?
(i have not tried it in a build)
that’s what I was thinking would happen since the script is not being ran from its own standalone process, unity is running those scripts. I havent tried it yet in a build or in editor as I can’t yet, but I will.
I am a little fuzzy on the relationship between Unity and .NET application domain(s)
also, Application.Quit can take an exitCode parameter, which might sidestep this whole issue (:
Yes it would, i somehow didnt know it could take an exit code. Just more proof that you don’t have to know everything about something to know anything about it…
I didn't either!
Small update on this.. Unity seems to apply the UTF8 encoding before returning a stream of bytes. This is not mentioned anywhere in the documentation. Just wondering so I know for the future cases, is this considered general knowledge? Do backend requests that return a stream of data generally apply the UTF8 format before sending it?
Isn't UTF8 only the way you interpreted byte ? If your Byte does not conform to a UTF8 string, then you would get garbage when you try to convert it. Usually, you specify the format when you encode and when you decode. See StreamWriter and StreamReader for more information.
https://learn.microsoft.com/en-us/dotnet/api/system.io.streamwriter?view=net-8.0
https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader?view=net-8.0
Is there any way to pass an environment variable to unity on the command line? I have a build machine that has a system user running a Jenkins service. A required environment variable isn't visible inside of one of the methods being invoked on the command line. This is after setting the environment variable in the power shell script that invokes unity, as well as using EnvInject.
My current work around is simply running the service as the main user on the computer that has the environment variable already set. This works for now, but might be an issue later on where I need to override the value of that environment variable based on what project is building.
I image standard windows c# code should the trick.
well, the bundle sounds like it's supposed to be binary data, not printable text
Not sure what you mean.
Oh, I misread what you wrote
I thought you said "isn't it the only way to interpret bytes?"
that makes a lot more sense now lol
I'd like to keep any environment variable swaps outside the project since this is specific to the build machine. I already attempted seeing the variable in the PowerShell script but it doesn't seem to carry over consistently.
The variable itself is a path to an SDK toolset.
You can use script variable through a call to unity build with https://learn.microsoft.com/en-us/dotnet/api/system.environment.getcommandlineargs?view=net-8.0.
I was hoping to use the env var directly inside the build script as I have been rather than adding additional tooling to pass the ask path via arguments. That's looking less and less likely the more I look around, unfortunately.
The main issue is that the variable is user level. System level variables are fine and EnvInject works to a certain extent. Builds succeed (unity also requires the env var to be set) but my own calls to invoke some SDK tools fail because it's looking for the variable user side and the user is system level.
I've been working on package that heavily relies on command buffers. I wanted to transfer and have support with URP and HDRP later on, but I know that the workflow is not the similar. To have minimal changes and keep a more united codebase, does anyone have any idea on how I could do it? I know for shaders it's easy enough by rewriting the whole shader, having the same name, and including a unity package on the asset for URP shaders. But the problem is that the command buffers are interconnected with my codebase, meaning that doing the same equals to rewriting the whole package. And changing one thing on built in could end up being a lot of work on URP or HDRP.
Start by abstracting everything that has something to do with rendering by creating interfaces/defining contract.
By example, create a function: RenderShadow which use as little as possible BiRP things. Then, whenever you upgrade redo your implementation.
So I'm having an issue with the AssetDatabase query in code.
AssetDatabase.FindAssets("t:scene (init or patch)")
This doesn't work in code, but does work as a query using the editors search.
AssetDatabase.FindAssets("t:scene init")
In code if I get rid of the OR it works fine. Is there a bug with using OR for the query in code?
I believe you might want to use the more advanced search tool. Maybe look at: https://docs.unity3d.com/ScriptReference/Search.SearchService.Request.html
I see, i think i will move out of command buffers for levering some part of lighting. Do you know if with Graphics.rendermeshinstanced i can have a custom only shadow pass?
Not sure why my code wont do the same thing in the negative z axis which is on the left side of this cube
Issue is solved now
I am currently making a scriptable object, which has to display the
[Serializable]
public struct AbilityData
{
public string title;
public string cooldown;
public string UID;
public string script;
public Color titleColor;
public ItemType type;
public Sprite sprite;
public string[] attributes;
public TooltipDataTitledDescription[] titledDescriptions;
}
class onto a gameobject, which I am using as a prefab because thats the only way to access something through a scriptableobject.
However, when I call this function
public override void AddData(object data)
{
AbilityData tooltipData = (AbilityData)data;
print("Adding data from " + tooltipData.title);
title.text = tooltipData.title;
title.color = tooltipData.titleColor;
type.text = tooltipData.type.ToString();
image.sprite = tooltipData.sprite;
cooldown.text = tooltipData.cooldown;
UID.text = tooltipData.UID;
}
which writes data onto the object, it works, but only sort of. The prefab view doesnt update and doesnt even realize its been changed! Its a really weird thing and IDK if theres a better way to do this, please help?
do i need to write something like a custom-treated scene just for viewing the properties of abilities? i would actually love to do this ngl it sounds fun
If you mean to edit the prefab instance, you'll probably need to set your changed elements dirty or record your changes in prefab:
https://docs.unity3d.com/ScriptReference/EditorUtility.SetDirty.html
https://docs.unity3d.com/ScriptReference/PrefabUtility.RecordPrefabInstancePropertyModifications.html
If you mean to edit prefab in your assets, then things get more complicated. Keep in mind that the prefab preview doesn't show the state of your prefab - it is just the temporary state of its copy. Depending on your choice you can later discard it or save it. In other words - if you're modifying the file itself, the changes won't be visible in the preview until you reopen the file. So always make sure you're editing the correct object.
I thought the AddData() Function would write the the prefab preview, but it looks like it writes it to the file instead. How can I change it to write to the prefab preview?
if (GUILayout.Button("Select"))
{
Unselect(myTarget, myTarget.editing);
Undo.RecordObject(myTarget, "Selected Ability " + title);
myTarget.editing = i;
myTarget.abilityTooltipS.AddData(myTarget.abilities[i]);
}
For reference, here is where I write AddData:
To modify currently opened prefab you need a reference to its instance. If the object is currently selected in the Hierarchy window, you could simply access it with Selection.activeGameObject;. Alternatively, if you've opened the prefab via code, you can store the reference to it. There is also the option of getting the reference of the currently opened prefab via PrefabStageUtility.GetCurrentPrefabStage().prefabContentsRoot); (assuming you've it opened in a Prefab Stage).
so when I save the scene it applies the changes... How do I Do this in the AddData function?
welp
I just put [SerializeField] infront of the
public AbilityTooltipS abilityTooltipS;
line in my code and it allows me to (temporarily) pick a gameobject instead of a prefab, ignoring all of this finicky nonsense.
I know that this is "bad practice" normally, but for my situation, i view this as perfect
- I ignore all finickyness
- With prefabs, things can get deleted and the connection between the SO and the object is not stable, which can delete (and has) deleted objects in the past.
- I do not need the AbilitiyTooltipS to persist through even scene changes, only need the reference which i can reassign at any time.
I need some ideas on how to approach this, I have a terrain texture, and I sample from it on a shader. I use GPU instancing, so for all of the meshes on that terrain the share the same terrain texture. And If I have to use another terrain texture, i need to make a separate draw call with a new terrain texture. I would like however to unify this.
What could I do to configure the shader so that in a simple draw call each knows which terrain texture to use?
Ideally without adding to much memory size. I've been managing so far fine with a single int. One idea is to transform the textures into a texture2d array and then pass also an int index with the draw call to know which one to sample, but that means doubling the amount of memory
is there any low precision int value that has less memory size? normally it would go from 0 to 6 in extremely worst case, a whole int seems too much
If you want to encode data in less than 4 bytes, you have to pack it into a 4 byte value, alongside other data. For example, you could use 1 byte from the int you're currently using, so the int becomes a 3-byte int and a 1-byte texture index.
Packing and unpacking this data is done with bitwise operations.
Mmm, i could look into that, thanks!
I have another problem
If I do
RenderParams renderParams = new RenderParams(lod.materials[lm]){
camera = cam,
matProps = propertyBlock,
receiveShadows = true,
shadowCastingMode = CastShadows? ShadowCastingMode.On : ShadowCastingMode.Off,
worldBounds = new Bounds(Vector3.zero, 10000*Vector3.one),
};
Graphics.RenderMeshIndirect(renderParams,lod.mesh,CommandBuffer,1,submeshCounter*sizeof(uint)*5);
it doesn't work
but if I do
Graphics.DrawMeshInstancedIndirect(lod.mesh, lm, lod.materials[lm], terrain.meshResult.settings.meshBounds, CommandBuffer, submeshCounter*sizeof(uint)*5,propertyBlock, ShadowCastingMode.Off, false);
it does
it doesn't work all the time, it does for the first two frames and then disappears
I've had problems getting the new RenderMesh methods working. It might not support built-in RP.
oh no
But it's fine to use the old methods, they're not going anywhere anytime soon.
I just wanted to have one single code base, why do they make it so haaaard to support urp ,hdrp and built in... 😦
How do we add depth to a top-down game in Unity? (like jumps and stuffs)
I am thinking of adding z_value into consideration, making the y_value that appears on the screen = y_grounded_value + some_coefficient*z_value. But since this would complicate the position calculation of Unity, I want a more neat solution.
How do we implement this? Im also thinking of customizing the get_position() function of Unity so the new way of calculating the position wouldn't break the physics interaction. can we change unity rendering code?
If you want to encode data in less than
You could just make it actually 3D
Isometric view sounds like a way to go.
How can I make a dynamic texture 2d array? Xd
Dynamic how ?
I don't know the length of it, it should be more like a texture2D list
I finally made this greedy meshing voxel thing using dictionarys which people told me not too for some reason lol
but I would need to redraw all my animations and objects in 3d
and transfer everything to 3d?
Unfortunately there is no such thing. Make an assumption of how many you will need and pre-allocate it
Okay
As far as I know the limit for textures in a texturearray is 1024 so if you need more then you can work with a List<Texture2DArray>
dictionaries are the best and those telling you otherwise are wrong ;)
Okay, yeah i shouldn't be using more than 6 or 7 there's also the problem of copying the data every frame, but we will see
I'm using the following
// Encode the token in base64 format as "username:accessToken" where username remains empty
var authTokenBytes = Encoding.UTF8.GetBytes($":{accessToken}");
var authToken = Convert.ToBase64String(authTokenBytes);
using var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", authToken);
var response = await httpClient.SendAsync(requestMessage);
var responseBody = await response.Content.ReadAsByteArrayAsync();
return responseBody;
to hit a /content endpoint in Unity's CCDN on a private bucket (https://services.docs.unity.com/content-delivery-client/index.html#tag/Content/operation/GetContentPublicEnv). However, I'm getting an error saying that I'm unauthenticated? Adding the Authorization header in postman works fine, but in c# it's like it's not being added at all? I even printed out the header before calling SendAsync and it's there... I've been stuck for some time, anyone have a clue what might be missing here?
This code is deployed as a module in Unity's cloud, so there's no way to use a proxy on this or anything unfortunately
Hm are you supposed to include the : in the encoded base64?
According to this: https://content-api.cloud.unity3d.com/doc_client/
I'd say yes
I even found a forum post confirming it
That line is also contradictory to the comment above, it does not include the username
It should remain empty, so you essentially say ":token" and encode it in base64, as per the docs https://services.docs.unity.com/content-delivery-client/index.html#section/Authentication
I've even compared what postman is doing, and we're sending the same header, so the token itself should be valid 🤷♂️
That link shows an example access token, and the resulting base64, can you make sure it's also what your code outputs, if you use that token as input?
Hmm, good point, give me a few minutes
ah yes I found a solution
create 2 empty objects for player, one for shadow which holds the grounded position of player and another object for rendering the character in the air
Does anyone know a way to set the property "providesContacts" of a mesh collider to true without the mesh renderer needing to be convex?
What happens if you call LoadAsset() on an asset bundle multiple times?
bundle.LoadAsset<GameObject>(assetName);
Does it create multiple copies in memory or is only one copy ever loaded?
`` /// <summary>
/// Registrierung Username & Password
/// </summary>
public async Task RegisterWithUserNamePassword()
{
try
{
await UnityServices.InitializeAsync();
await AuthenticationService.Instance.SignUpWithUsernamePasswordAsync(m_RegisterUsernameInputField.text, m_RegisterPasswordInputField[0].text);
Debug.Log("SignUp is successful.");
}
catch (AuthenticationException ex)
{
Debug.Log(ex.ErrorCode);
}
catch (RequestFailedException ex)
{
// Compare error code to CommonErrorCodes
// Notify the player with the proper error message
//Debug.LogException(ex);
}
}``
How can I change the error ?
not sure if I understand your question, but you can always create a new exception with any message you like. You can even define your own exception class, just derive from ''System.Exception".
https://gdl.space/mokocadiki.cs
does anyone know how to fix this "not loaded" "is Loading" error everytime i change scene via this script?
I have a strange problem, game does only work in editor, doesnt work when built, it looks like from debugging that the Camera Manager would never call the SetupPlayerVirtualCamera() I can go voice chat if that would help
Camera Manager
private void OnEnable()
{
playerTransformAnchor.OnAnchorProvided += SetupPlayerVirtualCamera;
}
private void Start()
{
if (playerTransformAnchor.isSet)
SetupPlayerVirtualCamera();
}```
Player
```cs
public override void Spawned()
{
if (Object.HasInputAuthority == true)
{
playerTransformAnchor.Provide(transform);
}
}```
playerTransformAnchor
```cs
public class RuntimeAnchorBase<T> : DescriptionBaseSO where T : UnityEngine.Object
{
public UnityAction OnAnchorProvided;
[Header("Debug")]
public bool isSet = false; // Any script can check if the transform is null before using it, by just checking this bool
[SerializeField] private T _value;
public T Value
{
get { return _value; }
}
public void Provide(T value)
{
if (value == null)
{
Debug.LogError("A null value was provided to the " + this.name + " runtime anchor.");
return;
}
Debug.Log($"{name} runtime anchor provided with {value.name} transform and OnAnchorCallback {OnAnchorProvided != null}");
_value = value;
isSet = true;
Debug.Log($"value set to {_value} and isSet to {isSet}");
OnAnchorProvided?.Invoke();
}
public void Unset()
{
_value = null;
isSet = false;
}
private void OnDisable()
{
Debug.Log($"RuntimeAnchorBase OnDisable");
Unset();
}
}
this is mostly the code used in CHOP CHOP
It looks like the OnAnchorProvided is not connected to the method (it's null on SO)
the event is raised tho
What you experience is most likely due to the ScriptableObject. They behave differently in editor in and a build and it is why you should try to never use mutable scriptable object.
So Event channels would be okay?
I mean, if you know what you do it can be. The issue is that it increase complexity and there is alternative that do not.
Simply use singleton.
Thats what i thought
Hello, there is a challenge I don't even know how to begin thinking about. I want to simulate the earth wobble or planetary precession movement. Essentially, imagine an object that is tilted at an angle to the Y axis. The movement that I want is a rotation of the y-axis around the world's y-axis, thereby creating a wobble. Any ideas how to do this?
https://en.wikipedia.org/wiki/Precession like this
Precession is a change in the orientation of the rotational axis of a rotating body. In an appropriate reference frame it can be defined as a change in the first Euler angle, whereas the third Euler angle defines the rotation itself. In other words, if the axis of rotation of a body is itself rotating about a second axis, that body is said to be...
I only want to simulate this movement, I don't care about the physics at all.
I figured it out
using System.Collections.Generic;
using UnityEngine;
public class Precession : MonoBehaviour
{
public float precessionSpeed = 1f;
public float precessionAngle = 5;
// Update is called once per frame
void Update()
{
float currentAngleX = precessionAngle * Mathf.Sin(precessionSpeed * Time.time);
float currentAngleZ = precessionAngle * Mathf.Cos(precessionSpeed * Time.time);
transform.rotation = Quaternion.Euler(currentAngleX, 0f, currentAngleZ);
}
}
Good morning. I use an old plugin (from 2012). I managed to make a complete game with it. But when I use a version of Unity higher than 2021 or I have new packages, sometimes I get this when I click on the plugin and I don't know how to fix the problem. (Don't support in dynamic module)
does anyone have a good first person movement script???
you're almost certainly in the wrong channel, but here's a great little tutorial I used when starting out:
https://noobtuts.com/unity/first-person-shooter-game
Is it possible to nest other asynchronous tasks inside an AsyncOperationHandle, so it runs before whatever the main function is? I tried turning it into a Task but there's a heap of code that specifically relies on it being an AsyncOperationHandle, and I haven't yet figured out why it has to be that way
I'm running a function to load an addressable asset, and I want to ensure Addressables.LoadContentCatalogAsync() always runs first to retrieve the right catalog, by putting them into a single function so they run together
In 2d side management games like mom simulator, do you prefer to use animator to play animations or not?
There are many animations in these games.
Also, suppose we use spine
Can we mix between two animations and blend them through animator? Animations as I mentioned are created in spine.
Blending like face gesture and expressions
does anyone knows to get fix scenes "not loaded" "is loading" error?
Wait until it's loaded?
i mean during the loading the cinemachine confiner2d is disabled and all audio sources are cut
which is ugly
thanks but I would like to know if I choose mecanim, can I blend layers?
They said it is recommended to use skeleton animation instead of mecanim
Discuss animating with Spine and using the Spine Runtimes in your apps and video games.
In the Spine Editor, you need to create an animation (the "empty" or "mix-out" animation) that keys the same bones as your to-be-mixed-out animation (in this case, as the shoot animation). Basically you need any other animation playing that keys the bones again, otherwise the previous animation's state will not be overwritten by anything and left as-is.
Unfortunately these limitations are cumbersome, which is why we recommend to use SkeletonAnimation instead of SkeletonMecanim if possible. Another solution would be to use a Mecanim-wrapper workflow as shown in the example scene Spine Examples/Other Examples/StateMachine SkeletonAnimation/Mecanim Logic SkeletonAnimation View.
what is the Supreme way to break up your code professionally?
I have watched a tutorial on it but it is just seperating the codes into different files
There is none. Most rules are guideline and are subjective. The idea is to have the most maintainable code, and that varies depending on a lot of factor which includes project and team specific.
There is theory such as Coupling vs Cohesion and Solid principle that should help you find out about why and how to have a more maintanble code.
There is one that breaks the code into Movement Script, Combat Script and let them communicate through Main Controller. but I find a lot of flaws with it considering lots of action requires to take both Movement and Combat into account
then dont follow it
StateMachine is just an amazing idea to split the codes for example
Im finding similar structures to StateMachine
The idea of what you describe is to reduce dependency between each part of the application.
StateMachine is one of the best pattern in game development. It applies well in a lot of situation.
You have simplier variation such as Strategy Pattern.
I needed to include an external dll in my project so i stuck it in Assets/Lib
i get this error nonstop now
Loading assembly failed: "Assets/Lib/System.Drawing.dll"
the scripts work fine otherwise
unity just complains
can i suppress that?
i don't see any import settings to make it load nicely
worst case, i will just live with this error since it seems purely cosmetic and only happens in editor
System.Drawing is a Windows Forms only .dll
idk, this open source library i'm using requires it
i might have to just surgically remove it from the code which is annoying
and is that library a windows forms library?
btw, if you are including external dlls in your project they should be in a Plugins folder
hrm, i saw something on stack overflow saying i could just stick dlls in assets. maybe that was an old/dumb post
it's a Targa output library but i guess it uses some color structs from system.drawing for certain use case
it helps to read the docs https://docs.unity3d.com/2017.3/Documentation/Manual/SpecialFolders.html
Actually it does seem the the Plugins folder requirement has been removed in recent Unity versions, so ignore me
Odd though that is is still mentioned here
https://docs.unity3d.com/2021.3/Documentation/Manual/ScriptCompileOrderFolders.html
i'm using a slightly older unity version, i'll have to check and see
Plugins folder is best, just to cover all eventualities
I've always used Plugins, there used to be just one
Assets/Plugins
but now you can have many
Assets/.../Plugins
Assets/.../Editor/Plugins
so Editor/Plugins do not get included in the Build
what I particularly like is
Assets/.../Plugins/WebGl
where Plugins and Plugins/WebGl contain the same .dll but just compiled differently
The Build platform decides which one to use
Need some thought-solutionizers. I have a game brewing that has a gesture to execute a move (swipe up to move up, for example). I'm doing this via IPointerDown/Up handlers, keeping track of the amount moved, and moving after the Up is received and the gesture is greater than a threshold amount. I'm then playing a sound effect (like a "whoosh") in addition to any of the other moves. It works great...... but feels laggy. I've already eliminated as much dead space from the SFX as possible, converted the mp3 to ogg (I heard there was some latency when using mp3 based sfx?), but it still mentally feels sluggish.
I'm thinking that I might be wanting to do some gesture prediction and play the SFX before the user has finished the gesture, since 99% of the time the gesture will go through to completion, but in the 1% - the user is going to hear the whoosh before lifting their finger. Maybe I could start the SFX and if they don't lift their finger before some amount of time (0.1sec?) I cancel the SFX?
Any thoughts?
It's kind of hard to emulate/demo this in the editor, but here's a video (with audio) using the mouse.. hopefully you can sort of tell when I'm "unclicking" and hear the SFX
(as far as the audio tech - I'm basically just using PlayOneShot(), not using any aftermarket stuff like FMOD)
sounds like a good idea. Maybe even have a separate "fizzle" sound that plays when it's canceled
yeah this is the way, are you talking about the 'swipe' sound? i think ideally i'd make it loopable with a couple different 'endings', one for cancel and one for complete?
yeah, the swipe sound
i think as soon as they touch, it should make some sound
and that sound should last as long as they are holding
hm.. not sure if loopable would work..? you're thinking like an "engine rev" kind of loop?
like finger press whsssssssssssssssssssss fingerup oosh
Never thought I'd be typing out sound effects to describe a problem ... lol
well you're doing a good job of it! yeah that's what i'm thinking
some kind of visual feedback when you touch might be nice too
ooh, that's an idea, too.. maybe like particles emitting from the touch point
it's a little weird because you aren't touching anything in particular, so what should react? but i think if the board got a little sharper or something to show that you've 'got' it, that could work
(emission rate increases as you get farther from the origin?)
worth a shot, i might worry that particles coming from where they are clicking makes it seem like that location is important in some way, when really it seems like they are 'grabbing' the whole board
but if it did like a slight tilt or something it might be cool
🤔 I could also experiment with "gesture trails" which might look nice
oh yeah that too
or haptics when you initiate a pointer-down
i think the haptics might be annoying though
might be kind of distracting if the result 'drawings' themselves don't matter
i struggled to get them working properly before
yeah i don't know much about that but i think it might get annoying eventually
one of the core problems of games with this sort of interface is your finger often blocks what you want to see.. particle vfx and stuff at the touchpoint are often hidden by fat fingers
yeah
i'm thinking about games with similar interactions which i've played and i don't play mobile games so there aren't many, but i'd have a look at how candy crush and threes handle their similar drag interactions
they just tend to be more 'drag this thing' and less 'drag the board'
i have Royal Match on my device and there's 0 feedback
but it still works 🤷
I'll play around with it.. i like the 'engine-rev' idea, I'll give that a whirl
might be hard (for me) to get an sfx "finish" sound that connects seamlessly with the start
aye that part requires audio knowledge which i definitely lack, but i'm imagining the swipe being a fairly steady sound so that where you cut it off isn't such a big deal, and then if the ending is punchy enough (a little pop or something) maybe that works
aye.. what I worry about is the complexity.. since there probably is a different "attack" than the looping part, so it basically requires 4 sfx, "attack", "loop", "finish", and "finish-cancel"
and I gotta get them all to blend seamlessly
you might be able to get away with not doing the cancel case and see how it feels
I might try the "assume they're going to complete the gesture and play the sound and cancel it if they don't finish the gesture within 0.03 sec"
since mostly that won't happen
yeah
especially given that other games seem to do even less, that seems like a good place to start to me and then see how it plays
honestly once you figure out the game you don't actually do the "click and drag and think" thing.. honestly I put too much time into architecting that 😛
look finishing games is for chumps, it's all about spending years solving random edge cases and building tools that don't get used 
like I keep track of where you are in a "X" shape (where the cross is at the origin) and drag the tiles in a preview a few pixels.. it works nicely but turns out to be almost completely unnecessary beyond the first 30 seconds in the app
haha right?
Don't know if server related question are for this channel, but here goes.
Im trying to run a dedicated server from a linux machine to host on multiplay, but i cant connect to the server , i tried doing the same on a windows dedicated server and it did work, the problem seems to happen when I try to run the server on a linux machine ( im using centOS9 on a vm that is portforwarded)
depends on how you create the VM - if you're using something like docker then you have to add the ports to open in the dockerfile
eg:
(expose 49855 opens that port on the vm)
Is waiting until release an intentional design?
Swiping gestures in most apps don't require you to release to get triggered, and I would think requiring release plays a big part of why it feels sluggish.
Oh, triggering the move after some threshold + time has been reached to identify the gesture?
I'm not using "gestures" per se - rather just keeping track of origin/distance on pointer down/up
Typically minimal velocity and distance threshold feels good to me.
We did try that early on but it felt like it did the move before you meant to.. there's actually a lot of science and math in gesture identification, and me trying to roll my own for that ended poorly. I'm pretty sure there's some gesture libraries in the marketplace but the current solution (audio aside) is pretty good for us so we didn't pursue it
We don't have a need for any other "gestures" aside from swipe in a NESW direction
Sure, but that's just my experience from using swiping in pretty much all apps, especially social media apps with their tabs and you swipe horizontally to navigate between them. None of them requires releasing for the gesture to trigger.
You might need to play with the two threshold values a little bit, if it felt too eager that means the values were too low.
Presumably this game is also for mobile, another fancy thing you can do is to dynamically relocate the starting position as user keeps holding down their touch. This will allow player to hold down touch and continuously move in different directions without ever needing to lift up their finger every move.
so.. bad use case but I just tried tinder (lol) and it required a pointer-up event to finish the event
that sounds right to me...i don't know if there's really a 'right' answer but for a game i would go with what feels the most interactive and tactile
Anyone know of a way to access objects in a newly additvely async loaded scene before the contents of the scene do oneanble/awake?
I was looking at AsyncOperation.allowSceneActivation but that doesn't give me access to the "preloaded" scene right
Yeah different designs have pros and cons for sure, but if responsiveness is crucial then not requiring the release to trigger is definitely something to be looked into. In almost all mobile rhythm games, swipe/flick notes trigger by distance/velocity without requiring release, and being responsive is the core of rhythm games. And yes similar techniques like trimming the leading silence (even the few milliseconds) in SFX audio are also used, but I think there's a good reason why all rhythm games go for that design for swipe/flick notes.
So I was looking at source generators again to make using SerializedProperties easier. My thinking was if I could have something like class PropertyData<T> {}. And do something like:
PropertyData<SomeClass> someClassData = new PropertyData<SomeClass>();
someClassData.FooSerializedProperty.floatValue = 5;
Where the SG would find all the serializable fields and make properties for accessing the SerializedProperties.
But I think I have it a bit twisted around and it can't work like that... right. Unless I put every field inside of PropertyData<>. So ideas on different ways to achieve this sort of thing?
Does PropertyData has to be generic and you access a particular class via that?
A potential alternative would just to generate a SomeClassPropertyData class with all the stuffs in it.
My thinking was basically to provide any type and it would generate the serialized property accessors for it.
Yeah could do a type per, maybe that is the only way while avoiding magic strings. Just feels a bit... messy I guess?
There are different approaches you can take, mostly depends on which one you find convenient for your use case.
One approach is that you can put a [GeneratePropertyData] attribute on SomeClass, and SG looks for that attribute and generates the corresponding SomeClassPropertyData class.
If you don't have access to SomeClass, you can instead do something like:
[GeneratePropertyData(typeof(SomeClass))]
public partial class SomeClassPropertyData { }
And SG will fill in the implementation.
But both of these approaches have the issue of you have to do that for every class you want to generate.
I guess my goals are
- Make using serialized properties refactor safe by not using magic strings.
- Easily access serialized properties from any class with minimal boilerplate
Could I do something like
public static class DataConverter
{
public static partial ??? Create<T>();
}
??? someClassPropertyData = DataConverter.Create<SomeClass>();
Maybe generate SomeClassPropertyData from the Create method?
I don't really have a full grasp of what sort of info a SG can access and how it can be used.
Should be possible yeah, SG basically has access to your source code as parsed AST, you can indeed inspect that and see "yep Create<SomeClass> is called, I need to generate something so that will work."
Although you might have issue with how to actually implement that Create<T>.
Oh, really, that is cool. What sort of issue?
Not exactly related to SG, but how would you write code for a Create<T> that return different types depending on T? Eg calling Create<int> it returns an IntWrapper, but calling Create<string> it returns a StringWrapper.
Ahh you mean the return type?
Hmm, I was thinking generate a new Create method for each, but I guess that wouldn't really work...
Yeah
You can do DataConverter.CreateSomeClass though, but that kind of gets back into the magic string territory.
If you have access to SomeClass and can modify it, then you can put an attribute on it so you can let SG generate SomeClass.PropertyData so you can do new SomeClass.PropertyData().
But that has the same issues as the other approaches where you need to put attributes on every class you want generated.
Well PropertyData needs to access the editor for getting the SerializedProperty but yeah. As you said it both requires access to the class, and adding it to every one.
I guess I could do SomeClassPropertyData propertyData = DataConvert<SomeClass>.Create(); No...?
maybe... no...?
Would that work? Create needs to have a different return type for different SomeClass.
No I guess not right, cause the Create signature would be the same except for the return type.
Hmm, one idea is to do:
DataConverter.Create(out SomeClassPropertyData foo);
It looks a bit ugly though.
I would need to define SomeClassPropertyData thought right?
No, SG can generate it (probably).
How can it? It doesn't reference SomeClass anywhere in that line...?
I guess DataConverter.Create<SomeClass>(out SomeClassPropertyData foo); would do though
Well it can look at you calling with out SomeClassPropertyData foo and realize it needs to generate a SomeClassPropertyData class.
That feels kinda dirty but kinda cool haha
But yeah your idea of DataConverter.Create<SomeClass>(out var foo); is better, it's more refactor safe when renaming SomeClass.
Hmm, actually that wouldn't work.
You still need to specify the out parameter type so it can resolve overload.
And specifying type will break refactor when renaming SomeClass, if that's what you care about.
It would throw compile errors though I think, so it would be fine.
Yeah it would, then you would have to follow all the errors and fix them one by one.
The new SomeClass.PropertyData() solution wouldn't have this issue and is refactor safe, but the obvious con being you have to modify SomeClass.
Which I might as well just use an attribute at that point
This is also refactor safe if you need to refer to the generated class directly.
I found the article which looks like it might have something in it that could do-ish. But haven't finished reading it to understand what is going on and if it really applies or not https://medium.com/@sunside/converting-between-types-in-increasingly-absurd-ways-89414ae6eb7c
Yeah, I might do that, or try the static method with the out
Anything that prevents me from having to use so many dang 'magic strings' that I have to search down every time I refactor
Yeah having to write a stub class like that is a cost, but at least it’s just one time cost and you get the benefits of safe refactoring down the line.
Yeah, kinda my thinking
Anyone know of a way to access objects in a newly additvely async loaded scene before the contents of the scene do oneanble/awake?
I was looking at AsyncOperation.allowSceneActivation but that doesn't give me access to the "preloaded" scene right
The SG solution in the article basically boils down to an API of:
var propertyData = DataConverter.Create<Foo, FooPropertyData>();
Which I guess isn't that much different from:
DataConverter.Create<Foo>(out FooPropertyData propertyData);
// Or omit the <Foo> generic
I don't really like that though, it means creation logic of every single type will have to be in one method.
Yeah, and speaking of which, another solution other than the stub class one is to put an attribute on the SomeClass, but rather than generating a separate SomeClassPropertyData class, SG generates a nested class inside (SomeClass.PropertyData)
That will also be refactor safe and probably easier to use, if you always have access to modifying SomeClass.
Yeah but that would require wrapping it all in a #if UNITY_EDITOR and I am not a fan of mixing editor and runtime code when I can help it.
I think the way to go is either with the attribute on the SomeClass or go with defining SomeClassPropertyData with a attribute or something.
I guess I could always treat SomeClassPropertyData as a sort of 'view model' and have it partial so you can put other editor only logic in too
Hmm, wrapping it in #if UNITY_EDITOR should be done by the SG right?
So it shouldn't affect runtime code, other than extra attribute metadata.
Yeah, but it will still be there and accessible in the runtime code. And requires making your runtime class partial
Sure yeah I guess if that's a concern to you, this might be the way to go.
Yeah guess so. Thank you once again for your help! 😄
By pressing Q and E I'm rotating the camera by 90 degrees. If I want to keep WASD coherent for my grid based movement do I need to multiply my input by Quaternion(0,-cameraRotation.y,0)? Or else?
if it's a grid based movement I'd expect you'd just have different key profiles for each camera rotation
I mean I guess you can do camera relativity too, but probably easier just to set 4 different cases
Oh yeah actually thanks
Hi, with the JSONUtility class, is there a way for me to supply my own ToJSON() function for my own class, to serialize that part manualyl?
Not with the built in json serializer, you should consider using json.net or system.text.json instead
yeah, that's easy to do with custom converter with STJ
make a custom attribute, tag those fields/props then let your custom converter do the rest
Thanks a lot for the help
really the newtownsoft/json.net one i would recomend over JSONUtility for most use cases
it also supports more collection types, most importantly Dictionary as well
Wow, I've been wanting Dictionary serialization for ages, I'll definitely check that one out.
Does anyone have the best version of StateMachine? I know Darkadia has a very customizable and stable one but Im still looking forward to upgrading mine
a StateMachine is just a pattern, the best one or best way to implement one really depends on what you are trying to accomplish
unity has a built in state mahcine graph in the visual scripting package
nah I want to build my own for maintainable codes and make sure it fits best my game
It depends on what you want to do. You might, by example want to serialized data for your state, or have the best performance.
how can I overload methods with something like enums
I was able to do it with classes, but it feels weird
why would it be any different a class is a Type, an Enum is a Type
need to explain more what you mean, enums do not have methoods unless you are using something like extension methods
you can always create a new enum and point to the previous enum type and include additional entries
thats what I was thinking, but it doesnt show in vscode
now that I think about it, it could just be a vscode problem
thats annoying
show your code
one sec I gotta make it again
here is my enum:
Direct,
Universal,
Others
}```
here are 2 of my functions:
{
}
public static void invokeNetworkMethod(MessageTypes.Universal messageType, int recipientClientID, string methodName, params object[] parameters)
{
}```
remove the static modifer from the enum
why you can have static enum
not the way you use enums
this MessageTypes.Direct messageType, is an invalid signature
then in your method signatures just have MessageTypes
but I wont be able to overload the method
MessageTypes is the type for the enum, DIrect is a value of it
just like int would be a type and 42 would be a value
of course you can
not with the enum
you are misunderstanding what a enum is
you are trying to use a enum value as a type, not gonna work
also there is no need to overload in this case
you need switch case inside your method to branch
btw code beginner problem
nah I cant do that
absolutely definitely not #archived-code-advanced
Im making a multiplayer thing, and I need it to be understandable for others
different methods is messy
public static void invokeNetworkMethod(MessageTypes messageType, string methodName, params object[] parameters)
{
if (messageType != MessageTypes.Direct) return;
}
public static void invokeNetworkMethod(MessageTypes messageType, int recipientClientID, string methodName, params object[] parameters)
{
if (messageType != MessageTypes.Universal) return;
}
whats the problem?
he wants to constrian a signature to a enum value that is not possible
I'll just use classes lol
that is too slow
why do you need this, the signature changes based on the message type anyways, so that would be enough to seperate the methods and overload
Then you will either need to generate the sound with an AudioClip (If it is possible) or use a 3rd party audio library.
audio library?
also feels like trying to be clever over clear
FMod or Wwise
not using those
Then, you are out of option from what I know. I believe that using FMod or Wwise would be you best shot if audio clip cannot be generated at runtime.
So, runtime change ?
=> MonoBehaviour.OnAudioFilterRead
If not enough fast => FMod or Wwise
if still not enough fast => Do not know (Maybe Native call such as AndroidNativeAudio)
Quick memory related question,
If a single submesh in a fbx file is used does it load all of the other submeshes under that same fbx?
using Physics.NonAlloc casts. If I have a arr.Length of 10. Previous frame had 6 hits, and current frame has 3 hits. does that mean that the array will still have 6 "hits" 3 from current, and 3 from previous? Or does it set the rest to null per cast call?
Yes there should be the previous hits still in the array. The remaining items cannot be null because RaycastHit is a struct (a value type). These methods will conveniently return an int which indicate how many hits were filled in the array.
I see, I know about the int, it's just I had an Array.Sort on it and seems it will sort the old ones with the new ones.
can always clear it and it'll keep the stride capacity I believe
Array.Sort() has an overload where you can pass the start index and length, it won't sort outside of that
So Array.Sort(hits, 0, hitCount) where hitCount is the integer returned by the physics cast should do the trick
I'm trying to debug something in my code that calculates the minimum size of a component based on the max x/y of all the child components. They're instantiated and parented in a grid layout. They're each 300x350 but for some reason the anchored position is showing as (0,0) and a call to LayoutRebuilder.ForceRebuildLayoutImmediate is having no effect. I've also double checked that the objects are active and active in hierarchy. It just seems like the force rebuild isn't doing anything until... later?
Inspector/debug mode properly shows anchored position/sizedelta is what I expect, but in the frame I instantiate these things, they're all anchored at 0,0.
What idiot thing am I not realizing?
(inspector shows 45, -1368, debug.log shows 0,0)
Actually.. I'm kicking this all off in Awake(). Will layouts fail at that time? maybe that's the problem..
Sigh, that was the problem.
rubber duck to the rescue. 🦆
I have a scriptable object which wants to have a reference field to a specific script which I can drag in (sort of how I would do using something like a sprite, where i can drag the script in from an assets). I only want scripts which inherit from a specific class too, so if there is a way to do this someomne please help me out.
can App Domains be used in .NET Framework
and do such support Windows, Mac OS, and Android ?
Unless I'm mistaken App Domains aren't available in Mono. And they definitely aren't available in real .NET (Core) (which everything is moving to). My suggestion is to find a way to not use App Domains for whatever you're trying to do.
how can i unload an assembly from memory ?
I know they were slowly adding support for assembly loading/unloading through a different mechanism in .NET.
I have no idea if Mono ever allowed it through alternative means, a google search would probably point you in the right direction.
understands little of that
i think i know to to stop "not loaded" "is loading" error
i think my tries to load the scene every frame while being in the triggercollider2d
Hello, we're using Unity 2019.4.36f1, and we have a custom package in our project from a github repository. Unfortunately, it has caused us a lot of issues, and we'd like to just move it to the Assets folder instead of having it as a package. Does anyone know the best way to approach this?
You can copy the package's folder to the Packages directory at the root of your project and it will remain a package but it'll be editable. https://docs.unity3d.com/Manual/upm-embed.html
Tried that, but there's a bunch of errors coming from it. These packages are deeply integrated into a really large project
what errors?
Well, you'll have to give more specifics if you want to get help, because embedded packages don't fundamentally break things, they'repractically just normal assets
if you just want to make it easily editable, you can check it out as a submodule into the packages folder, then it'll still act like an embedded package but you can edit the working copy on the fly rather than having to mess with the lockfile every commit
thanks everyone. will give it a shot and be more specific once im next available
hey, can someone help with netcode here?
i'm trying to use it on LAN but it's not working
both computers are on the same network
and i'm using the ip from ipconfig
Most likely firewall
Looking for some help, Trying to build a string container that allows for member variables to be referenced like {memberVariable} in the string. This would allow for designers to grab current values of an object and also allow for any field to be retrieved. I currently have a working prototype but is using Reflection which is a bit slower, does anyone know any patterns or simple command that I am overlooking? here is my current code:
public static class FormattedString
{
public static string GetFormattedString(string baseString, object obj)
{
if (!baseString.Contains('{'))
return baseString;
string formattedString = "";
foreach (var split in baseString.Split('{'))
{
if (!split.Contains('}'))
{
formattedString += split;
}
else
{
int index = split.IndexOf('}');
formattedString += GetFieldValue(split.Substring(0, index), obj);
if (index < split.Length)
formattedString += split.Substring(index + 1);
}
}
return formattedString;
}
public static string GetFieldValue(string name, object obj)
{
try
{
return obj.GetType().GetField(name).GetValue(obj).ToString();
}
catch
{
return "{Unable to find: "+ name+"}" ;
}
}
}
Hoping someone might be able to help me because i've tried basically everything at this point. I'm trying to import msal for android into my project so I can do authentication with azure b2c on android
I got the aar in Assets/Plugins/Android with the proper platform include set up(only included in Android builds). I set up a custom proguard file just to make sure everything from it will be included in build.
I am trying to access the PublicClientApplication function but I am getting a AndroidJavaException: java.lang.ClassNotFoundException exception. I tried with a different function from the same library(BrowserTabActivity) and that was grabbed just fine. I've tried different versions of msal(5.0, 4.9, 4.0). double checked the aar contents to make sure it has the class i am trying to call(it does), i've check build logs to see if any errors/warning came up(nothing seems to be wrong). any ideas what could be going on?
anyone have any tips for hooking a particle system renderer up to a UI slider? this is the code I have for it cunrrently, and it gets the references but doesn't actually change anything in the material.
Just use a Dictionary. This is overkill (and very slow)
Do you happen to be a Python/JavaScript developer?
that's likely not the real property name. Set the inspector to debug mode to see the actual property names
@sly grove would love to know how to put all the fields into a dictionary, all structs would have to be boxed.
As far as I can tell from your snippet the values are all strings
It boxed variables really don't like changes
The GetFormattedString function requires an object to retrieve the type and fields.
What? What does boxing have to do with anything here? Your code is going to box the structs since you're getting them as a system.object through reflection. Dictionaries do not intrinsically box structs.
I don't really understand the use case behind your code. Why would I use your code vs existing C# string formatting utilities i.e. string interpolation or string.Format?
Ok, interpolated strings cannot take variables that are not referenced within the code. As such, If I had a designer that I told to build a tooltip for any object.
They could write the following in the unity editor text box: "Deals {minDamage} to {maxDamage] of [damageType] damage to the target."
My script would find all 3 fields within the script, since most teams export out there documentation it would always be up to date with the latest variables that are available.
OR
I could go about using Format, Give my designers the List of fields that are available and are sitting in the list I provide format as my arguments.
As such it would look like this: "Deals {0} to {1] of [2] damage to the target."
Not a big deal until I have 6 programmers working on 32 different scripts and the added fields were added to the documentation but not the list we provided the designers.
Also If you were to build an asset for the store, simplicity is key and having a property drawer that can just grab all fields for an in game tooltip is ideal.
code generation is often a performant alternative to reflection, but I think just agreeing on a workable system with designers might be better - I assume there will be some predictable consistency with what information should be in tooltips for the types you have?
Really bad idea to create a text interpreter (Error prone, possibility of performance issue, compatibility issue (ILL2CPP), more complex, error handling). Instead, I would do something like that:
[Serializable]
public abstract class DataProvider
{
public abstract string Get();
}
[Serializable]
public class TypeDamageProvider : DataProvider
{
[SerializedField] private DamageTypeDefinition _damageTypeDefinition;
public override string Get()
{
//Rich Text Formatting ? (_damageTypeDefinition.Icon, _damageTypeDefinition.Description, _damageTypeDefinition.Color, etc.)
return _damageTypeDefinition.Title //Name is already used by unity.;
}
}
[Serializable]
public class Tooltip
{
//Add Localization on top of it
[SerializedField] private string _message;
[SerializedReference] private List<DataProvider> _dataProviders;
public string GetMessage()
{
return string.Format(_message, _dataProvider.Select(x => x.Get()).ToArray());
}
}
That being said, ideally you would query directly the damage type/data of the attack instead of repeating the data twice. (And you might want to remove linq depending on the performance you are aiming for)
Neat, need to implement something like this eventually. No clue how to heck to tooltip an ability that creates other types of abilities through conditions though
some recursive tooltiping
I'm already dreading it
string.Format works by referencing index though, which is really fragile if your add/remove/reorder data providers, and with the current setup each data provider can only provide 1 string.
how i have handle it in the past is put all things that can be referenced in the string in a Dictionary
then had a regexp i used to find my placeholders and extract the key for that dict from and replace with the gotten value
If you make the reasonable assumption that message will use less variables then there are, the original solution of splitting the message and look for the value is imo the better solution. Just need to get rid of the reflection.
Storing names to values mapping in a dictionary is fine, or simply changing the data provider to string Get(string Key) then looping over is also fine assuming you aren't going to have hundreds of thousands of pairs.
(This kind of system sucks for catching typos and refactors because it's essentially magic string with no protection or even any help to know what variables are available, kind of the same issues with i18n, but oh well it's a tradeoff)
The message and the DataProvider are beside which kinda remove the issue of add/remove/reorder. In fact, I believe that using keys could actually be a detrimental as well. Such as duplicated keys, renamed keys, unused keys, unknown keys, ambiguous keys, etc.
Alternatively, you could have your DataProvider to be instead a DataSource and query from them instead with a key/value (find and replace). There is also the possibility of removing completely the DataProvider and DataSource and use a "DataResolver", however each time you are pushing your data further from your message increase the complexity. At the end, it is a matter of how much flexible you want to be versus how much complex you are ready to go.
Sure yeah, if for every tooltip you need to drag in the data sources alongside the message, then the index concern is less of an issue, but the tradeoff being you need to do that for every tooltip, rather than having a common set of providers and you only reference whichever you need (which also has the tradeoff of having to know the variable names)
I guess I am going to use the reflection solution I originally posted for the time being and try to optimize where I can. As you all have noticed I am using this mainly for tooltips which in all reality are displayed when the player slows or is non-active, thus a small lag spike could be mitigated if it even causes one to begin with.
Only thing I might end up adding is a property drawer with a list of drop downs and an attribute that only allows for certain fields to be used. I'll post the solution on GIT and link it here if anyone would like to try it out.
I want to schedule jobs over a NativeParallelMultiHashMap but I noticed that IJobNativeParallelMultiHashMapMergedSharedKeyIndices was removed. I couldn't find any info about what the standard prodecure is nowadays, anyone who knows?
And I thought my interfaces were a little too verbose
is it possible to access the Burst Compiler at runtime and get it to process assemblies that contain the BurstCompiler annotation
Sorry, I misunderstood your response. This worked perfectly fine. Thank you for your help!
Hey all, does anyone know if there's a way to modify native collections inside of animation jobs?
Is it possible to switch the openGL context in a native plugin without breaking Unitys rendering? I am trying to store the current openGL context and then switch back to it after I am done. But just doing this without anything else alrady breaks Unitys Editor rendering:
UnitySubsystemErrorCode QuadBufferStereoDisplayProvider::GfxThread_SubmitCurrentFrame()
{
GLFWwindow* unityWindow = glfwGetCurrentContext();
// Custom render stuff
glfwMakeContextCurrent(unityWindow);
return kUnitySubsystemErrorCodeSuccess;
}
Just solved this. If anyone's interested, the Animator class has a nice feature where you can add job dependencies that run before your animation jobs. You can get some pretty cool, complex procedural stuff going as a result, and could theoretically run things like burst-ified, parallel IK jobs 💪
I'm just now learning the jobs system because I have a game that has a pretty important use case for them
Question I have though, just to satisfy my 3 AM self
let's say I had an array of triangles representing a mesh, and it was a really complex mesh, and I wanted to calculate the physical mass of the mesh. My understanding of multithreading would suggest that having a bunch of threads summing up a single value wouldn't be possible.
Techically you could divide your mesh into submeshes, compute the mass of each submesh individually and sum them all after
haha good luck then
but I have a workload that involves generating convex collision meshes from one single concave 2D shape
why would you start from a 2D shape ?
and part of that workload involves calculating the mass of each collision mesh
I don't know what a "collision mesh" is
Because it's a 2.5D game and the final result of this 2D -> 3D conversion will always result in a mesh that has the same thickness throughout the entire mesh
and it's easier to paint and erase 2D shapes than it is 3D, we have a library for it that's decently fast.
mesh that you'd use for a MeshCollider
I just call 'em collision meshes
Also means that calculating the mass of each collision mesh is a simple algorithm
Yep working with one less dimensions should be linearly faster
You calculate the area of each front-face triangle, so those inside the original 2D shape. Then you multiply by the object's thickness value. This gets you the volume of the equivalent 3D triangular prism. Then you sum them all up, multiply by a mass per unit value, and bam
Just not sure if it's worth jobifying that
I mean I could jobify the part where I calculate each triangle's volume but not sure about summing them all up for the entire mesh
You only need to compute this for one mesh at a time ?
And how many vertices approximately would your mesh be made of
but more like ~500 or ~1m
it could just be a single cube, or a giant clusterfuck of triangles
xd
wouldn't say we'd reach 1 million triangles
the game does try to clean up the 2D shape before triangulation and splitting into convex shapes
but even a 1x1 unit circle will be 16 triangles
so if a player starts going ham with the circle brush, it adds up. And right now all of this is single-threaded, so if I go ham with the circle brush...even my computer struggles and the framerate starts to dip lower and lower till I let go
Mostly because I have to do multiple meshes at a time
you mean that the triangles are merged into bigger polynoms prior to your computation ?
Yeah.
the framerate goes due to the mass computation or the drawing ?
goes down*
The mass computation. Once the collision meshes are generated and the colliders are set up, the game's fine
oh so this saves a lot of work
And it's not just calculating the mass that I have to do
so right now you're computing the mass while you're painting ?
I have to extrude out the 2D shape, so adding back-face vertices for each front-face one. Then connecting those back face verts with the extra triangles in the index buffer. Then I need to connect the back face to the front face by generating triangles for each edge of the shape. Which also means I need to figure out where all the edges are by finding indices that form a line not shared by multiple triangles in the font face
So...
step 1: edge finding
step 2: mass calculation
step 3: generate backface verts
step 4: generate backface tris
step 5: connect front face edges to backface edges
step 6: update colliders
I'm doing all of that list of steps while painting
Need to be able to, because the game relies on the collision meshes to figure out whether you're painting over another object in the level
or trying to erase one
And it all works, it's just slow
are you using a lot of computations with floats and vectors
And since this also needs to be done as the level loads, if I can offload a lot of the work to other threads then it should also improve level load times (which..admittedly aren't that bad right now, all things considered)
did you ensure the computations (float, float) are always done prior to (float, vec) and prior to (vec, vec)
considering I don't know how to answer that, I'd say no
though A LOT of the work is just moving things around in memory
i mean if at some point you compute a * b * v (where a and b are floats, and v is a vector2), you should compute this in that very order, not v * a * b or a * v * b
Why? In my head, multiplying a vec by a float is easier to reason with. Curious what the performance implication is though
this is because a * b * v compiles to a * b (1 product) then result * v (2 products) while a * v * b for instances compiles to a * v (2 products) then result * b (2 products)
first needs 3 products while the second needs 4
I'll keep that in mind
https://www.youtube.com/watch?v=Xd4UhJufTx4 at 14:20 for better explanation with benchmarks
Find what common Unity optomizations truly make a difference. In this video I go over a bunch of interesting optimization tips as well and give you my recommendations on each.
Keep your code running fast with as little garbage allocation as possible by learning from these important concepts.
Benchmarks (let me know if you get weird results!):...
i don't understand why that is
did you compare the time of execution with other operations ?
well let's consider the step in the pipeline where I'm generating vertices for a mesh's back face
All I have to do there is
take the original 2D shape's vertices, and then its triangle list as inputs
for each index in the triangle list
grab the vertex
set Z to the object's thickness value
add it to the end of the mesh's vertex data (after doubling the size of the array, obviously)
then add the number of original triangle indices to the index I'm working on, then add that to the end of the original index buffer
So what I end up with is a new mesh, with double the vertices and double the triangles, but now both the front face and back face are represented
I see
So if I'm taking a 2D square, I'll start with 4 verts and 6 indices
So I have to allocate space for 8 verts and 12 indices
but remember that I started out with 4 and 6 respectively
for each of the 4 verts, duplicate it and set its Z to 1 (let's pretend I'm turning a square into a cube)
and store that in the vertiex array at position 4 + n where n is the index of the vert I'm duplicating
Just an offset into the array
so please tell me so that i can dive into your explanation
Why would you need 6 indices for a square ?
Because a square is made up of two triangles, a triangle is made up of three indices, 2 * 3 = 6
Oh yes that makes sense now
by index you mean the position into your big array of triangle vertices
Yeah
great
so there is only 4 verts, but 6 indicies since some verts are shared by both triangles
yes
the order matters to
I have to duplicate the verts but change the Z values of them, then I need to duplicate the indices and point them at the new verts
the winding direction is used to decide what way the triangle faces
most of the execution time is consumed when you connect the new triangles into the overall collider mesh no ?
I'd assume so. But I also imagine that a lot of time would also be spent breaking the original concave 2D shape into the convex ones.
I'd profile it, but I'm blind and the Unity profiler is....not blind-accessible
of its this is for a collider and not a render mesh really i would just try to use only convex shapes to start
Once I get to the point of generating colliders, I'm already dealing with convex shapes
I'm not focusing on the part of this whole algorithm that breaks concave shapes up, I'll eventually jobify it but I'm focusing on the part that's probably way easier to jobify which is extruding out the convex shapes into 3D meshes
Actually blind. Still have enough vision left to do most things but
rely on a screen reader to read anything more than a word or two at a time, and I have the windows magnifier at 1500% zoom
not 150%
1500
Wow mad respect for using unity in yout situation
but I've been writing code for almost my whole life, and doing gamedev pretty much the entire time, and I don't intend on stopping
ah so the profiler is brutal since its like 99% graphs
yeahhh
do you have colleagues who can look at your profiler results ? If no I can try helping you in a shared video or something
does most of unity work well with screen readers?
i know accessibility is sadly pretty terrible for a lot of modern applications, like heard lots of complaints about slack for example and screen readers
it is the worst piece of software ever for screen reader support actually, but I have my ways
Wait do you use text to speech then?
I'm familiar enough with Unity's layout that, as long as they don't do a massive overhaul, I can navigate just by muscle memory
when I'm reading the console, I'll copy the text out of it and into a discord channel so I can right-click on it and hit "speak message"
that's how I read stacktraces now
Oh god the horror of hearing text to speech of a full stack trace
I don't read the full one
Only the first 4 lines
I get the error message and then the first few entries in the call stack, usually by then I've already hit my own code
are there applications that zoom in on some window in real time ? like Powertoy's Crop and Lock but with a zoom
oh nice
but funny you ask, when I'm playing a game and I need to see the minimap, I just set up an OBS scene that captures the monitor I'm playing the game on....but zoom really far into the part of the screen with the minimap, then put the scene into fullscreen preview mode on another monitor
so the GTA V minimap for example takes up my entire left monitor
I also wrote my own plugin for rider that lets me highlight code and send it to a text-to-speech voice, and that's why I'll never write anything outside of C# because I'm so familiar with the language that I don't need to hear most of the syntax to understand what a piece of code's doing
Can navigate based on color and indentation
I can tell the difference between
thing == stuff
and
thing != stuff
even though the voice just says "thing equals stuff" in both cases, because there's a subtle pause when it tries to read "thing != stuff"
Nope, it kinda relies on a specific exe file being placed in a specific spot on my computer so
it's
not portable
that's unlucky
all that exe file does is take in the text to be read via standard input, and send it to a .NET 3 SpeechSynthesizer
it's a bodge
but it works
and I'm not changing it
because I hate kotlin and gradle
lol ok ok
ugh gradle, why you cussing
dont totally hate Kotlin will take it over most other JVM langauges but well i just rather not touch the JVM in the first place
C# and .Net is just a better Java and runtime
and other places where java is used alot like backends yeah i am just going to use something like Go instead
Thing that annoys me about Java is that it's actually a federal crime to have two classes in a single file. Obviously in most cases that's not desirable even in C#, but while i'm prototyping something......
why it depends on the purpose of the class, i often have multiple classes or structs per file
dont talk to me about java
generally one of them is a system of some sort and the rest are the data structures it uses
though generally its structs in that case
Usually as I'm building out a system, I'll start by writing it all in one file to get my ideas out and then I'll split the file up into individual classes
but in java your code just won't compile if you have more than one class in a .java file (except for nested classes)
my first course in my CS studies what a java project. I've maintained hatred towards the language ever since
though java both not giving you a value type like a C# struct or giving direct control of pass by ref pass by value sucks
I did C++ in school, I don't like C++'s standard libs but it's useful to know for C#
sometimes ya just gotta be a lil unsafe
and then there's VB
where arrays are accessed using parentheses
I love calling my arrays as if they're functions
and booleans take 2 bytes
C++ standard lib is always weird, its like a totally different langauge based on who you are writing it for
like every studio i worked at that uses C++ pretty much bans the use of certain parts of it
C++ filesystem paths use the divide operator for combining paths together
it looks so weird
or more or less made a whole DSL in it with macros
unreal enters the chat
yeah not a fan of how much operator overloading has been abused in C++
it just get muddies up intent and makes code harder to read without inspecting what all the ops do for a given type
UCLASS(Blueprintable)
class UThing : public UObject
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintReadWrite, EditAnywhere)
int thing = 4;
public:
UFUNCTION(BlueprintCallable, BlueprintPure)
int GetThing();
};
okay that's not so bad
yup
most of it is doing attribute like things
but it can make for some terrible looking stack traces
and some nasty errors if you screw up one of the macros or, god forbid, any of the generated code/headers from UHT and UBT get corrupt
wait do all fields require an attribute like the above in unreal ?
Depends
UPROPERTY() is like [SerializeField] in Unity, except that it's mandatory even for public fields. It allows the field to be reflected, serialized, and memory-managed if it's a pointer type
I see
it also lets you control how the property is able to be used in editor property views and in Blueprint
It's not too hard once you learn it tbh
except that it's mandatory even for public fields
really i would have prefered if unity did not do the serilzied by defualt for public thing
Yeah it still sounds okay
felt it should have always been explict
so would I
a lot of beginner Unity tutorials don't teach SerializeField
it's useful when you're trying stuff, just being able to write it as public
and just have you put public fields everywhere so you can access them via inspector
but in an actual codebase, this is never ever what you want
though i kinda agree with you
It may be useful, but it's not good to get into the habbit of doing and honestly it doesn't take much time to add a SerializeField or expose the private field via a public property. We have code completions now, you don't need to type it by hand
yeah I agree, I have a code snippet that does this, and I always write the SerializeField attribute instead of the public keyword when I only need to set the field in the inspector
but if I didn't have the code snippet, I thing I would often just write public
no snippet for me auto complete is enough, though i tend to do it inline
Apparently saying the word "anyway" is bad?
ah it would not let me gif, well you know i was going to toss the Jeremy Clarkson "On no, anyways"
nice one haha
Anyway... I was gonna ask one more jobs question
Let's say I have a NativeArray<Vector3> as an input where each element is a triangle.
And I have a NativeArray<float> as the output, it's one element.
I wanna do some math on each element in the input, with an IJobParallelFor, and I'd like to add the result of that math for each element up into the single float element in the output array.
Like maybe I'm calculating the area of each triangle in parallel then summing it all up as the result. How would I do this such that the result is accurate and threads aren't stepping over each others' toes?
i'm not familiar with unity's job system (although I intend to dig into into very soon), but it sound like you should
divide your array into slices of this array (index 0 to n-1, n to 2n -1, ...) and give the responsibility of each sub-array to a thread
can't you do this with the job system
yeah i have not dug into it much yet, really the only concurrent thing i do, i just manually made my own thread and task scheduler for
Wonder if it'd just be better to do the calculations inside the job but then sum them all up on the main thread when the worl's complete
Bunch of float+float operations in a sequential array should be pretty cachable
at least I'd assume so
Or I could even break the summing up into its own long-running job and wait for that to complete. That way it's not forced onto the main thread when there's theoretically a dormant worker thread that could be doing it.
or a 3rd job with depedencies on the other 2
I don't think you can work with a MeshCollider or a Mesh in the job system, at least...I haven't tried
But if even updating the colliders could be parallelized then man
this is gonna fly
especially if ya throw a threadripper at the game
yeah not sure if you can, am like 99.9% sure you can only deal with MeshCollider in the main thread
hmm would assume the same for Mesh as well, it is a reference type and has lots of arrays in it
At least it can take a NativeArray fo the vertex data
and supposedly can for triangle data as well but I haven't figured it out
Is it true that switch cases can't use variables as their condition? It HAS to be a constant? No way around that? I find it hard to believe, since I thought that a switch case was basically supposed to be a more powerful form of an if statement.
would assume they are referring to the cases not the condition
would be 100% pointless if it was the condition
oh lol yeah that makes much more sense
but yeah the cases have to be constant, think that also holds try for pattern matching as well. though for pattern matching you can do more complex comparisons and do stuff based on the shape of the data
I've been following this tutorial to try and add squash and stretch functions to my buttons and other elements:
However, when I try to call the coroutines, I get weird behaviour. For one thing, Event Trigger component's OnPointerEnter and OnPointerExit are getting called repeatedly and I'm not sure why since there's no raycast target that should be interceptting them (text one is disabled, image is enabled). For the button's OnClick event, it seems to work fine. Except that the shrinking seems to disappear down to zero instead of back to default size when I have "reverse" toggled. This occurs whether calling Shrink, OneShot, or the original coroutine, which suggests I messed up somewhere, but I'm not sure where.
Maybe someone could try to replicate this with the script I have by attaching it to a button. I thought I was fairly careful, but I guess not.
Adding some squash and stretch to your GameObjects can really make them come alive. All you need is a bit of code in Unity! Let's learn how!
This script can be attached to 3D objects, 2D sprites and UI elements without any changes needed. It's highly customizable and offers features like forward and backwards playing of the animation, percentag...
Maybe start from asking in #💻┃code-beginner
This really doesn't seem like an advanced issue.
il remove it thx
I think the two coroutine will play at the same time if you dont stop it
so wait for grow coroutine to finish and start shrink one
For anyone reading into the the Tooltip Text Injector from yesterday, I did manage to find a solution.
Open to anyone: https://github.com/JBWD/Unity-Tooltip-FormattedText
Hey guys, getting this error when I try to run my WebGL game on Itch.io but I don't get the error on desktop browsers. Same thing for all apps.
Blocked a frame with origin “https://MYITCHACCOUNT.itch.io” from accessing a frame with origini “https://html-classic.itch.io” Protocols, domains, and ports must match.
Anyone have any ideas?
Classic CORS misconfiguration
That is what I'm gathering. I am new to web. Usually I work on mobile / vr. Where should I look to fix that issue?
You need your web server to spit out a CORS header i.e. Access-Control-Allow-Origin including the other domain as an allowed domain:
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing#Simple_request_example
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be accessed from another domain outside the domain from which the first resource was served.
A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos. Certain "cross-domain" requests, notably Ajax requests, are ...
They said they published on itch
Ok Thanks I will look into that any idea why it would work on desktop but not mobile?
One would presume you're doing something weird with web requests
This app is webgl build published to itch yea
I understand that something may be misconfigured. I'm not the only dev on this project. But it runs on desktop but not mobile. So I'm confused as to why that is
That would lead me to believe it's configured fine but I may be missing some setting somewhere or something.
Well it's almost certainly the web browser doing the actual blocking/disallowing here.
So presumably a difference in policy in the browsers
Open browser dev tool, go to network tab, refresh the page, look at which request errored due to CORS.
Ok I'm doing that now.
How does "Find Reference In Scene" actually work? Because it's showing a bunch of GameObjects in the scene that very evidently don't reference the asset.
Is there a version of ref: that finds GameObjects and Components in Scene that just have the asset directly (Unity 2019)
not a code question, certainly not advanced so post in the correct channel in future but..
I think what you want is search t:asset in the hierarchy
It looks like it's impossible to limit mouse movement into a circle. You can lock it or not lock it but other options don't exist 😭
by system call or just display the cursor inside a circle
Have the actual cursor and a dummy cursor, the dummy cursor moves based on the cursors delta and it’s locked inside the circle, the actual cursor is set to invisible
You can use cursor warping in the new input system for this.
I did it guys!!! I multi-threaded one part of my game's collision gen code and, although the performance hasn't gotten substantially better (since there's still one huge part of it being done on the main thread), there has been a slight improvement
ahah that is nice to hear
did you try my suggestion about the order of the variables
None of the code I refactored so far does any vector math rn so it wasn't needed
I'll bet the next part I jobify will though
I see
Though there is at least one part of the code where I can move a floating-point multiplication to a later job, to save a huge amount of multiply operations. Just haven't done it yet
It's where I multiply a triangle's volume by the object's mass. I should be doing this after summing all of the submesh volumes, that'll save me potentially thousands of multiply ops
I also may be able to get a huge gain by using NativeArrays to store the vertex and triangle data for the source 2D concave shape, and have the convex shape splitting code return me a bunch of NativeSlices. This'll potentially save me a bunch of NativeArray allocations and deallocations, and maybe even some GC hits
Either way I'm having a lot of fun
Being able to talk everything out here yesterday really helped
I'm not really familiar with NativeArray, could you explain why you're using them instead of regular c# []
if I'm being honest, the Unity job system kinda reminds me of SPU cores on the PlayStation 3. Where it takes a bit of skill to work with them correctly, and the kinds of workloads you can do with them is limited, but the potential is really huge if used correctly
Because you must use NativeArray when using jobs
Jobs don't support C# managed types
Oh okay
Also if I remember correctly, yesterday you mentioned that you needed to work with the global shape every frame, but do you think you could cut it down into several pieces and only work on the area the player is painting on ?
I have somewhat of a complicated problem >.> I think
and re-compute this area after some delay
When I said that, I was referring to what the player was currently painting on
I can try helping you
Oh so you do cut down the overall shape
Imagin you want a ball to bounce in the air... or off a glass table. the table is square
in fact the table could be any shape, it can even have hills on it
It's just that the player could be painting a really huge shape, and the bigger the shape they're painting into the world, the more the framerate drops as more and more collision meshes need to be generated. This also depends on the brush they're using, larger brushes with less vertices mean less computation
but you want to be able to place a shape on the floor under the table and have the ball only bounce in that area above the table.... but without walls
so its like a nav mesh in 2d, projecting itself in a way that an object in 3d is limited to that 2d space
but for various reasons we don't want to project walls up, not even invisible walls
so if the player draws a straight line of 100 meters, you'll compute the overall line each frame ?
we got it working but the problem is you cant slide along those walls it simply decides "nope, you cant go here" and you loose your momentum instead of deflecting or sliding along the invisible barrier
Yeah. But if they're drawing a straight line with a square brush, the framerate will never drop because the shape will always be 4 verts, 2 tris, and one collision mesh
It's when you involve circle brushes and/or anything more than a straight line where things get more complex
maybe you can add a force that forces your object to the center of the tables to ensure the ball doesn't leave the area over the table
its not always a bouncy ball
sometimes its a hackey sack so it would slide rather than repel
it's actually none of these things but NDA prevents me from describing the actual problem
we tried casting a ray sweep down to triangulate the edge but that isn't returning values for some reason, we tried racasting a sphere, but it cant either...
i think you can try dividing your shape when it grows big no ? for instance if the player draws a 100m line, you can cut it in two and only compute the last 50m drawn from now on (obviously it would be much more complicated than that but technically do you have to use the whole shape ?)
NDA
A standard-issue legal contract that takes away a lot of things and gives little in return.
Cyberpunk 2077
Love this.
I don't see how the object not being a ball changes my option
Unfortunately I just don't have the skill to be able to break up the shape data like that, but since this is something you only deal with when creating levels I think it's fine to just throw multithreading at the issue
Only need to recompute colliders when the brush moves, and once more when you let go of the mouse and finalize the object
What do you mean this is something you only deal with when creating levels, isn't the painting a core feature of your gameplay ?
Nope, it's a level editor feature :)
okay so normally if you jump into a wall it checks the normal and you can possibly slide, depending on the friction material on the wall/controller
but in our case we don't want have a material, we want nothing, so sometimes it acts like a soild, sometimes it acts like a ribber, sometimes it acts like a wind volume
to control the external environment we wanted to use a 2d shape under the level to establish a boundary, once you get outside the boundary apply the desiered effect
but we need to be able to calculate the relation of the boundary angle to the vector of the object so in the case it deflects or slides, it does it relationally to the angle of the edge
but since the only way to confine the object above the 2d space is to ray cast down... we have only a true or false as our data point
if you're satisfied with your framerate, I don't see a reason to change your approach, but if the user can draw an "infinitely big" shape, the execution time would keep increasing so it may eventually break the game
@spiral grotto why can't you use invisible walls ?
There will always be a point at which the shape becomes too complex to maintain a stable framerate, but that'll depend on the computer. If this were a console game I'd limit vertex counts like LittleBigPlanet does, but once collisions have been computed they get cached for the life time of the level
I may even be able to trade disk space for computation time by storing the cached collision meshes in the save file
because we don't want them to be "solid" and also our character controller is.... unorthodox
Do you absolutely need to use a single mesh ? If not I don't see why the following would be true There will always be a point at which the shape becomes too complex to maintain a stable framerate
also imagine the player can draw their own shape and have it become the allowed area
they can be solid to the object but non-existent to the character
i know i mean we want to use it as a boundary that is only sometimes a collider and sometimes not a collider, sometimes its a trigger and the depth beyond the surface matters
these settings can be changed via script, although your simulations seems really curious since no real-world object's physics behave like this
I guess superliminal should be a crime then >.>
I wonder why AnimationCurve is very efficient and faster than the usual .Lerp
Ah! right after I typed that, just remembered that all .Lerps are clamped, proly that
except LerpUnclamped!
yeah
Yes. Remember what I said yesterday, that you're not actually brushing a mesh into the scene
You're brushing a 2D shape, which is represented as a list of paths that get extrudd into a mesh as you brush
In fact, most of the actual brushing is handled by a third-party script
it can be edited but if ya saw the code for it, you'll understand why me and my blind-ass self ain't editing it :)
Hi guys. I'm trying to make a fortnite build system and it all works except for the preview object.
I asked #archived-code-general for advice and so far they couldn't seam to figure out why the preview build only works on a platform and not reset to the normal position
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.
any ideas?
I've given you ideas. You need to reset the position if it becomes too far away
Do as many comparisons as you like, as long as it works
Hello not sure if this the right channel (ist kind of a math question i guess); Consider I have a grid which looks like this:
| 1 | 2 | 3 | 1 | 2 | 3 |
| 1 | ? | ? | ? | ? | 3 |
| 5 | ? | ? | ? | ? | 3 |
| 1 | ? | ? | ? | ? | 3 |
| 2 | ? | ? | ? | ? | 3 |
| 1 | 2 | 3 | 1 | 2 | 3 |
As you can see i know all values along the edges, i know want to find the values in the middle by lerping from the sides; I managed to lerp East to West or North to South but never from all sides at the same time..
On the picture you can see what i need it for the y coordinates of grey meshes vertices is the grid from above; as you can see it already has the correct y-values for all vertices along the edges. Any help; Ideas or useful links appreciated Thanks in advance 🙂
that solves the distance problem while standing on a platform but it won't work when on the ground and the player would have no corners to check
So how are you building the first platform from the ground up?
First, write your 16 equations.
Then, create a 16x16 matrix.
Then use any method to solve the equation system. (I did it once, but I do not have the code with me, it is pretty straight forward if you understand Gaussian Elimination Method) (Take the largest row, swap it with the current row, divide the number then substract others row)
Alternatively, you could calculate the average of all your border
Fill the number with the average
Recalculate the average of each number till it stabilized. (I believe it will always converge, but I might be wrong)
planning for a project where level+gameplay designers aren't familiar with c#...
is visual scripting non-shit now?
there is no fucking auto-convert value!! wow ok i have my answer
I dont remember it being shit, but it's just not something where I've got time to use for
so if you got the devs who are going to be creating systems and tools then sure, why not
it was shit when they acquired it from that asset store dev, then they said they'd implement his new engine to gain some speed
what i'm saying is unfinished node graph with sluggish performance and inconsistent behavior, that's bound to piss everyone off on the team
Performance is terrible, however it is not made for performance but for convenience. It is useable for sure, but usually a couple of Component/SerializeReference can do the job. For more advanced user you can even go with Unity event.
are you saying it's even slower than unity event?
ok, so they didn't update the backend
Yes it is.
Does anyone know if DynamicObject and tryInvoke work with Unity?
Only with Mono. IL2CPP does not support dynamic
From my code I set BuildTransformpoint() on a button with the new input system. I then press the button to instantiate a build in the muzzle transform when the player is on the ground. If the player is on a build or looking at a build the player would then instantiate a build in a point on that build.
Hi! Any idea who can I delete a user account from cloud code js?
Also note that dynamic is terribly slow.
Does anyone know when assembly definition constraints get resolved, especially those used in packages? I have a long standing issue with our build tools where define constraints don't seem to be taking effect when invoking BuildPlayer and I'm not sure if it's something to report, if I'm doing something wrong, or if it is intended.
do you use the parameters in the build function ?
I usually make sure that no parameters is set and use this. Because the https://docs.unity3d.com/ScriptReference/PlayerSettings.SetScriptingDefineSymbols.html did not work correctly for a while. Do not know if it is still the case.
Neither work. I also normally use the extraScriptingDefines to avoid having platform specific defines from being committed to the repo.
It seems like the defines in package assemblies don't see the change at all when setting the define just before the build.
Have you try to trigger an AssetDabase refresh ? Or maybe something like EditorUtility.RequestScriptReload (It is Async)
That wouldn't be possible when using the extraScriptingDefines since it gets set internally by unity at some point on the BuildPlayer call.
I'd like to avoid async since this is going through build automation and I'd be worried about unity closing while waiting. Not something I've tried working around, though id like to avoid the effort.
Hi everyone, I want to make a conveyor belt system where the objects traverse along the conveyors. However I want to have a really high item cap. Should I have a script on each item to create a job for the item movement or should I have an item manager script which does a foreach loop and adds a job for each item that way. Which would be quicker?
define "high item cap"
Possibly between 10-100k
If you're trying to make Factorio you'll probably want to read their devlogs... and build the game in C instead of Unity
you wont be doing that with gameobjects
What would you suggest then
at the very least you'll want to be looking into the job system and/or ECS
I want it 3D
what praetor said
That makes what I said even more true
this is a very difficult engineering task
So entity component system yes
not for the faint of heart or a novice
you basically have to keep the simulation totally separate from unity and use unity just to render what the player can see
Oof, good luck me then
its a fundamentally different approach than what unity invites you to do with its gameobjects based architecture
Btw I did build something like this:
https://www.youtube.com/watch?v=ve0rtD7KUNQ
The rendering is the most annoying part. I used compute shaders
Just playing around with Cinemachine Dolly Cart in my untitled factory builder game. The camera movement is pretty janky, I know!
Ahh thank you I’ll have a look. Because at the moment I’m lerping and slerping each object
Well there's going to be lots of interpolation going on - but individual GameObjects for these things is a complete nonstarter
So if you were making this were would you start
At some point I need to revive this project 😵💫
really if you have to ask, you'll not get there
the answer is basically: learn how to figure out hard problems
and you do that by learning CS fundamentals
and you do that by reading books
and trying stuff for 5 - 10 years
Let’s not start with you’ll not get there that’s a bad mindset. I’m about to finish CS A level and going uni this year so I’m defo passionate for it. I just need to know what to look at. I’m not in any rush
then do your CS degree, then apply what you learned
there is no simple answer to your question
there is no "start here"
you gotta break down your problem, research the parts, and try to put them together
So I need to work out how to render multiple object translations whilst also keeping my FPS stable not by using game objects? The only ways I can think of is the job system. And ECS
you need to get to a point where you don't feel the need to use tools that someone else made to solve your particular problem. you dont need Entities and Jobs specifically.
So I just need to get to a point where I know enough of the systems in Unity and C# to problem solve without looking at anyone else’s solutions or advice? So basically reading and learning as much as I can then tackling the problem
it is the reality of it. CS A level i assume is a highschool course, this is a nice start before university but honestly is almost equivalent to nothing when it comes to experience.
I think you are massively overscaling your project. Start with something simpler
the problem you have is purely theoretical and derives from how computers work, Entites is one way to leverage a certain quirk of CPUs, Jobs are another that give you training wheels to do multi threading, but your problem is not solved by using any of these things, its solved by understanding why you have a problem.
So could I start by trying to build a smaller system which is similar to the one I want to eventually get too. And then attempting to solve it without any help. The problem I have is FPS and rendering so many object transformations at once
nobody has yet solved your problem while targeting unity, all games that so far have had massive simulated entity count (factorio & co.) used custom simulation engines that only used the "game engine" to render a tiny view into that full sim
You cannot make a smaller system (lets say 1k objects) then apply it to 100k. It will not run
also all these games make very drastic concession in their game design to enable that entity count, this is something to be aware of
it might run at 0.01% the FPS
thats what i consider not running, aka no one will be able to play
indeed
I want to make the game right and not do some half bothered attempt at it which is why I’m asking so many questions. I’ve been looking at satisfactory as an example and it baffles me how they have so many objects but they are using UE5 not Unity
has nothing to do with UE, it could be done with unity just as well
also, for the 3rd time, the simulation is not run in the game engine or with any of its types, it is fully custom, 100% separate
the engine just shows you the 500 items you can see from your players POV
there is no off-screen conveyor that has items lerping along its surface
its all trickery
Oh I get it now sorry, I’m a little slow. So I need to learn how to create custom simulators to handle large amounts translations that aren’t seen by the user so it saves rendering and then implement that with any game engine of my choice
kinda, yes
Loosely, I’m no expert by any means but I’m working on it
mind that it is not trivial to manage that
took all these games a really long time to make it work
I don’t doubt that and as a solo dev it’s going to be way harder
and unity has been messing around with a generic solution to it (Entities) for almost a decade now
nobody has yet proven that a generic solution even exists and works (i.e. maintain productivity while getting increased performance)
So what I’m trying to do is possible yet impossible. Like Schrödingers cat
yes
you should be optimistic that you can do it theoretically (enough time, money, motivation) but very respectful of the scale of the problem and very sceptical about anything you do in the short term
So in other words I need to not screw up now so I don’t have a major screw up in future
naturally, you don't know what you dont know yet, so you might not even realize how difficult your project really is
That’s what I’m afraid of.
no, you need to screw up, to learn. learn fundamentals, they are all you need. and continue trying to solve the problem, make prototypes, but dont expect your first 10 attempts to succeed.
if you don't fail, you will not learn.
this is impossible to avoid especially as a new solo dev. One day you might realize you want a new feature, want to remove a feature, maybe try to implement a better algorithm. Then your code must change. The goal of clean code is that you have to change as little as possible
I’m not expecting my first 100 to succeed. I just need to find a starting point. I can sort of code in C# but not higher level concepts.
But I have to fail at the same time to get better
while you will always get the advice to start small, and that is good advice, its also important to have a long term goal, a dream, something that stays outside your grasp, especially when you're new to the whole thing
Fail is a loose term here, failing can be having to scrap code because its not up to your standards. It is not like unity pops up with a "You lose" screen randomly
Fail can also mean scraping the whole project
Yeah it’s just a stab in the heart when you spend hours on something and it doesn’t work
I scrapped my 5 month project a few months ago and felt so much better 😆
Good for you I guess lol
i overscaled what i should be making, and thus it had to go
If that made you happier
scrapping projects is the only option for 99.999999% of solo developers
so, you should get a friend to help you
that increases your success rate 1000x
Couldn’t agree more, but all my mates at college are stupid
you need to figrue out how to not think that way
other people are not stupid, they just want different things
well, if you get funding you don't scrap, you do a death march 😄
My mate was in a CS course for 1.5 years and still can’t write an if statement
he probably isnt in the right field then
Yeah he ditched a while back
he might be a great poet or carpenter
But he’s happy now so that’s all that matters
mind though, there are people who are incompetent (in a given task/role) and you need to recognize them and not do projects with them
Also true
capable teams are very rare
But there are capable teams and that’s all that matters
most orgs use processes than only require mediocre/passably skilled workers
maybe, but i'd expect there to be one super-monkey in each team who cleans up all the shit to get it to pass certification
Anyway I must go, but thanks so much for the advice. Will defo get reading. It is half 1 in the morning over in UK so probably start tomorrow lol. Night everyone
@lament salmon , hey man, been some time. I have had to do some other things but now I've come back to the cover baking thing. Sorry for the ping but, I'm just completely unable to figure out how you used the cover data to find an optimal point of cover to which the enemy could safely move. I've got a bunch of the baking figured out, but yeah, I've just been thinking about how to do this for a really long time now. My best ideas have been centralized around starting the search for an optimal point at the player and expanding outwards, checking every point in a radius, until a match is found, but that wouldn't solve the safe travel problem.
You can do some simple visibility check raycasts (from points along the path -> to the opponent) to get a score for the route's safety
I'm still experimenting with that myself
Performance is a concern since multiple paths would have to be checked for each query
A lightweight option is to score it by how much you have to move towards the enemy
Or combine those two
Do you have problems with other things apart from the safe travel?
And I don't mind the pings - it's an interesting subject
Using NavMesh.Raycast instead of Physics.Raycast could be more performant, but obviously not as accurate since it only checks the ground
No, not really. At least not yet. I haven't done a lot since I started thinking about how I would actually use the data in finding the point. But thanks, I think I got an idea from this!
Hi everyone... I've been quite bothered by a little something in Unity for a while now, specifically with the size of some box helps created in a window. I need this right box help to automatically adjust to the size of the left box help for aesthetic reasons, but I don't know why the heck it's getting so complicated for me... I've asked about this in this forum before, but we couldn't solve the prob... Any ideas? Here's the code for both box helps:```csharp
private void DrawLeftBox(JsonData jsonData)
{
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
string elementName = jsonData.Name;
GUILayout.Space(7.5f);
GUILayout.Label(elementName, GUIStyles.GetFontStyle(true, "#3498db"));
GUILayout.Space(-7.5f);
EditorGUILayout.LabelField(string.Empty, GUI.skin.horizontalSlider);
GUILayout.Space(5f);
string newName = EditorGUILayout.TextField("Class Name:", elementName);
if (newName != elementName)
{
elementName = newName;
}
showOptions[1] = EditorGUILayout.Toggle("Something Else", showOptions[1]);
showOptions[2] = EditorGUILayout.Toggle("Something Else", showOptions[2]);
DrawMultipleInstancesOptions();
EditorGUILayout.EndVertical();
}
private void DrawRightBox()
{
EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.Height(EditorGUIUtility.singleLineHeight * 8), GUILayout.Width(EditorGUIUtility.currentViewWidth * 0.25f));
GUILayout.Space(2);
GUI.backgroundColor = new Color(46f / 255f, 204f / 255f, 113f / 255f);
propertyAdditionMenu.Draw();
GUILayout.Space(15);
GUI.backgroundColor = Color.white;
EditorGUILayout.EndVertical();
}```
This should be in #📲┃ui-ux, but is there a reason you're not using UI Toolkit?
Actually it should be in #↕️┃editor-extensions
oh yeah sry
but you are right, should be using UIToolkit not IMGUI
To answer this:
starting the search for an optimal point at the player and expanding outwards
Yeah that's what I currently do, I first try with a small radius (10-20meters) and if it fails or the score is too low I expand the radius and try again
Might want some spatial partitioning (octree or just chunks) for optimizing the search, but that can come later
Do you consider the players shooting range in your calculations?
Not really at the moment, since every gun can be deadly at a long distance as it's aiming for realism
But I will likely implement that later, so that a player with a sniper rifle will seek farther firing positions than one with a pistol
It's a very tricky one to solve optimally
I got some ideas for it but we'll see how it goes
This gets very complex if the map has any verticality in it
There's already a heuristic for 'distance to enemy' so I could just have a higher weight for that if you have a long-range weapon
Oh, I just use it because I like the way it looks in unity... Most of the assets I've used do with IMGUI, and that's why I'm used to it. I think that if I used UI toolkit (besides I would have to start learning it) I would lose a little bit of the essence of how windows look in unity. A few time ago @upbeat path suggested me to learn unity toolkit, but i've finally decided to stay with IMGUI, atleast for the moment
UI toolkit is almost indistinguishable from IMGUI, and a lot easier to make more complex things with
also you can customize it to look however you want
I'd wager a guess that IMGUI is going to be deprecated in favour of UIT at some point in the future as well, so you could avoid some potential pain by jumping on UIT earlier (though there's pain in that, too). It wouldn't make sense for both systems to survive long term.
Certainly when you are trying to do complex placement of items, UIToolkit is far superior and much easier to use
I'll definetly try it...
So... do you know wich element is the best to add and image like this one?
a label or a visual element?
yeah
No I meant which part of the UI
So I'm trying to implement Jobs for the first time but I'm pretty stumped. Here is one of the least complex methods that I want to implement and it would be great to run each row in parallel but I'm not able to call scripts from outside of the job so I feel like it wouldn't make a large difference?
private void calculateVertices() {
Vector3[] vertices = new Vector3[WorldGenerator.Instance.chunk_vertex_count];
data.local_noise = new float[WorldGenerator.Instance.chunk_vertex_length, WorldGenerator.Instance.chunk_vertex_length];
data.biomes = new Biome[WorldGenerator.Instance.chunk_vertex_length, WorldGenerator.Instance.chunk_vertex_length];
int count = 0;
for(int i = 0; i < WorldGenerator.Instance.chunk_vertex_length; i++) {
for(int j = 0; j < WorldGenerator.Instance.chunk_vertex_length; j++) {
// The local positions of the vertex
float x = i * WorldGenerator.Instance.chunk_step_size;
float z = j * WorldGenerator.Instance.chunk_step_size;
// The global positions of the vertex
float x_global = x + data.offset.x;
float z_global = z + data.offset.z;
float y = applyGlobalNoise(x_global, z_global);
// Get biome at position + apply noise
Biome biome = WorldGenerator.Instance.biome_manager.getBiomeAtPoint(x_global, z_global);
float biome_noise = biome.calculateNoiseAtPoint(x_global, z_global);
y += biome_noise;
// Save useful data
data.local_noise[i, j] = biome_noise;
data.biomes[i, j] = biome;
// Local position of vertex
Vector3 position = new Vector3(x, y, z);
// Apply vertex
vertices[count] = position;
count++;
}
}
data.vertices = vertices;
}
Can someone explain what the frick multiplying a Color by a float actually does? Because in this image, the word "Admin" is meant to be an orange color.
Basically I'm taking yellow (#ffff00ff), multiplying it by 0.5f, and that's the color I'm using.
In other game frameworks/engines, this usually would result in a 50% translucent version of the color but I have no idea what Unity's trying to do here or what the actual use case for this is in code
If you want 50% translucent but the same brightness, only multiply the alpha portion
I linked it to you?
Or do you mean an operator that only scales the Alpha? It doesn't exist, make an extension method
Yeah but github + dark reader doesn't highlight things very well and I still can't find it
I did link directly to the line of code
and I still can't find it D:
welcome to me being blind
Have the same issue any time someone links me to a discord message
It's line 103
I feel like that's not how I'd implement what they're trying to do tbh
hey guys , i'm wondering if Neon intrinsics is supported in my android system how can I check if Avx2 available and the the MMX, SSE, SSE2, SSE3, and SSSE3 extensions at runtime ?
found out that I can't use
using Unity.Burst.Intrinsics;
before declearing as static using static Unity.Burst.Intrinsics.Arm.Neon;
what would be the optimal solution to anchoring a point to a specific region of a perspective camera using a varying FOV? here's a couple photos based on what we have. the gun camera has an FOV of 75, hence when I make the normal camera FOV 75, it is positioned properly. however, it gets displaced because of the gun cam still being 75, thus changing the position of the origin of the bullet trail in the perspective cam. im assuming i have to use tan in this, but im not sure how. any insight?
75 fov with 75 fov on gun cam
120 FOV on main cam with 75 fov on gun cam
Hello, would just like to check if anyone has worked on a project where Unity was subscribed to a RabbitMQ broker? I am told that Unity supports RabbitMQ client as of .NET support for 4.0 but I would just like to check to be sure. I am using 2021.3.xx for my Unity version.
Curious what the use case for this would be as opposed to proxying through a web service.
Hi all,
Is there really no easy way to deal with .webp images?
I download a .webp image to the disk at runtime and wanna display it in unity UI.
I can just save the same data and rename the file to .png, but this leads to invalid bytes i suppose, since texture2D.LoadImage() fails then
This is what i used:
if (File.Exists(filePath)){
bytes = File.ReadAllBytes(filePath);
UnityEngine.Debug.Log("Bytes: " + bytes.Length);
texture2D = new Texture2D(2, 2); // Create new "empty" texture
if (texture2D.LoadImage(bytes)) // Load the imagedata into the texture (size is set automatically)
return texture2D;
else
{
UnityEngine.Debug.LogError("img couldnt be loaded to Texture2D");
}
}
else
{
UnityEngine.Debug.LogError("file does not exist");
}
Has anyone found a way to read the data from webp files without using any of these half-implemented experimental github repos?
Ty!
Unity doesn't support webp images out of the box so you will indeed need to convert the data to a supported format before displaying in Unity. Simply renaming the file won't do anything productive.
Thanks for your reply. You're right of course, but it also didn't really find anything on how i would possibly convert these without paid c# libraries. I was thinking this is a common thing since webp is pretty popular
Is this one of the half-implemented experimental GitHub repos you tried?
https://github.com/netpyoung/unity.webp
It's quite new, Unity may eventually add support for it.
Yes but this already throws errors upon importing
hopefully, though in forums it's been already requested since 2013 so i doubt it
sure but it wasn't very popular in 2013
Fair enough
I think it's common for web servers to provide more than one version of an image for compatibility with older browsers. Are you sure the server you're downloading from does not also host PNG or JPEG versions?
That's a good idea. Thank you.
(Though i still think there should be more support for webp, but hey i'll take a small victory if i can find one)
I've shipped a couple games with webp support in Unity. I've used a couple different implementations
~~The most recent one used this and we didn't have any issues: https://github.com/netpyoung/unity.webp~~ Just saw you said it imports with errors. Do you know what errors you are getting? I didn't have that experience when using it
any ideas for this?
Thanks for the feedback. It's good to know that someone successfully used it. It could have been something on my end then. @sage radish was actually correct with his assumption. I only checked for png or jpg as fallback, but it turned out it our fallback is jpeg. With that i can completely ignore all the webp complications. Though now i know that there is a working solution in case i do need webp in the future and i might have judged too quickly. Thank you :)
I'm not on this server too often so if there's any reputation/ thanking system, let me know. You guys were all really helpful
hey devs!! I dunno if this is the correct thread to post this... actually I have been following this tut: https://www.youtube.com/watch?v=_Xx4S-3c57Q&list=PL8K0QjCk8Zmi56rAL7KDjB8aZotCGn4T2&index=3&ab_channel=Flarvain
the thing is that unlike his, my cube wont update the position set in the prefab and will spawn at Vector Zero... why is that happening
Hey All,
Apologies for the unclear audio, I had only noticed how the mic had been set up after recording. I'll make sure it's good again in future videos :)
Hope you're enjoying the series so far i'm having a blast discovering everything netcode for gameobjects has to offer.
If you'd like to support me please consider hitting that subscribe b...
can i draw my own application surface instead of using the built in one
i think you mean splash screen
No
I mean rendering images on a custom app surface
So instead of letting unity to render the sprites, you render them yourself
If I'm understanding you correctly, then yes, you can build a fully custom renderer but it's a bit esoteric. The basic idea is to just do whatever it is you need to do in the fragment shader (similar to if you'd do ray marching). Sebastian Lague on YouTube has a video where he builds a ray tracing renderer in Unity this way.
I don't know if it's what I'd call a "production ready" technique though.
Hm, what do you mean with just resizing the app surface?
Well, imagine a game with black bars on each side (resolution issue)
You wouldn't be able to render text in those black bars
not unless you resize the app surface
I'm not entirely sure I'm following, but the shader would operate in clip space, which are normalized regardless of the resolution of the surface. You'd have to explicitly take the resolution into account during rendering.
Say if you want to maintain a specific aspect ratio, you'd have to know the aspect ratio of the target surface and draw the black bars yourself.
Drawing text outside the surface would require you to draw it at negative values, which I assume you can't
No, the fragment / pixel shader would in fact only be invoked once per visible pixel on the surface being drawn.
So that's what im trying to say
Instead of rendering text inside the yellow box
which is the app surface
Can we scale it up
The black bars remain, but you can now render text at negative values
Well not necessarily negative values but u knnow
Yes, it makes no difference to the pixel shader. You have to explicitly decide what to draw inside of the black bars anyways.
Not a code advanced question, and you need to give us more context than linking a youtube tutorial.. code? scripts? details? etc
I am making a terrain system that generates an island, I am using a modified version of sebastian lague's Terrain generation project. I am also using a shader to texture based on height. How could I make a biome system that will change terrain color, allow for biome based locations and vegetation, and be repeatable so it can be performant over network? DM or @ if you need to see any of my code or other resources