#archived-code-advanced
1 messages · Page 89 of 1
Would fixed update be suitable?
yea most likely
hehe. the dumbest way is often the best.
I should cross-stich this
another one i learned from scars: "when you finish something and you're thinking you're clever, it'll break and you won't be able to debug it" 😂
Here, here 🍻
That’s an accidental leave-behind from when I was playing with different sizes, sorry. When I set all the necessary values to either 256 or 512, it occasionally (but not always) gives me an index out of range error, so I tried increasing the size to no avail.
I’m not at my computer right now, but the shuffle I used essentially loops through every single item in a provided array and swaps it with a randomly-indexed second item.
For shuffle, take a look at: https://en.wikipedia.org/wiki/Fisher–Yates_shuffle
The Fisher–Yates shuffle is an algorithm for shuffling a finite sequence. The algorithm takes a list of all the elements of the sequence, and continually determines the next element in the shuffled sequence by randomly drawing an element from the list until no elements remain. The algorithm produces an unbiased permutation: every permutation is ...
it occasionally (but not always) gives me an index out of range error
I think this is a clue to the second thing I mentioned, youryfbeing negative - I've also noticed you're actually subtracting the modded value instead of the original value
you have:
public static float Perlin(float xCoord, float yCoord)
{
//...
int X = Mathf.FloorToInt(xCoord) & 255, Y = Mathf.FloorToInt(yCoord) & 255;
float xf = xCoord - X, yf = Y - yCoord;
//...
}
this is very wrong- I'd go back and look at the js code again, you've renamed x to xCoord and y to yCoord which is probably why it got mixed up
Alright, I’ll go back over it again and let you know if there’s any issues. Thanks so much for the help and happy holidays :)
Hey so does anyone know how to make a transparent game background so you can see your desktop with the game being click through but being able to interact with UI?
please do ping me if you know how to do it. i really need this
I've replaced my shuffle with Fisher-Yates and fixed the issue you mentioned. Looks slightly more coherent now, but still wrong:
Let me know if there's any code you need me to show.
There seems to be a diagonal pattern of bumps.
this looks a lot better
as for the diagonal pattern it may be worth playing with the scaling, Perlin noise is designed to repeat on an interval. As you can see from the first line perlin(x+255, y+255) will be identical to perlin(x,y), in fact the entire region of x:0..255, y:0..255 is the same as x:255..510, y:255..510 (give or take 1)
Let me increase the size of the permut table and see if that makes it look less repetitive. If it does that's probably the issue.
Alright, that appeared to be what was going on. Thanks for the help :)
no worries - for what it's worth you don't need to use the permutation table at all, any hash that maps an integer to a random but consistent value will (probably) work just fine
but that's deviating a bit from "perlin" noise
One more small thing I'm hoping you can help with. Sorry for the bother :/
I've added in octaves so that it looks more natural, and at a glance, it looks pretty good:
However, from above there are very clear intersecting diagonal patterns:
Might this relate to the offset I gave the x and y coordinates so that they don't end up as integers and return 0? It was a pretty small number (0.05).
Terrain with Wind Zones, can it have colliders/navmesh for ai on dynamic-ground to imagine understand what i mean use dune 3 sandworm (todo heights)
it is not just a graphics effect on shaders, or a procedural mesh, but a terrain that could heave sand/grass that moves with wind with the whole groundheights.
nav meshes are an optimisation technique to reduce the complexity of pathfinding via baking a simplified representation of a nav-space, if your nav space is dynamic, you obviously can't use baking nearly as effectively.
Some 3rd party systems like A* Pathfinding Project give you some tools to modify navmeshes dynamically at runtime, and also offer runtime baking that runs semi-smoothly in separate threads
navmesh can be baked on mesh or also on colliders, and colliders also can be baked for optimisation, if its not static. similar dynamic baking by gpu (checked for batch materials - and here is the big thing to think not 2d matrials, xna had 3d materials )
in principle: if you keep your nav-meshes small (local around the player) and updates relatively infrequent and/or local you can have dynamic navmeshes
Hey so im trying to make a transparent and click through background in unity but also make the ui works so the click through turns off when i have my cursor on UI. But for some reason its neither transparent and neither click through.
this is my code i need help with my finite state machine. the pause and investigate states just dont work
Hey, does anyone know how to properly get the API Compatibility Level in either define symbol or C#?
Because this does not seem to be working for my Assembly Definition
In 2022 and above I can select the editor compatibility level but not on 2021.3LTS and below
so I have a weird question
Say I have a shadergraph texture that is called "MaskMap", and thats it
is there any feasable way to figure out what that map masks, does, or otherwise all from C# automatically? I did not make this shader so say I cant look into it in shadergraph to figure it out myself
What do you mean by "figure it out from C# automatically"?
thinking aout this Im pretty sure its impossible
There are 2 ways you can figure something out:
- see how it works internally and understand the logic(this requires seeing the code or the shader graph)
- empirically see what results different inputs produce and try to figure out the logic from that
So, unless you mean writing an algorithm that does it for you, I don't see how to do it automatically from C#.
yeah I think ill have to write an algo
is there a way for me to reinterpret the shadergraph shaders as a text file?
The answer here might help
https://forum.unity.com/threads/how-to-get-shader-source-code-from-script.1102147/
oooo thanks!!
Hello, I have a code block as follows.
Everything is working correctly but "ConnectionApprovalCallback" is never called, what could be the reason?
NetworkManager.OnClientConnectedCallback += OnClientConnectedCallback;
NetworkManager.OnClientDisconnectCallback += OnClientDisconnectCallback;
NetworkManager.OnServerStarted += OnServerStarted;
NetworkManager.ConnectionApprovalCallback += ApprovalCheck;
NetworkManager.OnTransportFailure += OnTransportFailure;
NetworkManager.OnServerStopped += OnServerStopped;
I'm looping through a meshdataarray to get the diferent arrays of vertices, however for some reason, im getting the same array at each step, what could be a reason for that problem? I know it's that because if instead of getting the array i create my own i dont get problems
MeshGenerationData data = new MeshGenerationData(){
meshInstances = new GenerationInstance[count],
meshDataArray = Mesh.AllocateWritableMeshData(count)
};
for(int i = 0; i < count; i++)
{
Mesh.MeshData meshData = data.meshDataArray[i];
NativeArray<Vertex> meshPoints = meshData.GetVertexData<Vertex>();
//more unrelated stuff
}
Any hope?
how can you get ITilemap? cant find any help online this is my last option is here.
Dont cross post
this is not some easy error you can find online
Cross posting is posting in more than one channel.
It's against the rules
Still no excuse to post the same thing in 3 different channels
sorry but its importanted, unity dont give any good examples to use ITilemap, I've look everywhere
Hey man, sorry for the ping but I have a question. How do you deal with getting the cover angle but separating it from other walls that are a little further away? Currently, I've got a multiplier which looks at the distance between the last raycast and current raycast & determines if the next raycast has got too big of a difference in distance to be considered as part of the cover. This however, as seen in the picture, doesn't get the entire cover for me. I'm wondering, how did you do that?
This however, as seen in the picture, doesn't get the entire cover for me.
Not sure what you mean by that, can you elaborate?
In the case in your screenshot, I would store an angle range which would range from the first (left) to the second last ray, basically ignoring the long/missed raycast from the angle coverage
This is maybe a bit better of an image, you can see that it clearly should be getting that area on the left as well, but it isn't. I'm wondering how you approached getting the cover angle
With the area on the left, do you mean this?
Yeah, that
I'm wonder how you got that entire area
I align the raycast to the normal direction of the edge/cover point
So that the center ray points directly at the wall
Then shoot a fan of rays from left to right, relative to that normal angle
This angle is stored in the cover point when baking
Perpendicular direction of the navmesh edge
Hm, alright. Thanks!
Radar
Does anyone have any tips on modularizing your code? I like to experiment with different options that we can call modes. It would be fair to say that you should make different scripts for each mode, they would essentially be the same scripts with slightly different variations. My current approach as an indie dev has been to assign experimental features to booleans and have conditionals for the modifications, my only concern is the eventual decline of code performance with additional conditionals. For example I'm currently working on a game that handles collisions differently for different game modes, and I imagine those conditionals will start to impact performance. I guess what I'm fishing for is some way of making the script compile in a way that these conditionals are taken as truth that won't change, while still having the freedom to keep the scripts wholeness.
This is basically the poster child use case for interfaces
For example make an ICollisionHandler interface
and when you want to switch mode you can decide which implementation to use. Contrived example:
ICollisionHandler collisionHandler;
void Start() {
if (mode == Mode.Bouncy) {
collisionHandler = new BouncyCollisionHandler();
}
else {
collisionHandler = new StickyCollisionHandler();
}
}```
The interface would have some methods on it that you call elsewhere here - maybe a "HandleCollision" method for example
and each class would have a different implementation of that
Thanks for the informative answer. That still requires copying code and updating those separate scripts for general script updates but that might be the best option. I'd love if there was some way to write a conditional that always returns the bool it returns on the first go though.
if you want those separate scripts to share logic you can have them reuse some shared static functions or be a part of a class hierarchy using inherited behavior. That's not mutually exclusive with using interfaces.
btw another option is to use delegates
you can have like:
public delegate void CollisionHandler(...);
void StickyCOllisionHandler(...) {
}
void BouncyCollisionHandler(...) {
}
CollisionHandler myCollisionHandler;
void Awake() {
switch (collisionType) {
case Bouncy:
myCollisionHandler = BouncyCollisionHandler
/// etc..
}
}
``` etc
these are basically like function pointers, if you're familiar with that from other languages
Right, I've definitely gotten better about breaking up functions as much as i can with each project. I see. definitely taking notes here, thanks a ton!
How can I use the Mesh.AllocateWritableMeshData() with multiple meshes?
Im trying to set the value greate than 1 but then for some reason i get race conditions that I dont get if I allocate the mesh data bit by bit
basically this
InvalidOperationException: The previously scheduled job ApplyHeighToVertex writes to the UNKNOWN_OBJECT_TYPE ApplyHeighToVertex.vertices. You are trying to schedule a new job PathMakerJob, which reads from the same UNKNOWN_OBJECT_TYPE (via PathMakerJob.vertices). To guarantee safety, you must include ApplyHeighToVertex as a dependency of the newly scheduled job.
if anyone is knowledgeable in using unity's output data from audio, help would be much apprichiated. I'm trying to make a super basic audio visualizer UI component, and this is what I have so far
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using CustomInspector;
using Radishmouse;
public class AudioVisualizer : MonoBehaviour
{
[SerializeField] private float sensitivity = 100f;
[SerializeField] private int sampleCount = 64;
[Space]
[SerializeField] private int linePointCount = 64;
[SerializeField] private float lineThickness = 5f;
[SerializeField] private Color lineColor = Color.blue;
[SerializeField] private AudioSource source;
UILineRenderer uILineRenderer;
float width, height;
void Start()
{
uILineRenderer = gameObject.AddComponent<UILineRenderer>();
uILineRenderer.material = new Material(Shader.Find("Sprites/Default"));
uILineRenderer.thickness = lineThickness;
uILineRenderer.color = lineColor;
uILineRenderer.points = new Vector2[linePointCount];
width = GetComponent<RectTransform>().rect.width;
height = GetComponent<RectTransform>().rect.height;
}
void Update()
{
float xIncrement = width / linePointCount;
float[] spectrumData = new float[sampleCount];
source.GetOutputData(spectrumData, 0);
for (int i = 0; i < linePointCount; i++)
{
uILineRenderer.points[i] = new Vector2(i * xIncrement, spectrumData[i] * sensitivity);
uILineRenderer.SetAllDirty();
}
}
}
The UILineRenderer is just a component similar to Unity's line renderer but it works for UI, so its not really important for the problem. I will attatch a video of what the visualizer looks like in game
i guess my issue is im not sure how to change the height/frequency(?) of the y value of the output data without moving the line up and down like that
and the song is just for testing, eventually ill link it up to my mic audio source.
ok i ran into some issues with mono not being compatible with SSL connections utilising the certificates.
has anyone been able to successfully get SSL working with unity?
i want this particular setup for account creation and logging in etc.
if you know any open source libraries or alternative approachs please shoot them my way so i can try them out im in a pinch here and this is the last part i need to implement, please let me know if you have anything in mind.
Also this is a new updated for my Asynchronous Networking library
RSGNetwork which i will be publishing for free on the asset store and on my gitlab server to replace the old implemented model i have.
What’s the effect you are looking for, any reference?
something like this:
A basic audio visualizer made in Unity using a line renderer. See here http://goo.gl/eNBZYC and here http://goo.gl/MHtMBm to see how it's done!
i feel like my implementation is just wrong but idk why
What your implementation immediately sticks out to me is the count being merely 64
For a 48000Hz audio, 64 samples is a little more than 1 millisecond in time.
I’m guessing the waveform fluctuation in 1 ms is so small that it just appears as a flat line moving up and down rather than a wave (imagine you stretch out the waveform horizontally by a lot).
Try increasing the count and see.
If the rendering can’t keep up, you may consider reducing the amount of line segments, but should still cover more data than just 64 samples (eg still rendering 64 line segments but they cover 1024 samples)
I have a problem with my AI movement system. I recently rewrote my movement system to physics based, because when I moved the characters with transform they bugged across obstacles. I solved this issue with physics but when I have a lot of characters instantiated the game instead of lagging, gives higher speed to all characters moving with physics. Does anyone knows how to fix this?
//Update
private void Update()
{
//Get All Enemies
List<GameObject> enemies = new List<GameObject>();
enemies.Clear();
Component[] humanoids = Humanoids.GetComponentsInChildren<Component>();
foreach(Component hum in humanoids)
{
if (hum.gameObject.CompareTag("Enemy"))
{
enemies.Add(hum.gameObject);
}
}
//Get The Closest Enemy
if (enemies.Count != 0)
{
Target = enemies.OrderBy(enemy => Vector3.Distance(transform.position, enemy.transform.position)).FirstOrDefault();
Vector3 TargetDirection = (Target.transform.position - transform.position).normalized;
//NewPosition
Vector3 newPosition = lastPosition;
//Move Towards Target (Physics)
newPosition = TargetDirection * Speed * Time.deltaTime * 100f;
if (Vector3.Distance(transform.position, Target.transform.position) > 1f && Vector3.Distance(transform.position, Target.transform.position) < 30f)
{
rb.velocity = new Vector3(newPosition.x, rb.velocity.y, newPosition.z);
}
else if (Vector3.Distance(transform.position, Target.transform.position) >= 30f)
{
animator.SetBool("IsMoving", false);
return;
}
//............
//LastPosition
lastPosition = newPosition;
}
else
{
animator.SetBool("IsMoving", false);
}
}
1st, why are you doing this ?
List<GameObject> enemies = new List<GameObject>();
enemies.Clear();
- Remove your linq queries and just iterate it manually. You're constantly creating garbage on every frame there.
3.You can avoid GetComponentInChildren by just adding property/field to the Humanoid directly and add your "enemy" there
believe it or not, in the past, List.Sort is much faster than Linq's OrderBy. Hope that's not the case today
pretty sure you can just remove the sorting completely and play around with the logic right after you're checking their distance in your if-else
I've been using Odin for a long while, now I'm on a side project and would rather not use it
I hear new stuff came out since Odin like [SerializeReference], can it fully replace Odin's serialization niceness?
SerializeReference is god-sent, not quite sure about Odin, never really used it
uitk for custom editors is like easy-mode, no joke
you dont even need to sort to get minimum
in general, query minimum k elements from n elements is k+ (n-k)log(k), if k is constant then it is linear time
hmm can I have something like a dropdown for which I can select a type to instantiate, then populate a list with it, using SerializeReference?
you surely can, again depends on how you'd implement it on the custom editor side
like:
public class RulesDefiner : ScriptableObject {
[SerializeReference] public List<IRule> rules;
public void ApplyRules(object obj) { foreach (var rule in rules) { rule.Apply(obj); } }
}
(sry for weird formatting, just wanted to be compact, lol)
ahhh I'd still need a full Custom Editor to handle clicks and list.Adds to achieve that, then?
absolutely 😌
happen to know if there are any ready ones I can reference to? would rather not go for full editor, lol
my editors tend to become a little too focused on styling 😅
Ima be a jackass and say it once again, uitk is easy-mode for custom editors 😃
for introduction just do it inline, meaning no uxml/uss if you're too afraid touching that
hmm thanks but it might be a big change coming from IMGUI background -- and this is something I would like to spend a max of 1 hour in (for now at least)
I could probably whip up an IMGUI editor that does that in an hour but it's just that I was never good at managing editor styling scope lol
with uitk + inlinestyles, you can do less than 1 h, trust me
afraid gonna end up making it look like The Elder Scrolls: Add To List Dropdown xD
and that includes the learning curve of learning the necessary uitk stuff I need to do that?
I keep mentioning InlineStyles there, meaning it's the c# way. Basically you're just doing full c# and nothing else
when you feel it becomes too boilerplatey, then it's time for uxml/uss
for introduction, just do it inline you should be good
alright thanks will give it some thought
here lemme give you a simple example how easy uitk is
[CustomEditor(typeof(T))]
public class Car_Inspector : Editor
{
public override VisualElement CreateInspectorGUI()
{
VisualElement myInspector = new VisualElement();
myInspector.Add(new Label("This is a custom inspector"));
return myInspector;
}
}
ain't that beautiful!
it is, but.. well add that to drawing a full list (including buttons) and drawing its content.. it stacks up 😛
it's not!
//make the template
Func<VisualElement> makeItem = () => new Label();
Action<VisualElement, int> bindItem = (e, i) => (e as Label).text = items[i];
var lis = new ListView();
lis.makeItem = makeItem; // or just pass it via ctor
lis.bindItem = bindItem; // or just pass it via ctor
lis.itemSource = List<T>; // put your list<T> here / or just pass it via ctor
done
goodluck
if you're used with the binding workflow of XAML for example, working with uitk shouldn't be too hard
I highly recommend doing it inline for the introduction to the framework. Once you used to it moving to uxml/uss way shouldn't be to hard
for custom editors uitk is a bless, for runtime? it's a curse 😅
did they actually intend for it to replace UGUI?
I'm guessing yes
Anybody using google play to get a ServerAuthCode ? google takes 12 seconds to answer to that petition and i'd like to know if its normal or is just because or app is in development
Are you doing it using UGS? If so, go post in #archived-unity-gaming-services
I made a public function that returns the closest target and replaced all my linq queries with it. The code definitely looks more readable but I dont see any changes in the performance.
//GET THE CLOSEST ENEMY
public GameObject GetClosestEnemy(GameObject hum, List<GameObject> enemies)
{
GameObject closestEnemy = null;
float closestDistance = float.MaxValue;
foreach (GameObject enemy in enemies)
{
float distance = Vector3.Distance(hum.transform.position, enemy.transform.position);
if (distance < closestDistance)
{
closestDistance = distance;
closestEnemy = enemy;
}
}
return closestEnemy;
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
The profiler says the Update() [invoke] takes the 55% of the cpu.
You're making a whole new list every frame.
You're calling GetComponentsInChildren every frame (which also allocates a new array every frame)
You're going through EVERY component (why??)
You're adding the enemies to the list multiple times (once per component on them)
Just... A lot of really unnecessary slow stuff
And they asked about the clear thing because why would you need to clear a brand new list? It's already guaranteed to be empty
Yeah I already removed those line from the code and declared the list as a private list.
Which lines
List<GameObject> enemies = new List<GameObject>();
There's also still the Component stuff which makes little sense and is also slow as mentioned
then how should I get all enemies and put them in a list?
Really depends on how they come into existence. This isn't advanced stuff though
Put them in a collection either at edit time, when they're spawned, or at the start of the game
And keep them there
var validated = seaCore.Where(r => r.IsBorder);
var scanline = seaCore.Where(r => r.IsBorder);
int breaker = 100;
Profiler.BeginSample("Slow Section");
while (scanline.Count() > 0 && breaker-- > 0)
{
scanline = scanline.SelectMany(r => r.Neighbors).Distinct().Intersect(seaCore).Except(validated);
validated = validated.Concat(scanline);
}
Profiler.EndSample();
I have this block that is very slow and generates very high amount of garbage (half a gigabyte)
unless I cast the queries inside the while loop into lists (.ToList()), which makes it complete in few ms and generates around 1mb of garbage
trying to find if it's something innate to Linq or this specific query or my enumerator (.Neighbors)
https://gdl.space/linijinovi.cpp relevant pieces of code
Linq is doing a lazy resolution of the operation. In other words, it does nothing till you actual call a function that needs the result such as ToList. I believe you might be exponentially increase the complexity of your data structure if you do not cast the result in a list.
Also, it is worth nothing that Linq does an extreme amount of garbage and should almost never be use in critical path.
If the code is critical, you should convert it to a standard for loop.
but .Count() should be evaluating it every iteration also
this is a run-once calculation (world generation) and at this point readability is more important
later I might rewrite it
It does evaluate your enumerate, but you keep using the old one that is not evaluated.
hmm, I'll check this
oh, so each new iteration will store the previous query as a dependency and that chain keeps growing ? and it will keep evaluating a growing chain of queries over and over ?
that would explain such a drastic difference in performance
for bigger world sizes it went from half a second to literal minutes
Exactly
thank you for the help
I'll keep that in mind when dealing with iterative queries, glad I don't have to rewrite my other parts of code, would be a huge headache
gonna check this out
seems very nice
we currently use odin for inspectors so anything open source might be worth looking into
Guys how can I get normal vector of trigger collider ?
I think you need collisional trigger for contact points
oh, there is nearest point on collider I think, but I'm not too sure how accurate that is
contact points are great because you can average the normals to get a more accurate vector
you can also maybe raycast a bunch and maybe do something similar on contact
but trigger collider don't have contact points I guess
Yeah I dont think that approach is the one you want, but if you want an approximation
you could just use the vector from both object's centers
or a bit better, you could get the closest point and use that for the calculation
On my engine I have a kinematic rigidbody that I use for this purpose whenever I need this (Which is not that often)
Don't cross post
I thought is better to put here instead in talk
not code advanced
general, beginner
So I am trying to work with the new input system and create a global singleton with events that everything in the project can subscribe to with events. For example the input manager checks WASD and mouse clicks. And my GUI components can subscribe to the event to see if mouse is clicked. Instead of hardcoding Input.GetMouseButtonDown everywhere like you did before. But I also have to check for input values all the time in input singleton:
private void Update()
{
Vector2 _cameraMovement = cameraMovement.ReadValue<Vector2>();
if (_cameraMovement != Vector2.zero) {
OnMoveCameraEvent?.Invoke(_cameraMovement);
}
}
Is this sane?
I would have to do the same for basically every keymap
Yeah this is an approach that work
requires a bit of initial setup but once you get it going you can easily manage workflow by just subscribing/unsubbing from the callbacks
I'm trying to implement value noise with smooth interpolation. The two functions here work fine, but I'm wondering if anyone here can catch any glaring optimizations that need to be made? I'm calling this function relatively often, so I need to be sure it's not incurring any unnecessary overhead.
static int IVPermutSize = 256;
static float[,] IVPermut;
public static void IVInitPermut() {
IVPermut = new float[IVPermutSize,IVPermutSize];
for(int x = 0; x < IVPermutSize; ++x)
for(int y = 0; y < IVPermutSize; ++y)
IVPermut[x, y] = (Rand.Float01() * 2) - 1; }
static float CubicInterp(float a, float b, float t) {
t = (t > 1f) ? 1f : t;
t = (t < 0f) ? 0f : t;
t = (t * t) * (3f - (2f * t));
return a + ((b - a) * t); }
static float InterpolatedValue(float x, float y) {
int gridX = Mathf.FloorToInt(x), gridY = Mathf.FloorToInt(y),
gridXX = gridX + 1, gridYY = gridY + 1;
float u = x - gridX, v = y - gridY;
gridX &= IVPermutSize - 1; gridY &= IVPermutSize - 1;
gridXX &= IVPermutSize - 1; gridYY &= IVPermutSize - 1;
float bottomLeft = IVPermut[gridX, gridY], bottomRight = IVPermut[gridXX, gridY],
topLeft = IVPermut[gridX, gridYY], topRight = IVPermut[gridXX, gridYY];
float interp1 = CubicInterp(bottomLeft, bottomRight, u);
float interp2 = CubicInterp(topLeft, topRight, u);
return CubicInterp(interp1, interp2, v); }
public static float LayeredInterpolatedValue(float x, float y, float frequency, float lacunarity, int octaves) {
float i_frequency = frequency;
float influence = 1f;
float total = 0f;
for (int i = 0; i < octaves; ++i)
{
total += InterpolatedValue(x * frequency, y * frequency) * influence;
frequency *= 2;
influence /= lacunarity;
}
return total; }
You could try to use Burst or/and inline function
I got a rotation question. I have lines that each have a orientation, the lines are 'placed' on other lines (in this case the smaller line is placed on the bigger vertical line).
What I want to do, is given a point along a line and the rotation of that line, place another line perpendicular(?) to it and rotated on the forward axis of the parent line.
So in this example, lets say I want to place the smaller horizontal line. I get the position on the big line, and the rotation of the big line. And have a angle I want to place it at. How do I do this?
(Note that lineRot * Vector3.Forward would be the direction from one end of the line to the other).
I don't understand the question, you want a rotation perpendicular to that one?
Basically, given the transform of the big line, how do you place the horizontal line so it will match the rotation/potion it has in the gif
pos: position + lineRot * new Vector3(0, halfLineHeight, 0), rot: lineRot * Quaternion.Euler(90, 0, 0)
If you don't understand why, lmk
Damn... you're right that is it... I was doing stuff with AxisAngle and LookRotation and multiplying vector directions by the rotation and stuff...
There are certainly other ways to do it too
I gotta messaround to get it working in the real thing. But it works in the test setup so at least I know what I need to do. Thank you very much! ❤️
Hi friends, I want to Import and Export 3d model in unity at runtime, do you guys have any solution?
How to find the class that destroyed a gameObject? My gameObject is destroyed when I start the game but I can't find what does it.
Have you tried logging in OnDestroy or OnDisable?
I wrote Debug.Log(gameObject); inside of OnDestroy(), it worked but I don't know how to log the caller class of Destroy
does the stacktrace show any information?
What's stacktrace? How can I find it?
I coded an extension for it but it doesn't show what called it
It gived error (maybe because of assembly/dll difference)
Stack trace, I believe, is like a trace of steps that led to the method
Doesn't matter, that wont show you what you want anyway, OnDestroy is called by Unity not by your code
ondestroy (or disable) are callback from engine and i think it cant tell you who destroy your object
You often can (also we're posting in advanced code and asking what a stack trace is 💤 )
OnDestroy is delayed, so it won't work, but OnDisable will
What approach should I take to sort a native array of structs based on an int value from said struct? I'm aware of NativeArray.Sort<> but I have no idea how it works with values within structs, if it can do it at all.
what i found on docu
public static void Sort<T>(this NativeArray<T> array)
where T : struct, IComparable<T><----
so I should implement IComparable into my struct?
T needs to implement this interface
So I have this struct of an IDPair that contains both string and numerical IDs here:
public struct IDPair
{
[Header("ID")]
[SerializeField] string _stringID;
[SerializeField] int _numericalID;
public readonly string StringID => _stringID;
public readonly int NumericalID => _numericalID;
public static implicit operator IDPair(int num)
{
return new IDPair() { _numericalID = num };
}
public static implicit operator IDPair(string str)
{
return new IDPair() { _stringID = str };
}
// other implicit conversions
public override readonly bool Equals(object obj)
{
if (obj is IDPair other)
{
return this == other;
}
return false;
}
public override readonly int GetHashCode()
{
return _numericalID.GetHashCode();
}
}
I'm using this on a DataMappings<T> class which basically acts as a container for holding a dictionary of IDPair keys to corresponding values (like for example ScriptableEnemy, which implements an IDPair).
As you can see, the IDPair struct's GetHashCode method only returns the hash code of the numerical ID. This means that the IDPairs can only be used in lookups done using numerical IDs, but I want to be able to look up using both strings and num IDs.
Here's a small snippet of what the DataMappings class currently has for this:
private Dictionary<IDPair, T> Mappings { get; }
private Dictionary<int, T> NumMappings { get; }
private Dictionary<string, T> StrMappings { get; }
As you can see, it needs to hold 3 dictionaries for holding mappings for both strings and integers. This can be quite memory inefficient though, so I was wondering if it is possible to have just one Mappings dict that just has the IDPair as a key for lookups.
So to the actual question, is it possible to have an override of GetHashCode() which returns a hash code that isn't just based on the int, but the string also?
So like if we had an
IDPair { 0, "gun" } and an
IDPair { 0, "fake_gun" }, both would have the same hash codes of the numerical ID
And if we had an
IDPair { 0, "rifle" } and an
IDPair { 1, "rifle" }, both would have the hash code of the rifle
This is kinda hard to explain but hopefully someone gets it
yes, of course, GetHashCode can do anything you want it to do so long as it returns an int
And is this kind of logic possible?
yes, generate a hash using both the int and the string
So something like
hash = numID ^ stringID;
where the ^ is a XOR operator?
But then like in the first example here, the hashes would not match because the string part is different
Actually, we could just have the implicit conversions return like an IDPair where the string part is null when we want to create an IDPair with just the numerical id, and the same the other way around
why not
int x = _numericalID.GetHashCode();
int y = _stringID.GetHashCode();
// Do something with x and y
And make the numerical id nullable or something
But then it wouldn't be serializable so idk
But the question is what to do with x and y afterwards, the logic
anything you want, you know your data I do not
I'll try something like this:
If numerical ID is less than 0 (not valid), don't take it into account in the hash code algorithm. Same goes for string, if it's null, don't use it in the algo.
Then when the client wants to get a mapping, they just create a new IDPair implicitly from either int or string, and each implicit operation leaves the other as null (or -1 in numerical IDs case)
But what if the mappings dict has IDPairs that have both numerical IDs and string IDs assigned to them? Like { 46, "zombie_blaster" }
I don't think this is possible
why would it not be possible? you just need to turn 2 ints into 1
have you done any research into creating hash values?
But for example the client may not have access to the string ID, only the numerical ID (like what I use when saving to JSON)? The hash code will obviously not be the same as in the Mappings dict
Nope, 0 at all
you most definitely do NOT want to use GetHashCode in the int or the string if you are going to serialize it.
Then I suggest you do so, starting with the GetHashCode documentation
But I don't think the serializing has any relationship to GetHashCode, no?
want to bet? RTFM
Yeah, no need for the manual even, I think it's common sense
When you serialize "hello world" and deserialize it, it will be "hello world" again. Hash code doesn't care about the serialization or aynthing else, just the string parameter. So both will have the same hash code still. Else it would lead to hash collisions which would be stupid design
wrong
No
yes
So if I serialized a list of 1000 strings and deserialized it, they would not have the same hash codes?
Strings are value types, not references, so unless they were StringClasses or something it would stay the same
From the MS Docs
Then how come you can look up for example by integers, or anything for that matter, in dictionaries, IF the hash code generation has entropy?
Can't fight against that cause dunno what domains are (in the context of hashes)
I'll just stick with using the slightly memory inefficient approach of having 3 dicts loaded in memory
you can just do what sensible people do, write your own hashing algorithm
No point because the logic I described may not actually even be possible
I think theoretically the hash code of non strings is stable but it's not guaranteed
Thanks! But I think I'm good for now
It's just a link describing why, not a solution
But I'm not serializing hash codes anyways so that isn't relevant in my situation
Sure but it's interesting
Yeah, defo something to look deeper into in the future
i think there is no solution to your problem
what you want:
if two ids are same, they should have same hashcode
if two ids not the same, and their string are same, they should have same hashcode
but unfortunately, GetHashcode is only dependent on its state and you cant take others' state for consideration, what you want actually is a sorted set (likely based on the string) not unordered set
Yeah that's what I was thinking
let says if you have three instances
- {x,"a"}
- {x,"b"}
- {y,"b"} (ofc x!=y)
since 1==2 and 2==3, so the hashcode should be the same, and you can replace x y "a" "b" to anything so the only way to do that is to return the same hashcode no matter what the content is
Damn thanks for pointing that out
It's like a paradox so it's not possible
actually not replace x y "a" "b" but to include two more instances
{x, any string}
{any number, "b"}
but you get the idea, fine
i just realize you cant use single sorted set to do this btw
Well, this can't really be done anyways so
I am creating a 2d mesh generator. For large map, I have made the ability to disable meshes that arent displayed by the camera.
The problem is, the performance gain isnt respective to the mesh not being generated in the first place.
I understand there is to be some bottleneck because the mesh is still in memory (but disabled), how can i further increase fps after disabling mesh objects.
For example, in a 1000 x 1000 hex map, here are the stats
Full Map Visible: 300fps
Half the Map Visible: 500fps
None of the Map Visible: 1000fps
How ever if i generated a simple 100 x 100 map, fully visible is 2000fps.
Is that overhead that much to account for 1000fps drop?
The difference between 1000 fps and 2000 fps is only 0.5 ms per frame. Which is not a lot.
I see, so further optimizations on this arena is simply pointless micro-optimizations and I should put my efforts somewhere else
nobody has a 1000hz monitor
that being said, better performance is always better. But yeah the difference between 2000 fps and 1000 fps is much less significant than 30fps vs 60fps
Start optimizing when you have an actual performance problem. A game running at 1000 fps doesn't need optimizing. When you get to double digits then find out where the real bottlenecks are
Got it. Thank you gentlemen @sly grove @devout hare
Probably more of C# question than actually Unity, but is there a way to read&write only one variable inside a big struct stored in an array?
I have a NativeArray containing some pretty heavy objects, and while all those data are used I have a few jobs that only need to change one parameters, and I was wondering if I could dodge the performance cost of having to load the entire object, then send back the entirety of it when only a small part changed.
Or does the compiler automatically do it behind the scene? I can't find a way to dodge that full read/full write in C#.
I mean, I could probably do it with some Explicit Struct Layout and IntPtr shenanigans, but maybe there is a cleaner/safer way.
the performance cost of blitting the entire array is probably lower than individually copying every changed parameter back. But maybe it's time to split your object into parallel NativeArrays instead if this is a concern
Is the struct actually that large that it would matter?
In C#, arrays return elements by reference, so when you do array[i].parameter = true, it only reads the memory address of the element to the stack.
NativeArray doesn't return by reference, not sure why not, but it means you can't assign parameters directly like this and always have to read it to a temporary variable. Whether the compiler will be able to spot that and optimize it depends on the compiler. I don't think Mono JIT will, but Burst might.
Alternatively, you can also reinterpret cast the NativeArray to a pointer or a Span, which will let you access the elements by reference.
Unity 2022.2+ has a NativeArray.AsSpan() method. For older versions, you can do it manually with NativeArray.GetUnsafePtr().
Hello, I want make skill system with ScriptableObject. but I need only 1 .asset file to make skill. first. I made skill system like this:
//SkillBase.cs
[CreateAssetMenu]
public abstract class SkillBase : ScriptableObject
{
public abstract void Execute();
}
//TestSkill.cs
public class TestSkill : SkillBase
{
public override void Execute()
{
//Do Something...
}
}
But, In editor, create tab has the unnecessary menus. then, I want make ScriptableObject only once. but how to?
No idea what you mean.
oh I see, again, First, I want make skill system with Scriptable Object.
with like that
And... ?
but, that code has one problem.
when I made many skills, the "Create" tab has many menus.
and there menus is used only 1 times.
last, I want the make .asset file only once. but how to?
I still do not understand. Are you able or not to make the scriptable object ? And why it is an issue that you are able to make it twice ?
oh, ok
Remove [CreateAssetMenu] then?
I also do not understand
So, when I create an ScriptableObject, if you write the CreateAssetMenu attribute, that SO is added to the Create tab, right?
Usually, but in your case it wont because you are doing it on the abstract class I guess
So, I want to create just one SO asset.
Then dont create it with CreateAssetMenu and use an other method ? Or remove the CreateAssetMenu once you created it ?
Oh, there's a way to first create it and then erase the attributes
Yes, remove it from the code once you created it
Ok thanks, but the way is only that?
This is a way. Another would be to simply not create a second one or use an editor tool to create it.
Oh that is so cool!!!
what separates an intermediate coder from a advanced coder?
Experience
id say intermediate should be able to do lambda expression, ternary operations, oop, etc
eventually it goes down to knowledge of unity and software architecture
advanced programmers should also be aware of what's going on under the hood of the programming language
oh thats important to know. Any recommendations where to start? Is that something I should just look up ?
Trying to take it to the next level.
im unaware of what a "unity advanced programmer" looks like however, there's people building their own memory allocation / heaps and their own compilers
i really dont know what you're aiming for but if you want to be the best Unity Dev possible everything i mentioned lambda expressions, software architecture, functional programming(not really that necessary), what happens under the hood for C# are great places
buy some books man if you really want to be the highest level you can be, and most importantly make shit with what you learn
data structure and algorithm...
im doing a F# project in Unity right now after reading some books on lambda calculus and proper F# personally
true
id assume that's more inferred but yes
I would like to be a great gameplay programmer if i had say what my main thing is.
thank you
no problem as i said learn stuff and implement it in mini projects
yep thats best strategy
Kinda lte but, when using CreateAssetMenu, one can organize the asset menus into folders, so like if you set 5 SOs to have the "menuItem" parameter to "Rarely Used/New Placeholder Item", you will only see one menu "Rarely Used" in there that you can then expand
This is useful for like config files and stuff
why the hell would importing push notifications package break GPGS?
the resolver is automatically deleteing 70+ files.
would really appreciate the help from someone who knows how to deal with this stuff, since i had a lot of problems setting it up the last time too
* What went wrong:
Could not create an instance of type org.gradle.initialization.DefaultSettings_Decorated.
> Could not initialize class org.codehaus.groovy.reflection.ReflectionCache
ok, in publishing settings just marking custom main gradle template fixed this. nothing was even changed, it just copied the file
i hate this so much
can i see the variables in the editor somehow? if i put the variable in the enemy entity class i can see it but not if i put in the parent class base entity
public class EnemyEntity : BaseEntity
{}
public abstract BaseEntity : MonoBehavior
{
[SerializeField] public int health {get; set};
}
ouh sry i thought im in the general channel btw. what do you mean exactly with "field:" should we change this to the general channel?
stick in here, include the field: in the attribute
still no idea what you mean please send me the docu or send me a short code what you mean sorry thanks for ur help
thank you very much ❤️
Thanks
So i'm currently trying to make a regex query for my database and running into a bit of an issue.
Scenario:
the user wants to filter for entries in the DB with a specific string.
Issue:
They want to filter for multiple fields/properties via that one string
Code example:
var IDregex = new Regex(IDescapeText, RegexOptions.IgnoreCase);
filter &= Builders<Item>.Filter.Regex(g => g.Name || g.Desc, BsonRegularExpression.Create(IDregex));```
Problem:
g => g.Name || g.Desc doesn't work, and i'm unsure how to have it check for if it's contained in either the Name or Desc, rather then in both.
Okay, so the backtrace shows stuff related to vulkan
#00 pc 00000000000692a4 /vendor/lib64/hw/vulkan.adreno.so (qglinternal::vkCreateInstance(VkInstanceCreateInfo const*, VkAllocationCallbacks const*, VkInstance_T**)+652) (BuildId: 0fb46969e23197ed4b8b6f53da9e578c)
#01 pc 000000000001b78c /system/lib64/libvulkan.so (BuildId: ca307e00fd24c1f25df24d68f6ff1f6d)
...
it crashes on my phone, but on bluestacks it doesnt. Any ideas?
disabled vulkan, as smooth as butter now
Hey so im trying to make a transparent and click through background in unity but also make the ui works so the click through turns off when i have my cursor on UI. But for some reason its neither transparent and neither click through.
Experience is definitely the principal factor that separate an intermediate coder from an advanced one. However, you need to be able to translate that experience in useful skills. Such as not repeating the same error, knowing what to do before doing it, quickly being able to identify diverse possible cause of issue, etc.
One of the best example that you can quickly differenciate an intermidate programmer and advanced one would be profiling. The intermidate programmer will know how to use the tool correctly, however he will need a lot more trial before reaching the same result of an advanced one. This is principally due to the fact the advanced one will already know what the potential issue could be and how to fix them. By example, if you have issue with GPU performance, the more advanced programmer will already know what to look at and have potential solution in head. (Draw calls, Polygons, GPU bandwith, etc.)
Personally, I try to not shy away from challenge whenever I see them. I also am not afraid to test things whenever it is possible.
An advanced programmer is able to select the best solution in a complex project with conflicting real world requirements, that anticipate future extensions by someone else, without overengineering anything, and doing all that while writing code a beginner can readily understand and learn from.
thank you, some good answers.
Hi, sorry to bother everyone with what might be a super easy fix. im making a game in vr rn, where the player picks up a rope and throws a moving ai at the end of it like a ball on the end of a string, everything is working apart from the ai cant move when the rope is attached, like the rope is either too heavy or has too much friction to let it move, but i have removed any drag on the object and wieght
[field: SerializeField] public PawnController Controller { get; private set; }
Can someone explain what "field:" does in this situation? I saw this neat trick on Reddit and I'd like to know what it is.
auto property creates a backup field, the "field:" is telling unity to serialize the backup field
public int a{get;set;}
```is compiled to
```cs
private int k_a;//or other prefix
public int get_a(){
return k_a;
}
public void set_a(int value){//or other name
k_a=value;
}
Basically to apply the attribute to the backing field rather than the property.
dont cross post, stick to code beginner
ok
Is there a way to intercept a physics collision and modify it's force of impact or even bury it completely? Or is that something I will need to detect myself?
Well I don't want to directly cancel out the velocity as I have to consider other potential impacts. There are circumstances where I will need to adjust the impact force to prevent unwanted behavior. Is OnCollision event fired BEFORE impact is pushed to the physics engine or AFTER? Meaning can I tweak the impact calculation there or do I need to do a counter impulse after the impact?
try it and see
As a personal idiom, I use the following when I want to rebuild items in a container:
- Destroy all children (using
Destroy()andtransform.childCountwithGetChild(i)) - Iterate the data and recreate them.
Today I've been working on some utility functions to rebuild the container size when I use scrollrects. The problem is that when I destroy all children, create new ones, destroying them doesn't actually destroy them until the end of the frame, so for that one frame duplicates exist and the size calculation is incorrect.
I've resorted to using DestroyImmediate() since I can't find a good API call to something like "IsDestroyed()" that returns true in the same frame that I destroy an object.
The API docs seem to warn away from using DestroyImmediate() but don't have any justification why, and I couldn't google up any reasons against it. Any idea? Is my practice of doing it this way going to have any side effects I should be aware of?
Sorry if I'm misunderstanding but cant you just check if the object == null before including it in your calculations? DestroyImmediate is more for editor stuff, since Destroy wont work there
That's what I thought, but it's returning !null in the same frame that I destroy it
I already have a "BetterMonoBehaviour" class (that has new void Destroy() that I use 100% in my codebase.. I might just add a flag and method for IsDestroyed..
https://pastebin.com/FbwiUei9 Essentially line 4 of this method (I included my library methods below so you can grok it)
If I don't DestroyImmediate() then my utility method GetMinimimSize() sees both the old and new game objects
Ah my mistake with the null thing.
https://forum.unity.com/threads/is-there-any-flag-indicating-an-object-is-marked-as-destroyed.864301/
The flag that you suggested above does seem to be a common workaround online
Yeah... I just realized though while I was building it that it only works if the children are "my" monobehaviours and fails for generic GOs. Normally that's fine but .. it requires me to do a little bit of object calesthenics like if (gameObject is BetterMonoBehaviour bmb) bmb.Destroy(); else UnityEngine.Destroy(gameObject);
It's fine.. It just seems like there ought to be some functionality to check if a GO was destroyed in this frame (even understanding the race conditions that could arise)
I want to make a script that I can just throw on any gameobject with a button and textmeshprougui to add "are you sure" functionality (ie, for "Delete" buttons). My approach was going to be to grab a list of the events at Awake(), and replace them with a "are you sure" button handler, which would handle a second click within 5 seconds to invoke the original events.
However, I can't seem to modify the "Persistent" listeners (ie, those added in the inspector). RemoveAllListeners() only removes script-added listeners.
My first workaround was going to be to create a new button "on top" of the original (and then "hide" the confirmation button for 5 sec) but this seemed like a lot of work.
Any ideas?
To modify persistent listeners: https://docs.unity3d.com/ScriptReference/Events.UnityEventTools.html
Yeah, I saw that bit but... I wanted this to be in the runtime (which requires the editor dependencies).. Also, wouldn't it mess with the inspector-added event listeners..?
wouldn't it mess with the inspector-added event listeners
Kinda thought that was the point
Like, I'd have to write a bunch of plumbing to add the original listeners back after the game is closed
but yes this is editor only
Yeah I sorta was hoping for something easy that I could slap on any of the "delete" buttons in my unity admin tool (there's a lot of them) to require the user to press a delete button twice to confirm something.. I was hoping for something that wouldn't require too much effort to implement across the .. 100 or so existing delete buttons throughout the app
Like it's already a bit of effort to drop the script on all those buttons
https://pastebin.com/DGCUfhUQ This was my first attempt (which obviously didn't work because of the above)
Thinking about a clean solution here 🤔
Yeah..
My initial thoughts were also adding another "invisible" button on top
but then making the button transitions still work might be messy
I'm honestly thinking the invisible button thing is best but.. it's sort of a lot of work
I think the click logic itself would be simple
It breaks too if I've created anything more complex then a button with "delete" on it
you can just Invoke the onClick event
oh.. hm.. I could just make an invisible image with an onclick handler
i can still grab the original buttons text and modify it
Clicking once would just hide the image
Wait can't you do something like this @misty glade ?
ButtonClickedEvent oldEvt = button.onClick;
ButtonClickedEvent newEvt = new ButtonClickedEvent();
newEvt.AddListener(() => {
// show are you sure dialogue
ShowAreYouSureDialogue(oldEvt);
});
button.onClick = newEvt;```
Where ShowAreYouSureDialogue shows the dialogue and calls Invoke on oldEvt
nah it's all part of the UnityEvent object
ie, I don't think modifying onClick has anything to do with the list of persistent listeners
There's nothing about persistent listeners on Button
it's all part of the UnityEvent
Yeah, I saw that - I dug into the source myself, but ... I'm wondering if there's something else at play.. I'll try that, one sec.
Provisionally working.. but something else is broken. Progress!
nice
Amazing, it works. Problem was that I didn't set isValid = true at the end of the awake if it succeeded
I didn't think to just save the entire event instead of trying to muck with removing the listeners piecemeal.. thanks boss
GameObject bridgeParent = new GameObject("Bridge", typeof(Bridge)) {
tag = "Bridge"
// What else can go here?
};
So I've found out you can create GameObjects with the following constructor method.
I've read the documentation and it is a bit unclear what else I can include in this "object".
probably any public field/property in GameObject.
This is basically the same as setting the fields/properties values after the constructor.
Avoid crossposting next time
@untold moth Could you please provide an example?
Same as this:
GameObject bridgeParent = new GameObject("Bridge", typeof(Bridge));
bridgeParent.tag = "Bridge";
@tender fern That's not a unity feature, that's a c# feature ("object initializers").
@misty glade Yep, initializing an object!
Oh, uh, I see you messaged the same in general already
😜
How can I speed up my 3d cellular based water simulation?
I mean the algorithm not playing with time
The implementation is like https://github.com/jongallant/LiquidSimulator but in 3d and some changes
Suppose there is a water source in the left side. When it is flowing because the flow speed is slow horizontally, it causes water level is rising fast instead of flowing on the ground horizontally
I'd do just fake it with meta-ball + custom render feature for things like this
something like that
Hey guys! New to the discord but I was wondering if someone might be able to help me out with a quick question I had
Ohh gotcha okay
Well I'm relatively new to Unity as a whole and I'm having trouble trying to make an image a button. I can drag the image I want into the Source Image and that works, however the button then becomes a large rectangle and instead I want to make it the specific shape of the sprite. Any Suggestions?
is it code question? probably ask in ui/ux or unity talk
Yes I apologize it is Unity related. Just feeling my way around here is all
Thanks :)
can someone help me on how to raycast out of a sphere :()
i need someone to help me on the math :'()
I am implementing a market of goods per town, so 5 towns, 5 markets. What is a good pattern to access these market and check prices for multiple systems. I feel like using 5 instances of marketmanager does not seem good?
One thing you could do is check out a pattern known as the "repository" pattern. Simply the Repository is very good at storing collections of information (market goods in your case) but you can also attach some operations to them easily as well such as buy, sell, out of stock, discount and so on. The repository pattern also allows for quick saving/serialisation. Here is a video on the topic to help get you started: https://www.youtube.com/watch?v=5D4qHl3SeoA
Sign up for the Level 2 Game Dev Newsletter: http://eepurl.com/gGb8eP
Download the project at https://www.patreon.com/posts/project-unit-of-60029495
Data concurrency and data access bottlenecks are common problems that arise when dealing with persistence. In this video I'll show you how the Unit of Work design pattern (with the repository patte...
The pattern is used a lot for business applications as well for accessing and storing data within a data access/storage layer. So you can find a lot of information about the pattern in general and its use cases
Hey guys, Im trying to make my project compile to .net framework 4 and not netstandard. I set my api compatability setting to framework, but I still get netstandard dlls in my build, why is this the case and how can I fix it?
I'm really happy that you are suggesting that pattern, I feel it is under used in VideoGame.
🙂
I need to have 2D inverse kinematics with rotation constraints but I can barely find any resources on it. does someone have a paper for the math for such a thing or something similar?
LayoutRebuilder.ForceRebuildLayoutImmediate(RectTransform) fails if the gameobject is inactive. Since I have some custom behaviour in OnEnable, I don't want to just set it to active, force a rebuild, then set it to inactive.
Anyone have any ideas on how I can get a layout manager to .. uh.. precalculate? the layout
This might not be possible since obviously the layout manager itself would need to know if inactive children need to be accounted for ..
ie, some combination of activeSelf and activeInHierarchy
Hey so for my game I'm planning on making a sandbox mode, where players can place objects in a scene and then the scene can save and player can load the scene again all the stuff they did will be there. So my question is there something in the assest store that can do this? I'm looking for one that can save rotation, transform, and scale. I would much rather just buy one but all the one that I found dosen't save scale. But if I can't what would be the approach to do this? Thanks!
@feral dirgeEasy save can prob do it
This is a really simple thing to do, you should invest a little bit of time to make it.
Ya after doing some research it actually dosen't sound that hard. I would rather just spend a little bit money and save a little bit of time but I think I'll just do it my self as everything is a little bit to much for me, Thanks for everyones help!
getting some really strange behavior with using random seeds. I don't think its super important, since there is like always gonna be a delay, but im curious if anyone has experinced something similar when using Random.InitState
you'd have to show your code
not really looking for help, just curious if this type of behavior is a known thing.
I would expect Random to return the same sequence of values when initialized with the same seed and the same functions are called on it in the same order. If you're seeing something different, that would be a bug
But it's possible that your code simply has a bug of some kind that results in different sequence of Random calls being made which will result in different returned values
oooh that makes sense
i am calling the function with the random code multiple times at once so i see how that would easily get out of order
could be a script execution order issue
especially if there's coroutines involed and you're depending on WaitForSeconds delays
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oh okay I'm stupid sorry
So I'm just trying to draw a box around it with that code. Instead, it does this. I've tried a lot of things and wouldn't come to this server if I didn't think I was missing something. Sorry if this is a really dumb issue lol.
lineRenderer.SetPosition(i * 2, corners[i]);
lineRenderer.SetPosition(i * 2 + 1, corners[(i + 1) % 8]);
do you know the line of line renderer rendered is always continuous?
it wont draw separate lines as you want
No I'm new to the whole line renerer thing, sorry.
and unfortunately, since every vertex of a Box has odd degree (3) since there not exists Eular path, and you need multiple line renderers to render a box if you want every edge is rendered only once
ofc you can revisit the edge....so single line renderer is still possible
Ohh okay. This helps a lot, thank you!
Hey! I want to read files from a Thread from the StreamAssets directory on Android. Im calling for it a java code, but I didn't was able to read the datas into a buffer. Somebody a good idea how to do it? I made it working by reading the bytes one by one, but its too slow, its only good to see this solution really can work.
public static byte[]? LoadFileAndroid(string fileName)
{
Debug.Log($"Android Streaming Asset: Loading file: {fileName}");
byte[]? buffer = null;
using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
using (var currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
{
using (var assetManager = currentActivity.Call<AndroidJavaObject>("getAssets"))
{
try
{
using (var inputStream = assetManager.Call<AndroidJavaObject>("open", fileName))
{
int length = inputStream.Call<int>("available");
Debug.Log($"Android Streaming Asset: New buffer size: {length} Byte");
buffer = new byte[length];
//Debug.Log($"Android Streaming Asset: Buffer before: {string.Join(", ", buffer)}");
var sw = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < length; i++)
{
int data = inputStream.Call<int>("read");
if (data == -1) { break; } // End of file
buffer[i] = (byte)data;
}
sw.Stop();
Debug.Log($"Time: {sw.Elapsed.TotalMilliseconds:0.00} ms");
//Debug.Log($"Android Streaming Asset: Buffer after: {string.Join(", ", buffer)}");
}
}
catch (AndroidJavaException e)
{
Debug.LogError("Exception while loading asset: " + e.Message);
}
}
}
}
if (buffer is null || buffer.Length == 0)
return null;
return buffer;
}
No Idea where to ask this but, I'm currently making a project that uses infinite procedural generation (WFC algorithm). The program is a little laggy so i was thinking about making the algorithm as a compute shader. However, Compute shaders have limited functionnalities so i wanted to know if they supported dictionnaries as i couldn't find any information about it online. Tysm
!
Best way to read StreamingAssets on Android is to use UnityWebRequest
dont know much about calling java code from unity, but i see the docu states you can pass the parameter to .Call, and java inputstream allows you to read "all the bytes" of the file
https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html
read(byte[] b, int off, int len)
```have you tried this if you cant really read the file from other threads? (most of Unity api is not thread safe)
also array is reference type and it doesnt need nullable
i only know how to call java function from cpp....
mb, it may not be the inputstream as java.io
I tried, but if I try to pass a byte array it's not changing it. I think it's copying the array buffer before sending it to the read function
i guess there is no BufferedInputStream
Why do you need to read it from a thread?
UWR is asynchronous, it doesn't block main thread.
If you need to do extra processing after you got the content, you can then spawn a thread to do it.
I have a little complex sistem whats running on a Thread. It need to load somehow binary files from a lot of one, so I think this should be the best solution. I just need to solve how to get from the java code the byte array. (I don't have experience with java but Im trying.) The another solution what I thinking about is to send the file path to the main thread, it load the file or files and send back but I think its slower
Memory is shared, they don't exist isolated in a thread that need to be transferred across.
Depending on what you are using, for example in UniTask there are helpers like UniTask.SwitchToThreadPool and UniTask.SwitchToMainThread, so that's just 2 lines of code to do what you want.
Hi, I think Im having a weird race condition with unity jobs/burst
Normally I understand that my problem is a race condition when two things happen:
- If I increase the job time (by switching Native Debug Compilation) the problem disappears (optional situation)
- If every time i re execute the same jobs in the same order, i get diferent results (must happen)
And so far, every bug that I've found that has the second and maybe the first is a race condition
But now Im finding myself with a bug where the first happens, but not the second. Could stil that be a race condition? The result is always the same, but if i increase the duration of the jobs it disappears
yes it can still be a race condition
interesting
Okey, I made a java class what return a byte[], its doing the loading and almost no delay (1-3 ms load time per file), thats what I needed.
I am trying to rotate the right shoulder to points towards targetTransform. For context, the rightShoulder refers to Shoulder.R, which is an ik bone. However, the ik bone doesn't seem to rotate. This code is included in FixedUpdate().
Vector3 difference = targetTransform.position - rightShoulder.position;
difference.Normalize();
float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
rightShoulder.rotation = Quaternion.Euler(0f, 0f, rotationZ);
Assuming it's part of an animated rig, you'd need to move it in late update for it to not be overriden by the animation.
Why not just cs rightShoulder.right = difference;
(I assume this is 2d?)
This is 2.5 D
So its on a 3D plane but I want to restrict the movement to the x and y axis
Will the arm to be overriden by the animation if I am using an avatar mask?
Now if it's not rotating at all it's probably being overwritten by an animator or something
What does the .right do?
Probably. If you want to move something controlled by the animator, you do it in late update.
None of these are advanced questions btw.
well since we're ssigning a value to it, it sets the direction that the Transform's "right" direction is facing
effectively it will set the rotation of the Transform such that its right axis is facing in that way
SO In my game I'm experimenting with a mesh that makes waves at the mouse location. Im using a render cam to make a parallel mirror effect. As the game progresses the main camera zooms out, and I've been increasing the size of the mesh but this is no longer viable for performance.
The render texture is the mesh's material.
If someone could guide me to a way of keeping the render cam and mesh the same size while maintaining the effect I would be forever grateful. I'll attach a video since it's hard to explain
TLDR: would like to zoom main camera out while maintaining slightly complex render texture.
you need to google the correct system call in mac os, or wait for others answer
You may also need to google how to link the “dll” in mac os
I want to create a targeting system, with its functions inside my battle state. https://pastebin.com/DWmWsxNU
// add all game objects tagged "enemy" to a list
// the player can then cycle through the list to select a target with an input
// they are targeted based on where they are in the camera's view.
// pressing left on the d pad will target the enemy to the left of the current selected enemy, etc.
// select a random one by default
// the selection will wrap around. if we reach the leftmost enemy and press left, we are now targeting the rightmost enemy
// start by getting the positions of all enemy tagged gameobjects in screenspace, then storing them in a dictionary (gameobject, screenspace position)
// then, move an invisible point around in screenspace which will snap back to the middle when not being updated constantly, use the stick movement vector for this
// then, get the screenspace positioned enemy closest to that direction
// finally get its gameobject from the dictionary```
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.
the pastebin is the WIP code with a lot of stuff missing
would really appreciate some help with this
this is my test scene so far, when i press right on playerInput.UI.Select i want to move the selection to that enemy on the right for instance
It sounds impossible (at least no efficient way to do this) but i am not expert in computer graphics....
my approach:
try to label every triangle (pre-enemy mesh) projected to screen space first, idk if shader can do this
get the z-buffer back (contains only the label of enemy) after gpu
then you can just iterate the z-buffer or collapse it to be 1d intervals in your target system
eg
XXXXXXD
AAXXXXX
ABBXCCX
XBBXCCX
XXXXXXX
this should be how the "z-buffer" looks like (X means empty)
collapse the enemy as 1d interval eg
A:[0,2) B[1,3) C[4,6) D [7,8),
then sort them by start and end (you will have two copies of this array, one sorted by start and another one sorted by end, note that you should create a "interval to indices in two array" mapping for efficient access), then for choosing left and right enemy, just pick the interval right before or after respectively
ofc it requires O(size of z-buffer=your screen resolution) time to create the intervals
It sounds like they're okay with simplifying the enemies to single screen positions for this, in which case you don't need to involve the GPU.
yes, but no accurate result (the player may wonder why he cant select the D in above example, assume all enemy are 2x2 square on screen)
and you cant select the left and right enemy correctly
computation is too heavy, use single point maybe the best way.....
i just realize my way wont work eg
A
eye obstacle A
A
then two intervals of same A enemy are created......many edge cases....
btw i think tree can support "next larger/smaller element" by boxcast to left or right
From experience, it is more than enough. If you really do need more precision, then you can use Box.
I'm fine with using a few similar camera angles tbf, or just the one while in the targeting state.
I suppose i could assign each one of the spawned objects a small script with references to each other
I'm looking to migrate to STJ with Unity 2022 and IL2Cpp backend, is there any big caveat? How should I set the linker?
How i can transfer data between scenes with vcontainer? When i'm register gameobject with dontdestroyonload on first scene and try get this gameobject from hierarchy in second scene i getting error. Or i should use scriptableobject for transfer data?
just put the link.xml in your assets folder and you should be good
for the linker it looks something like this
<linker>
<assembly fullname="System.Text.Json">
<namespace fullname="System.Text.Json" preserve="all" />
<namespace fullname="System.Text.Json.Serialization" preserve="all" />
<namespace fullname="System.Text.Json.Serialization.Converters" preserve="all" />
</assembly>
</linker>
You'd still need to write your own converters for value-type generic tho
not quite sure if this already fixed or not in Unity
Does <namespace /> not automatically include all child namespaces?
you don't want to include all anyway, some handled just fine as is, only those problematic ones
again you should check if they fixed this in 2022 lts already or not
I've a feeling we may not require this whole magic anymore nowadays
Cool.
why migrating? if you're planning to publish it as package/lib it will be pain tho, just a heads up
Nah it's for my own game, have some free time and figure now it's a good chance to look into STJ.
nice! 👍
Oh forgot to tell you, you need to unpack the nuget package manually and pick only the required .dlls
or else you'll get conflicting namespace
Yep I grabbed the one for NS 2.0, seems like it depends on System.Text.Encodings.Web and Microsoft.Bcl.AsyncInterfaces though, guess I'll need to grab those as well.
This code has the player point the right arm towards the mouse. When the player is facing to the right, the arm's orientation is proper, but when the player is facing to the left, the arm's orientation isn't proper, causing the player to hold the firearm upside down. How do I go about fixing this.
public void LateUpdate()
{
if (holdingFirearm)
{
Vector3 difference = targetTransform.position - rightShoulder.position;
difference.Normalize();
float rotationY = transform.rotation.y;
//This check is to ensure that the player doesn't end up holding the firearm upside down when the player is facing to the left.
if (0 < rotationY && rotationY < 180) //This is for when the player faces towards the right
{
rightShoulder.up = difference;
rightLowerArm.up = difference;
rightUpperArm.up = difference;
rightHand.up = difference;
}
else // This is for when the player faces towards the left
{
//difference.z = -difference.z;
rightShoulder.up = difference;
rightLowerArm.up = difference;
rightUpperArm.up = difference;
rightHand.up = difference;
}
float rotationY = transform.rotation.y;``` this is very wrong
rotation is a Quaternion, and rotation.y therefore is not any kind of meaningful useful number to you
if you just want to know if it's facing left or right you would do:
bool facingRight = transform.forward.x >= 0;```
How would I adjust this part of the code?
else // This is for when the player faces towards the left
{
//difference.z = -difference.z;
rightShoulder.up = difference;
rightLowerArm.up = difference;
rightUpperArm.up = difference;
rightHand.up = difference;
}
Well Idk the whole thing is weird
but basically you can see it's not just the gun that's upside down
it's the whole arm
it's really hard to say what the correct thing is though without knowing the orientation of the particular bones
usually you would use something like an AImConstraint for this kind of thing
hi! So... If a user decompiles my code, and modifies the code and uses the brute force method (or any other) to find other users accounts, and modifies the code to delete the found account. how do i prevent this?
Are other users' accounts stored on the device, or are they stored on your backend server?
Well... I use unity authentication
That doesn't really answer the question, but that sounds like you store user accounts on your own backend
In that case it's very simple: a user should never be able to delete someone else's account to begin with.
I think you know that unity provides logging service. Also in their documentation is: DeleteAccountAsync() - which deletes the logged in account. I was thinking that if someone managed to log into someone else's account and call that function, that account will be deleted. How do I prevent this? can't I set somewhere that the accounts can only be deleted by the admin?
not really an answer, but for what it's worth - intuitively I wouldn't be surprised if support for that is deliberately not possible due to data concerns, you might have to support a way for users to delete their own data. If they have authd with their own account, there's not much else you can do
Their own accounts
Yes
But as I said, if somebody decompile the game and somehow login in other user account and delete it, what should I do?
There is no way I can prevent this?
I'm having issues with steering behaviors. Whenever an enemy detects an obstacle (say, another enemy) it gets weird
and it doesn't try to go around it or anything
how would anyone be able to acquire the auth details of another user from the game?
Can you Show the obstacle detection code block
public override void Detect(Enemy enemy)
{
Colliders = Physics2D.OverlapCircleAll(transform.position, Radius, ObstacleLayerMask);
enemy.Obstacles = Colliders;
}```
the actual detection works fine
the behavior is the issue
Ok i suppose this is in your Update func? Can you also Show the behavior code
public override (float[] danger, float[] interest) GetSteering(float[] danger, float[] interest, Enemy enemy)
{
for(int i = 0; i < enemy.Obstacles.Length;i++)
{
if (enemy.Obstacles[i] != null && enemy.Obstacles[i]!=ThisCollider)
{
Vector2 ObstacleDirection = enemy.Obstacles[i].ClosestPoint(transform.position) - (Vector2)transform.position;
float ObstacleDistance = ObstacleDirection.magnitude;
float weight;
if (ObstacleDistance <= ColliderSize)
{
weight= 1;
}
else
{
weight = radius - ObstacleDistance / radius;
}
Vector2 NormalizedObstacleDirection = ObstacleDirection.normalized;
for(int j = 0; j < Directions.directions.Count; j++)
{
float result = Vector2.Dot(NormalizedObstacleDirection, Directions.directions[j]);
float value = (1-Mathf.Abs(result-0.65f)) * weight;
if (value > danger[j])
{
danger[j] = value;
}
}
}
}
dangersGizmo = danger;
return (danger, interest);
}```
this is for avoiding
{
if (enemy.ReachedLastTarget)
{
if (enemy.Targets == null || enemy.Targets.Count <= 0)
{
enemy.CurrentTarget = null;
return (danger, interest);
}
else
{
enemy.ReachedLastTarget = false;
enemy.CurrentTarget = enemy.Targets.OrderBy(
target => Vector2.Distance(target.position, transform.position)).FirstOrDefault();
}
}
if(enemy.CurrentTarget!=null && enemy.Targets!=null && enemy.Targets.Contains(enemy.CurrentTarget))
{
CachedTargetPosition = enemy.CurrentTarget.position;
}
if (Vector2.Distance(transform.position, CachedTargetPosition) < ReachThreshold)
{
enemy.ReachedLastTarget = true;
//enemy.CurrentTarget = null;
return (danger, interest);
}
else
{
enemy.ReachedLastTarget = false;
}
Vector2 TargetDirection = (CachedTargetPosition - (Vector2)transform.position);
for (int j = 0; j < interest.Length; j++)
{
float result = Vector2.Dot(TargetDirection.normalized, Directions.directions[j]);
/*if (result > 0)
{*/
float value = result;
//if (Mathf.Abs(value) > interest[j])
//{
interest[j] = value*InterestVariable;
// }
//}
}
interestGizmo = interest;
return (danger, interest);
}
this is for seeking
{
float[] danger = new float[8];
float[] interest = new float[8];
foreach(SteeringBehavior behavior in Behaviors)
{
(danger, interest) = behavior.GetSteering(danger, interest, enemy);
}
for(int i = 0; i < 8; i++)
{
interest[i] = Mathf.Clamp01(interest[i] - danger[i]);
}
Vector2 output = Vector2.zero;
for(int i = 0; i < 8; i++)
{
output += Directions.directions[i] * interest[i];
}
output.Normalize();
Result = output;
return Result;
}```
this one puts them together
Using brutal force until they get username and pwd
Are you storing your Account Info in your Code?
If Not an attacker has No reason to decompile your Code He can Just write the brute force himself
I think the simple answer you need is, unless you're doing something very silly like trying to store Unity user credentials on your own server, it's not your concern to worry about
And im pretty sure unity has safety measures against brute force when authing
As long as you store the password hashed (and possibly salted), your attacker will need a couple of dozen universe lifespans to crack it with bruteforce
still no idea what I could do
Yeah i dont have time to Go through this much Code right now sorry!
no problem
still though, any tips for steering behavior?
or well, steering behavior where the target is always present
What i have noticed from your video IS that your enemies seem to get Stuck right at the hitbox, its possible that you dont give them enough time to Walk away from the hitbox
How is their behavior when nothing is around them
they walk towards the target
Your avoidance just turns them into the opposite direction but it should Turn them in a direction based on the location relative to the blocking collider
I dont know if it belongs in this channel, but, I need help with my 2d game, I have a system of roads which are each seperate Gameobjects, identical and square, each have 8 points to connect to another road, i need to somehow check if each road is connected by itself, or another road with a certain Gameobject, they should connect via Triggers any ideas how I would do that.
Hey guys, sorry I'm not so active on this forum but I'd like some point of view on a solution to a problem I have,
I instantiate an object which is essentially just a skinned mesh renderer and a rigidbody at a specific place using a parent transform. The object is then moved by an animation and it moves relative to the character I'm animating (drawing an arrow from a quiver if you want context)
I want to have a rigidbody so I can apply a force to the arrow when the string gets released, but if I add a rigidbody, the arrow gets "stuck" and does not follow my animation.
Using isKinematic won't work, or at least I did not find a solution using it. (I have no issues of placement of the arrow when there is no rigidbody btw)
I used ChatGPT so I would not waste you guys some time, and the AI found a solution : storing the rigidbody values, Destroy the rigidbody, then add a new rigidbody and add the destroyed rigidbody values.
Is that fine? Am I missing something easier ?
Thanks a lot if you read me,
OP7
a physically active (simulated) rigidbody will override anything you do to it via changing its transform, or rather the transform updates (via animation) and the rigidbody simulation fight each other. You should probably instantiate a new object when the arrow is fired, that one with a rigidbody, and keep the one used for the animation without one. Rigidbodys should also not be parented to anything. So yes chatGPT gave you the right idea. Not sure if you need to copy the values, just spawn the "bullet" in front of the bow and give it a strong impulse, it probably doesn't have to be fired from the exact position that the animation ended at.
the avoidance isn't supposed to do that, since it's supposed to go for the optimal path adding the weights pointing to the target and substracting the ones pointing to obstacles. I now made it so the weight pointing to the target also takes into account the distance to it and......ok it's still not perfect but baby steps
Thanks a lot, I actually fixed the issue and it's of course because I am an idiot who used interpolate while it was not necessary during the animation...
By setting this property to none, the issue was resolve and my character is shooting arrows! On the next step, I'll use its collider !
How do I make sure singleton 1 did all the work needed for singleton 2 to be able to use OnEnable to subscribe to events? Since OnEnable runs after Awake but before Start? I had to do [DefaultExecutionOrder(-100)] on Singleton1 but it seems kinda ugly
i mean default execution order would be how you do it
if you have to subscribe in onenable, then set up your events in awake
or just use an eventsystem class
And skip onenable?
Avoid invoking events untill your whole game is done initializing.
@untold mothBut I can't run OnEnable on Singleton2 in Start or later, must be done in Awake, and the event needs to be created by Singleton1 before that
If the event is to notify that something is enabled, you could check that when subscribing to the event to update to the correct state.
Another option is using an event queue.
can someone help me figure out how to make Graphics.RenderMesh work while the game is paused? i developed a custom 2d world system that generates outline and fill meshes, but they only render as long as the game is running; if the game camera re-renders while the game is paused, the meshes aren't re-drawn by my world system's Update since it doesn't tick
When you say paused, are you talking about setting Time.timeScale = 0? Because Unity doesn't have any runtime pause feature, only in the editor.
right, i meant pausing it in the editor
Hmm, looking this up, I've come across an event method that I've never seen before:
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnRenderObject.html
This is also called during edit mode, and I would assume also while paused.
The only issue with this is that it's called after rendering has finished, so any Graphics calls here will be executed next frame.
thanks a lot, i'll try this out :)
i'm fine with it being executed next frame since it's only going to be for the editor
hey would anyone please mind helping me for this problem ? #🤖┃ai-navigation message
Hey so I might be doing things completely backwards and I am super happy to change this approach .
Current game setup
I have Scene 00 - bootloader. This holds all my managers like inventory, VcamManagers, Ammo Manager , UI, equipment, audio, etc.
I then have Scene 00 - Main menu. This is where the game starts.
Now my thought process was , have a level variable reference script. This holds things that the managers needs to function
Example:
I am on Level 1 - Town of new beginnings.
I additively load Scene 00 - Bootloader with all the managers.
Once done loading I take the reference variables from the level script and assign them to the managers.
This always always causes null pointers and I am thinking this is a stupid way of doing it . Any help would be greatly appreciated.
I see nothing inherently wrong there. You'll need to provide specifics.
I'm currently in the midst of porting some code to utilize Unity Jobs. However, I am running into some issues. The following code sample shows the issue I am encountering and is reproducible on 2023.2.1f1:
/// error CS8377:
/// The type 'ExampleClass<T>.ExampleStruct<T>' must be a non-nullable value type,
/// along with all fields at any level of nesting, in order to use it as parameter 'T' in the
/// generic type or method 'NativeList<T>'
public class ExampleClass<T>
where T : struct
{
private NativeList<ExampleStruct<T>> _container;
private struct ExampleStruct<T> where T : struct
{
public int data;
public T job;
public ExampleStruct(int data, T job)
{
this.data = data;
this.job = job;
}
}
}
Why is this code not valid? It instantly becomes valid if the struct has it's generic type removed.
Please note, utilizing "notnull" in place of "struct" when defining T results in the same error.
constrain to unmanaged because a struct can contain managed types but NativeList can only use unmanaged types
Lifesaver, thank you!
I have a question about source generators.
Since Unity requires source generators to target .net standard 2.0 but the unity dlls are .net standard 2.1 when api compatability is set to .net standard in the latest versions, is it not possible to access anything within those assemblies or is there something I'm missing?
Ideally I'd like to generate an enum for layers and also if possible some constant strings for tags but I cannot figure out how I can do so since i cannot build with a reference to unity's dlls
You mean so you can call Unity APIs to get the tags and layers?
yes
I don't think source generators are executed within Unity's domain. It's probably a separate .NET runtime.
So even if you could reference the .dlls, none of the APIs would work.
I think the IDE executes them, because you need a compatible IDE to use source generators in Unity.
damn, alright
yeah doing this using a source generator would be tricky. but you can get the same result using an editor script, listen for the right callback, then create the txt/cs file 'normally' and save. it's a little hacky, sure, but it'll work 😄
SG runs in your IDE and runs every time you changes your code, without you having to tab back into Unity editor for editor script to take effect, so the ideal use case of SG is to generate code based on code.
If you need to generate based on non code assets, it's probably better to do it as a good old Unity editor script.
The information is saved in the unity cloud. I use unity login with username and password and keep them in player prefbs, encrypted. in addition to that I have other systems that prevent an attacker from taking User Information. But even so, those systems are after login. If somehow someone manages to connect to a user from the code, they could delete the account - you can't do it without confirmations from the app.
Wait what? This is really confusing to me. You're storing player login info somewhere in a prefab? I can't even begin to understand what that means
Why would player login info ever be involved at edit time in your Unity project
did you find a solution to this? I'm having a similar issue
I just made our build process simply copy over the dll manually. Extremely stupid solution
interesting, for me its the sprite editor that resets the values whenever I hit apply
Hi! I have a slight problem with the Animator.
I'm using a state machine for managing my player, and for the combat, what I had in mind is:
Idle state checks if the Left click is pressed trought my Input Actions Controller, if so, switch the state to Attack, where on Enter, I set the variable assigned to the Attack transition from idle, which works, and I want to check if the Animation finished playing then set the state back to idle, but I log every enter/exit state and noticed something.
The transition and animation activation works just fine from Idle to Attack, but in my attack state, the Animation check is faulty or idunno, and instantly switches back to idle state (The attack animation plays all the way, so I cant imagine what went wrong)
Attack State's Update function:
if (!Ctx.AnimatorIsPlaying("Attack_TwoHanded"))
{
Ctx.Animator.SetInteger("attackState", 0);
SwitchState(Factory.Idle());
}
Animation check functions:
public bool AnimatorIsPlaying()
{
return _animator.GetCurrentAnimatorStateInfo(0).length >
_animator.GetCurrentAnimatorStateInfo(0).normalizedTime;
}
public bool AnimatorIsPlaying(string stateName)
{
return AnimatorIsPlaying() && _animator.GetCurrentAnimatorStateInfo(0).IsName(stateName);
}
Nvm I got it, the animation doesn't play right away, but waits until the Idle animation is finished or reached the transition time. And when I switch to the Attack state, the current animation that's playing is the Idle, so it assumes the attack anim is already finished, so I added a check for Idle too
Hey Guys, I'm currently working on a registration page in Unity while storing the Userdata in a MySQL Database. On the Registration Page I have 2 TMPro Input fields, a Button to confirm the Input and a Text. The Problem probably lies in the php Code for the Database because no matter what is happening in the Database, I don't get any errors back to Unity. For example if everything went smoothly, the unity console is supposed to print out "User created successfully". If the username already exists, the console is supposed to print out "This Username already exists". The funny thing is, the Database knows the name already exists and does not save the information, but I still get "User created successfully".
So I think this might be a PHP problem because otherwise everything is working fine. So if somebody has experience with PHP, the help would be greatly appreciated.
First step is to figure out the issue is with your backend (PHP) or frontend (Unity), you need at least that much to start debugging and not just stabbing in the dark.
You can use any REST client like Postman/Insomnia/or even the ones built into your IDE, to send the request and inspect if the backend is behaving as you expect.
That way you remove frontend from the equation.
I actually fixed the problem. I dont know exactly how I did it, but now it works just the way I intended it to. The only thing I changed is that I stopped using the newer Unity Networking in my C# Script that was handling the packaging and went back to WWW. I think I might have been using the wrong function of Unity Networking but I am happy for now. But thanks for your help I will consider it in the future.
Does UWR have the same functionality as WWW?
Pretty sure yes, although I have never used WWW because it's been obsolete for so long even back when I started Unity.
If you have already isolated that frontend is the problem, then you can debug the request frontend sends in and see if anything is malformed.
You can do that by either modifying your backend to inspect the incoming request, or temporarily changing your frontend to send request to an echo service instead (which will echo back the request you just sent and you can inspect it)
hello i am working on doing like a lagre video player but with multiple videos in one scene for a vr game. The videos are located on a sdcard so outside the app. My issue is that it looks like loading multiple videos from an external storage on the videoplayer takes a lot of ressources and can make my app crash. Do you guys know any advises on how optimize or maybe dispatch the loading ?
unity videoplayer has always been very very bad, and such problem is common. you can't get reliable playback. people who need video end up paying for third party, there are in the asset store but check that there support your target as is compiled unmanaged dll
So I don’t know what this is called. And I’ve been googling for it, and the best I can find an example in blender and it doesn’t help me. What I am doing, and I have a quad set up with a two sided material that I’m rendering a sprite sheet on. I would like for the right frame to change based on the position of the camera. So that the camera is in front of the object, you see the face of the sprite, and vice versa with the sides and back. I don’t know how to check for an object angle relative to the source object
I feel like it’s atan , but I’m unsure how to use it like this
Anyone know how to utilize the tilemap rule tile system at runtime when I try to instantiate an object? Also in 3D
not exactly. I manually search my tilemaps to instantiate gameobjects
this is because i might have multiple tiles that correspond to one gameobject, etc, and I benefit from the control
Mathf.DeltaAngle(CameraTransform.eulerAngles.y, SpriteTransform.eulerAngles.y)
Something like that then you compare the angles and replace the sprite accordingly.
With Atan2 I think it would be something like this
Vector3 dir = SpriteTransform.position - CameraTransform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;```
if (angleAbs < 90f)
{
//forward sprite variation
}```
@cerulean waspHmm okay, do you know how to get the gameobject prefab sitting on a tile when painting with prefab brush?
i don't use any of unity's drawing tools
I have a custom drawing engine that I made
unity's drawing tools are ass
what I do is: on level load, search through tilemaps for all tilebases that require instantiation, and parse the data
this might be more involved than you need, and is quite expensive.
But you instantiate a prefab on the tile? How do I get information on what gameobject sits on the tile?
when I search, I have the information about the coordinate I just checked, and the TileBase
I have a big dictionary that links all my TileBase to a scriptableobject called BuildingObjectBase, which contains information for everything about a tile
including prefab, name, flags for logic etc
So you only use the tilemap to align stuff?
what do you mean?
You store all the data outside the tilemap
tilemap lives on a Grid. Grid allows you to use WorldToCell and visa versa to convert between cell and world space coordinates
all the data gets stored outside tilemap
Yeah so all you use it for is placing stuff on the right location
Okay so instead of me trying to ask tilemap what is on tile X I should just create my own dictionary
that's what I do, because I can tie a fuckload of logic to a tile, separately as a scriptable object
Okay thanks, makes sense
example
big dictionary links a tilebase to this scriptable object, and scriptable object has a field for the tilebase it corresponds to
You know when you use unitys palette drawing, if you draw terrain you want to create different edges, like a cliff for example if it is the outer tile, I need to same functionality at runtime
like an ingame level editor?
like in what's that game called that you build bridges
Kind of, but my player places 1 obj per turn
It should look kinda like that
So if user places a tile in the ocean the land expands and need to put the correct cliff tile
you probably want ruletiles for that
Yep
it is all a ruletile, with different logic, but is all one tilebase
But I am using 3D
And place gameobjects ```cs
Vector3 cellCenterPoint = _tilemap.GetCellCenterWorld(cell);
gameObject.transform.position = cellCenterPoint;
Because I'm not using SetTile I am thinking it would not detect my placement
SetTile is just a way to programatically write to a cell of the tilemap
is GetMethod slow? I have a Type corresponding to a singleton, and just need to call its GetInstance
cache it.. 1 time cost won't hurt
Hello, not sure this is the right place to post but here it goes.
I want my game to use the following Steam features:
- When a game is hosted by a friend, you can right click -> join to join their game
- When a game is hosted by a friend, and you want to join it, you can see the game being hosted in a list, without having to manually enter IP's.
Which parts of the Steamworks API would I need to use to achieve this?
Thanks a lot!
https://partner.steamgames.com/doc/api/ISteamMatchmaking#CreateLobby to create a lobby, https://partner.steamgames.com/doc/api/ISteamMatchmaking#InviteUserToLobby to invite a friend to a lobby, https://partner.steamgames.com/doc/api/ISteamFriends#GameLobbyJoinRequested_t to receive an event when the client tries to join a lobby from either an invite or directly through the friends list. Or if the game is not already open, it will launch with the +connect_lobby <64-bit lobby Steam ID> argument, which you can parse and pass to https://partner.steamgames.com/doc/api/ISteamMatchmaking#JoinLobby
Thank you so much for the detailed response
Has somebody a tutorial or something for nintendo switch joycons
Is there a way to modify the lightmap from C# and save it as an image?
Seems light the lightmap texture is readonly tried copying it but the same issue occured.
Not using URP.
Ah sorted it, just blit into RT and turn the RT into a regular texture, then your regular shenanigans
You gotta use the official Nintendo forum for any Nintendo question. There is considerable documentation about on their site. If you do not want to make the implementation yourself, you can use Rewired.
That stuff is typically protected by an NDA. Including access to the community support forums.
Is there any way for me to listen for a method being called, without explicitly setting up UnityEvents or anything
I need them to be dynamically created
Depends what you mean. There is a like a million way to "listen" to something.
uh
never used assembly
that sounds like it'd be overkill too,,
I might just deal with events
Sounds like you're trying to just avoid learning events. They really arent hard, and itll directly solve what you want. You dont need unityevent specifically, c# event exists
The only other thing I think is related is using override methods, so its only one method definition exists but you can change the implementation in child classes
anyone here can help me with graph nodes? I setup IEdgeConnectorListener to some nodes to connect, I am making the OnDropOutsidePort() working but the OnDrop() does not register
public void CreatePorts(IEdgeConnectorListener listener)
{
// Create an input port
input = InstantiatePort(Orientation.Horizontal, Direction.Input, Port.Capacity.Single, typeof(float));
input.portName = "Entrance";
inputContainer.Add(input);
//Debug.Log($"Port created: {input}, Orientation: {input.orientation}, Direction: {input.direction}, Capacity: {input.capacity}, Type: {input.GetType()}");
// Add an EdgeConnector to the input port
input.AddManipulator(new EdgeConnector<Edge>(listener));
// Create an output port
output = InstantiatePort(Orientation.Horizontal, Direction.Output, Port.Capacity.Single, typeof(float));
output.portName = "Exit";
outputContainer.Add(output);
//Debug.Log($"Port created: {output}, Orientation: {output.orientation}, Direction: {output.direction}, Capacity: {output.capacity}, Type: {output.GetType()}");
// Add an EdgeConnector to the output port
output.AddManipulator(new EdgeConnector<Edge>(listener));
}
the connection line its me before I left go of the mouse, after I let go it does not connect
I really need help with this been a full day can't find an answer to my problem, if any one know about this matter supper apreciated
Potentially complicated question: I am working on a 2d Isometric game right now, and have run into an issue where I am utilizing the Z as Y to add a semi 3rd dimension to my game. One of the other functions however is the use of a separate tilemap that draws over the other tilemap to show mechanics and options for selecting enemies.
The issue here is that the second tile map mentioned tilemap currently although respects the z heights of the floor tilemap, still draws over it due to the order in layer. Is there a way to basically make unity draw everything respecting z order as absolute? The first picture is an example of the problem, the second is a theorized solution that is not possible because it basically means making a option tilemap for each level.
My ideal is that like, i can force the engine to care about z positon on the tilemap more instead of the order in layer. And I think if they both have the same order it might be fine? im not sure to be honest
hoping someone might have an idea or at least a path to go down
does using layer groups not help? Not sure why layering here wouldnt work. Can always move the maps a smidgen towards the camera as well I would believe.
not sure what you exactly mean
you have orders of the layers and layer groups, you'd have a group for each map
ok im with you
but the problem is, if the red tilemap is grouped above
wouldn't the same problem persist?
cause it just be drawn over the floor
this has kind of been my problem lol
the red tilemap is already sort ordered above it, but i was hoping there might be like a "do sort order but also do z values more"
so like it would
or trying to explain is hard
i want it to look at like, z value 0, and do the layer order. Then look at z value 1, then do layer order
does that make sense?
Is this the results you're looking for? Because to me it seems like all that's happening in the top layer map is being rendered after the bottom map. Perhaps I'm not understanding, but layer groups are just using the transparent queue, but other than that you can also use URP render objects to have more control over lay rendering, but I'm not too sure if that's needed here.
yeah that is what im trying to emulate, the only issue i had with the way that effect was done is it used 4 layers instead of 2
since it was me making a floor tilemap for each height, and then an accompanying red tilemap
i can cook a good example
this is the same situation
the one on the left is the current tilemap system i have, the right is what i am trying to get to
so the red tiling isn't per map?
what do you mean per map?
are you using multiple tilemaps for the height
on the top one, no, it is just a tilemap for the floor (white and pink), and a tilemap for the red
in the right one, yes. There are 4 tilemaps being used:
floor height = 0 (bottom)
red height = 0 (the tile that you can barely see)
floor height = 1 (pink)
red height = 1
ok, and you're asking if you can do the right setup on the left without multiple maps if not sorting layers?
yes
no :)
man
2D is already restricting
ill have to see if switching to multiple tile maps will just break my game or not
otherwise i might need a new system for t his
this is the system btw
yeah, I'm not too sure how it's all batched
it depends up to unity honestly, but I could think of ways of doing it myself
its for showing move ranges and effect areas
and this looks chef's kiss
but its the second you get into other angles its been giving me that trouble you saw above
honestly I'd continue with it. You're just rendering quads anyway so I'd worry less about the performance.
whatcha mean by continue with it
well, if it doesn't break your game
example of man this doesn't work anymore
and its just because its rendering all the red over everything
eh, I don't see why that would happen if you're rendering it per layer
maybe im doing the layering wrong
top layer should always render last
let me snap my layers and maybe you can see what im doing stupid
so im dumb (could be the problem): Most of my stuff is on the default layer and Ive been working with just order in layer numbers:
Floor is defualt 0
attack is default 3

thank you lol
what do you think i should change it to lol
cause im a little noviced lol
you can keep to groups for the most part (layers for raycast if needed)
Does this have anything at all to do with #archived-code-advanced
also probably not
honestly not sure when it was ever code-related. #🔀┃art-asset-workflow
or #🖼️┃2d-tools
figured there might be a code based solution or something of that alignment
this'll be my last for this then just to say ima pick 2d-tools since that makes more sense
If I run Invoke, will I be guaranteed that the event will finish before going to the next line?
if (MyClass.StaticVar == true) { }
Will the execution order be guaranteed?
Yes. Code always runs synchronously unless there's async or coroutines involved; and never runs in parallel unless threaded (which is generally an obvious thing)
You can use the debugger to step over your code and see it execute
hi guys, I have made a new path data in a void function, and now i wanna add it in two public variables, they called 'paths' and 'pathsCache' because i wanna like do the changes on paths and then if user wanted to close the editor window, he'll gonna get a pop up window that he made some changes and if he wants to save it or not, but there's a problem, any changes i do in paths, it changes in pathsCache too, so how can i make it right?
is the data reference type or the path and pathCache are pointer?
i mean their type are the same data type, yes, but when i add them to their list, it's like they are synced together
doesnt sound advance but i dont know editor extension
their type are ofc the "same type" otherwise how can you assign one data to both
i mean if their type is reference or pointer
overlooked
are you try to assign them like below
public List<t> a, b;
public void Method(){
List<t> tem=new();
a=tem;
b=tem;
}
sorry my mistake if it's not advanced, but it's a reference
a and b are pointing to the same thing
it doesnt tell much
where you assign pathsCache and paths
oh they are two difference list
yes
so is pathsData class or reference type?
no
then the list elements in two list are pointing to same thing
and i think it happens here
if you want to isolate them then you need deep copy everything
no
btw the float x,y,x can be replaced with vector3
thank u so much for this <3
yes i know but i can't due to saving it in json file
hey guys
I have a specific question about managing terrain via c# script in editor
I have sampled heightmapped terrain
and terrain layers
also I have a texturemap info in a custom file that i load into unity
All I want is to set this texturemapping info to the TerrainData via c# script
here is the code
wld.textures.count is the count of the textures that terrain use
textureMap is the custom data that corresponds to the which texture2D should be visible on the specific [x, z]
still need help with this if any one that understand about nodegraphs
hello, guys i've been trying to re-implement Transform.cs of unity in pure c#.
its almost done but there's some problem with rotation.
the code is a single file with no dependencies, if anyone knowledgeable enough & wants to help me i would appreciate it a lot
You need to describe what the problem is directly, in the original message
Asking whether someone is available just makes you receive help later than normal
im not sure where the problem stems from. but when the parent rotation is on X axis, the child rotation is on its Y axis, while it should be like the parent -- on X axis.
What types are you using to recreate that Transform? The Unity types from the DLL, or the ones from System.Numerics?
System.Numerics
Okay I'm pretty sure all of the types in that namespace are set up to be Z-up, contrary to Unity that is Y-up
Vector3.UnitY is (0,1,0) so i dont think so
Doesn't mean that Y is considered as "up" here. I'd do some checks with dot products, rotations both in Unity and in pure C# to see if the results are identical
alright
If you're doing a modding API for your game, I'd suggest just referencing the Unity DLLs and using their types instead of trying to re-create them on your own
no im making a server in c# without unity
Okay then you don't need to base your code on Unity, especially for testing things as stuff will be different. I'd also suggest asking in a C#-specific server because it's not a Unity code issue anymore
just compare the cross product? left hand system is negative of right hand system
i dont see how handedness would be the problem tbh. if im using a different basis, the rotation of the child would still need be the same as rotation of the parent...
but whether y/z is "up" cant be determined......
if it was a problem with handedness, they would be both same rotation axis, but diferent in unity. which is not the case
if anyone wanna have a look: https://pastebin.com/9h1w81GM
What is this for? 🤔
Yeahhhh... suspiciousness increased by 3
its not what u think it is. as i said, making a unity server. this is not the only template i have multiple test templates (of many characters of many games) aka thats just a skin
That doesn't reassure what we think it is, that just reinforces it.
We don't support this sort of thing here. You'll need to find another community.
one sec
"I ensure my program works for many games" is what I read
So yeah no, this isn't going to be the place to ask. It's not even about Unity anymore, anyway
its not. its a skin i could modify it rn. and thats not the pt guys...
Great you have access to Unity, so why the heck are you trying to replicate its core features in a C# DLL that does not work with Unity at all?
Smells like DLL injection to me
im still stuck here though if anyone wants to help me i would appreciate it
We don't support this sort of thing here. You'll need to find another community.
No, as mods said this is pretty much over
Discord ToS does not allow server to discuss illegal activities, your action could get this entire server deleted. So unless you can prove what you are doing is not that, you should drop it.
You'll need to ask somewhere else
but its not illegal activities what are you talking about ? you only saw a mesh skin and i deleted the photo because u thought its some sort of dll injection ????????
like forget about that entirely. im not doing that. even if it was there's nothing here against it im asking for mathematics help. (and its not what u think it is)
Ripping assets from another game is illegal.
its not ripping its for study and its on sketchfab
im not publishing something
Your question and elaboration did not make sense in the first place. You replicate Unity's Transform so you can use it "somewhere else", but you have full access to Unity???
The other occurrences where the question contradicted with itself was from people trying to hide something, sooo
i told you im making a server
not unity. a c# server for game
you wanna see the entire source code ?
Unity has ways to run in headless mode for servers
I'm being suspicious yes. You buried yourself deep enough it seems, so ask in another server
your suspecion is useless. even if i was doing all sort of bad things if someone scrolls here i only asked for math help. it oculd be for studying or for drugs or for destroying the world. i only asked for math help. you told me no images so i deleted.
whatever though ill stop
Mods can see deleted posts so technically your images are still somewhere... But yeah I think we reached the end of the conversation
How exacly do i do bullet holes?
not a code question really. Decals I suppose?
Sounds like you know what you need to do then - modify the mesh as desired.
What
Here's a good primer: https://www.kodeco.com/3169311-runtime-mesh-manipulation-with-unity
I have a tilemap grid (3D) and now I have mostly 1x1 cubes placed on the grid, saved position in Dictionary. But imagine if I have an L shaped object that are 4 1x1 cubes. Is there a way to get what tiles that L shape is occupying? When I place the L I only check the tile I click and add to the Dict, but the other 3 tiles will still be "empty". Even if my collider check solves that problem I feel the Dict will be incomplete for other use cases.
You should have some kind of Shape class that has a list of coordinates for the shape
for example:
public class Shape {
List<Vector2Int> positions = new();
public IReadonlyList Positions => positions;
public Shape(params Vector2Int[] positions) {
this.positions.AddRange(positions);
}
}
static Shape LShape = new Shape(Vector2Int.zero, new Vector2Int(0, 1), new Vector2Int(0, 2), new Vector2Int(1, 0));
Is it possible to raycast down on all tiles an object is above? For example if I put down my L, can I from each corner raycast down and see what it covers on the grid, then do a worldtocell calculation to see what it is above?
As long as my object size stays within the grid size bounds
in a grid based tile based game like this raycasting would be overkill
and no raycasting is not possible unless you're using physics colliders which also seems like overkill for such a game
I do have box colliders on them atm
So basically you are proposing that I define the prefabs shape, like I, L, E etc.
I think trying to use the physics engine would be incredibly awkward an inefficient for such a game
I had another idea, but that is raycasting basically. If each shape consists of cubes, so L is 4 cubes, and each cube has a script on it, so before placement or on placement each cube will raycast straight down on each cell and propagate up to the placement script on all cells to check. Then I wouldn't have to define shapes, but rather build my prefabs in cubes
It would make a temp list with vector3ints
raycasting would be completely pointless
why raycast
don't you have a dictionary of occupied cells?
YOu said so yourself, just check the cells that your shape wants to occupy in the dictionary
Yeah but how does the object I hold on my cursor know what cells it is above, and especially if I add rotating function
Plane.Raycast
and Grid.WorldToCell
Right, because even if I have defined shapes beforehand I need to do math when rotating
not if you use Grid.WorldToCell
also the math for rotating if it's tetris style rotation is trivial
I have a 3D Tetris framework which does not use Raycasting, if you're interested in seeing how I did it DM me
r/explainlikeimfive. What was this man trying to do?
Read the chat, it's stated a few times
how can i access the mono compiler
the only free one is https://github.com/handzlikchris/FastScriptReload
im looking for a runtime scripting tool
You ship it with your game
Roslyn has a bunch of libraries that let you invoke the compiler at runtime (but not il2cpp)
how do i do that
You should be able to compile code on IL2CPP, unless there's some AOT incompatibility in the compiler code; you just won't be able to load it into the IL2CPP runtime, so it can't interact directly with the game code.
Well yeah but it's super easy to fuck up
Aka it's super limiting
Also there's things like linq.expressions, which work but again are limited in the same way
Well, you can't do anything with just a compiled assembly on IL2CPP. You'll also have to include a .NET runtime like Mono if you want to run it.
Does linq.Expressions work on macos?
apparently we can use Burst but i have no idea if it can access managed objects in any possible way
I think so?
(eg, use burst to dynamically create and add runtime objects while the game is running)
With an embedded runtime like Mono, you'll be able to do anything that Mono can do, including linq.expressions. But again, that code will be running completely separate from the game code
like i CAN use LuaJIT but idk if that would be as fast as C# itself or if it would be as fast as Burst
It's slow
I don't see how Burst relates to this discussion. It's compiled ahead of time.
also idk if BURST can be used to manually compile code at runtime
No, the Burst compiler is not included in builds.
And it only works with precompiled C# anyway, so you would need to include a C# compiler and Burst.
huh? so IOSs allow dynamic code generation now? pretty sure we can't do this in the past not sure now
It's a bit more nuanced but they have loosened the rules a lot
basically i want some way of runtime code compilation with support for Windows, MacOS, and Android
Presumably, you also want to be able to run this compiled code?
Because those are two different steps
That require two different solutions
not expert in c# and compiler design (i even didnt study the course on it)
but if you target so many platforms a interpreter+vm should be a proper choice
yea
preferably directly via embedded Mono JIT if possible
And is it fine that the code runs in its own runtime, separate from the game's code? You'd still be able to define some interface to allow some communication between them, but not full interoperability without some Reflection based magic.
JIT is not a simple matter on MacOS with Apple Silicon from what I can see. It's not impossible, but requires a permission flag and special memory allocation APIs.
I would start with trying to embed Mono, test it with precompiled .dlls. After that, you can embed a compiler like Roslyn, which should be easier.
honestly it would be great if i could find a precompiled LLVM for windows, mac os, and android
but no such precompiled libs exist ;-;
like, we could use HPC# but idk how that works nor how we would communicate back to the C# runtime since managed objects are not allowed
How are you going to compile that? Burst is precompiled in the editor, the compiler is not included in builds. And you'll need to compile C# to IL first.
idk
basically i need to support compiling (with optimizations) and executing for x86 and arm64 at runtime
where can i find prebuilt C# compilers for windows, mac, and android
as i notice Mono includes LLVM which itself takes ages to build
The most popular C# compiler, Roslyn, is itself written in C#. You can run it directly within Unity, without needing to compile for different platforms.
how do i do that ?
without paying for the Unity Asset version
and without the Free Trial version
The compiler is in the Microsoft.CodeAnalysis.CSharp NuGet package.
https://www.nuget.org/packages/Microsoft.CodeAnalysis.CSharp
To install a NuGet package, you can either use a third party Unity editor tool for that or install it manually by downloading it and all of its dependencies directly from the nuget.org website.
which version would be supported by Unity
.NET Standard 2.0
A shared package used by the Microsoft .NET Compiler Platform ("Roslyn").
Do not install this package manually, it will be added as a prerequisite by other packages that require it.
More details at https://aka.ms/roslyn-packages
This package was built from the source at https://github.com/dotnet/roslyn/commit/e091728607ca0...
Some of these are already available in Unity. Just place the Microsoft.CodeAnalysis.CSharp and Common dlls in Unity and it will tell you in the console which .dlls are missing.
Microsoft.CodeAnalysis.CSharp.pdb
Microsoft.CodeAnalysis.CSharp.dll
Microsoft.CodeAnalysis.CSharp.xml
do i need all 3
No, just the .dll.
plus all these
cs
de
es
fr
it
ja
ko
pl
pt-BR
ru
tr
zh-Hans
zh-Hant
for */Microsoft.CodeAnalysis.CSharp.resources.dll
I believe there is some way to strip localization from it, but I believe this has to be included.
eg ```
microsoft.codeanalysis.csharp.4.8.0.nupkg\lib\netstandard2.0\cs\Microsoft.CodeAnalysis.CSharp.resources.dll
microsoft.codeanalysis.csharp.4.8.0.nupkg\lib\netstandard2.0\de\Microsoft.CodeAnalysis.CSharp.resources.dll
microsoft.codeanalysis.csharp.4.8.0.nupkg\lib\netstandard2.0\es\Microsoft.CodeAnalysis.CSharp.resources.dll
...
what directory of my project do i put them into
It doesn't matter.
imma put them in Assets\C# Nugets\
how do i get unity to use them
Unity doesn't use it, you'll use it in your scripts.
ok
This will not work in IL2CPP, because it relies on Reflection.Emit, which is not AOT compatible.
But it should work on the Mono backend, which can run on Windows, Android and maybe Mac x86.
I know
Hello all,
So Im currently trying to fix a bug that was introduced in MagicLeap which causes a black screen on compile on Android devices: https://forum.unity.com/threads/issue-with-android-skipped-rendering-frame-because-gfxdevice-is-in-invalid-state-device-lost.1449145/
The fix as of write now is to remove MagicLeap XR from the project, however Im having some trouble doing that.
As both the AR feature/MagicLeap package are unremovable.
I've tried going into the package-lock.json and manifest.json to try and remove them and then delete the library folder.
And they always come back.
At this point Ir eally dont know what to do/look for
Obviously something is still relying on them but I can't find what.
