#archived-code-advanced

1 messages · Page 89 of 1

harsh lion
#

If you have many more objects you can look into splitting them up into cells

#

Many = orders of magnitude more

brittle charm
#

Would fixed update be suitable?

harsh lion
dapper cave
#

hehe. the dumbest way is often the best.

woeful kraken
dapper cave
north tundra
#

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.

scenic forge
# north tundra I’m not at my computer right now, but the shuffle I used essentially loops throu...

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 ...

obsidian glade
# north tundra That’s an accidental leave-behind from when I was playing with different sizes, ...

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, your yf being 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

north tundra
grand dagger
#

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?

grand dagger
#

please do ping me if you know how to do it. i really need this

north tundra
#

Let me know if there's any code you need me to show.

#

There seems to be a diagonal pattern of bumps.

obsidian glade
# north tundra

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)

north tundra
#

Alright, that appeared to be what was going on. Thanks for the help :)

obsidian glade
#

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

north tundra
#

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).

shrewd vale
#

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.

compact ingot
#

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

shrewd vale
#

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 )

compact ingot
#

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

grand dagger
#

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.

polar rivet
#

this is my code i need help with my finite state machine. the pause and investigate states just dont work

hardy girder
#

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

honest hull
#

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

untold moth
honest hull
#

thinking aout this Im pretty sure its impossible

untold moth
#

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#.

honest hull
#

yeah I think ill have to write an algo
is there a way for me to reinterpret the shadergraph shaders as a text file?

honest hull
#

oooo thanks!!

river tartan
#

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;

tired fog
#

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
}
tired fog
#

Any hope?

regal olive
#

how can you get ITilemap? cant find any help online this is my last option is here.

regal olive
half swan
upbeat path
#

Still no excuse to post the same thing in 3 different channels

regal olive
#

sorry but its importanted, unity dont give any good examples to use ITilemap, I've look everywhere

inland knoll
#

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?

lament salmon
inland knoll
lament salmon
inland knoll
#

I'm wonder how you got that entire area

lament salmon
#

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

lament salmon
#

Perpendicular direction of the navmesh edge

inland knoll
#

Hm, alright. Thanks!

tall dirge
#

Radar

full ledge
#

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.

sly grove
#

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

full ledge
sly grove
sly grove
#

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

full ledge
tired fog
#

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

tired fog
#

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.

knotty pollen
#

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.

chrome sparrow
#

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.

scenic forge
knotty pollen
#

i feel like my implementation is just wrong but idk why

scenic forge
#

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)

grizzled frigate
#

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);
    }
}
novel plinth
#

1st, why are you doing this ?

    List<GameObject> enemies = new List<GameObject>();
    enemies.Clear();
  1. 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

hardy sentinel
#

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?

novel plinth
#

uitk for custom editors is like easy-mode, no joke

tiny pewter
#

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

hardy sentinel
#

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?

novel plinth
hardy sentinel
#

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?

novel plinth
#

absolutely 😌

hardy sentinel
#

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 😅

novel plinth
#

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

hardy sentinel
#

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

novel plinth
#

with uitk + inlinestyles, you can do less than 1 h, trust me

hardy sentinel
#

afraid gonna end up making it look like The Elder Scrolls: Add To List Dropdown xD

hardy sentinel
novel plinth
#

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

hardy sentinel
#

alright thanks will give it some thought

novel plinth
#

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!

hardy sentinel
#

it is, but.. well add that to drawing a full list (including buttons) and drawing its content.. it stacks up 😛

novel plinth
hardy sentinel
#

👀

#

ok definitely gonna give it a try 😄

#

thanks

novel plinth
#

goodluck

novel plinth
#

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 😅

hardy sentinel
#

did they actually intend for it to replace UGUI?

novel plinth
#

I'm guessing yes

stuck onyx
#

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

grizzled frigate
# novel plinth 1st, why are you doing this ? ``` List<GameObject> enemies = new List<GameOb...

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.

sly grove
#

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

grizzled frigate
sly grove
#

Which lines

grizzled frigate
#

List<GameObject> enemies = new List<GameObject>();

sly grove
#

There's also still the Component stuff which makes little sense and is also slow as mentioned

grizzled frigate
#

then how should I get all enemies and put them in a list?

sly grove
#

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

rugged radish
#
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)

dusty wigeon
#

If the code is critical, you should convert it to a standard for loop.

rugged radish
dusty wigeon
rugged radish
#

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

rugged radish
# dusty wigeon 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

rocky mica
#

seems very nice

#

we currently use odin for inspectors so anything open source might be worth looking into

warm pebble
#

Guys how can I get normal vector of trigger collider ?

regal lava
#

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

warm pebble
rocky mica
#

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)

upbeat path
#

Don't cross post

jovial burrow
upbeat path
jovial burrow
#

general, beginner

upbeat path
#

you have it in unity-talk, keep it there

sage spindle
#

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

rocky mica
#

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

north tundra
#

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; }
dusty wigeon
urban warren
#

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).

austere jewel
#

I don't understand the question, you want a rotation perpendicular to that one?

urban warren
#

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

austere jewel
#

pos: position + lineRot * new Vector3(0, halfLineHeight, 0), rot: lineRot * Quaternion.Euler(90, 0, 0)

#

If you don't understand why, lmk

urban warren
#

Damn... you're right that is it... I was doing stuff with AxisAngle and LookRotation and multiplying vector directions by the rotation and stuff...

austere jewel
#

There are certainly other ways to do it too

urban warren
#

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! ❤️

distant fable
#

Hi friends, I want to Import and Export 3d model in unity at runtime, do you guys have any solution?

regal olive
#

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.

austere jewel
regal olive
austere jewel
#

does the stacktrace show any information?

regal olive
#

I coded an extension for it but it doesn't show what called it

#

It gived error (maybe because of assembly/dll difference)

grave apex
upbeat path
# regal olive

Doesn't matter, that wont show you what you want anyway, OnDestroy is called by Unity not by your code

tiny pewter
#

ondestroy (or disable) are callback from engine and i think it cant tell you who destroy your object

austere jewel
#

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

plush narwhal
#

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.

tiny pewter
#

what i found on docu

public static void Sort<T>(this NativeArray<T> array)
    where T : struct, IComparable<T><----
plush narwhal
tiny pewter
#

T needs to implement this interface

grave apex
#

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

upbeat path
grave apex
upbeat path
#

yes, generate a hash using both the int and the string

grave apex
#

So something like

hash = numID ^ stringID;

where the ^ is a XOR operator?

grave apex
#

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

upbeat path
#

why not

int x = _numericalID.GetHashCode();
int y = _stringID.GetHashCode();
// Do something with x and y
grave apex
#

And make the numerical id nullable or something

#

But then it wouldn't be serializable so idk

grave apex
upbeat path
#

anything you want, you know your data I do not

grave apex
#

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

upbeat path
#

why would it not be possible? you just need to turn 2 ints into 1

#

have you done any research into creating hash values?

grave apex
#

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

grave apex
upbeat path
#

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

grave apex
upbeat path
#

want to bet? RTFM

grave apex
#

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

upbeat path
#

wrong

grave apex
#

No

upbeat path
#

yes

grave apex
#

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

upbeat path
#

From the MS Docs

grave apex
#

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?

upbeat path
#

because that is within the same domain

#

Again RTFM

grave apex
#

I'll just stick with using the slightly memory inefficient approach of having 3 dicts loaded in memory

upbeat path
#

you can just do what sensible people do, write your own hashing algorithm

grave apex
#

No point because the logic I described may not actually even be possible

flint sage
#

I think theoretically the hash code of non strings is stable but it's not guaranteed

grave apex
flint sage
#

It's just a link describing why, not a solution

grave apex
#

But I'm not serializing hash codes anyways so that isn't relevant in my situation

flint sage
#

Sure but it's interesting

grave apex
#

Yeah, defo something to look deeper into in the future

tiny pewter
#

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

grave apex
tiny pewter
#

let says if you have three instances

  1. {x,"a"}
  2. {x,"b"}
  3. {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
grave apex
#

It's like a paradox so it's not possible

tiny pewter
#

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

grave apex
sleek terrace
#

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?

devout hare
#

The difference between 1000 fps and 2000 fps is only 0.5 ms per frame. Which is not a lot.

sleek terrace
#

I see, so further optimizations on this arena is simply pointless micro-optimizations and I should put my efforts somewhere else

sly grove
#

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

devout hare
#

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

sleek terrace
#

Got it. Thank you gentlemen @sly grove @devout hare

fickle mountain
#

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.

long ivy
#

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

sly grove
sage radish
# fickle mountain Probably more of C# question than actually Unity, but is there a way to read&wri...

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().

ashen hill
#

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?

ashen hill
#

with like that

dusty wigeon
#

And... ?

ashen hill
#

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?

dusty wigeon
#

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 ?

ashen hill
#

oh, ok

half swan
ashen hill
#

So, when I create an ScriptableObject, if you write the CreateAssetMenu attribute, that SO is added to the Create tab, right?

dusty wigeon
ashen hill
#

So, I want to create just one SO asset.

dusty wigeon
ashen hill
#

Oh, there's a way to first create it and then erase the attributes

dusty wigeon
ashen hill
dusty wigeon
ashen hill
#

oh I see

#

thanks

sage radish
ashen hill
plain parrot
#

what separates an intermediate coder from a advanced coder?

livid kraken
#

Experience

timid sinew
#

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

plain parrot
#

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.

timid sinew
# plain parrot oh thats important to know. Any recommendations where to start? Is that somethin...

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

tiny pewter
#

data structure and algorithm...

timid sinew
#

im doing a F# project in Unity right now after reading some books on lambda calculus and proper F# personally

timid sinew
#

id assume that's more inferred but yes

plain parrot
#

I would like to be a great gameplay programmer if i had say what my main thing is.

#

thank you

timid sinew
#

no problem as i said learn stuff and implement it in mini projects

plain parrot
#

yep thats best strategy

grave apex
#

This is useful for like config files and stuff

fresh basalt
#

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

strange dragon
#

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};
}
tiny pewter
#

not code advanced

#

field:serializefield

strange dragon
# tiny pewter not code advanced

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?

tiny pewter
#

stick in here, include the field: in the attribute

strange dragon
tiny pewter
strange dragon
ashen hill
#

Thanks

unborn ether
#

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.
fresh basalt
#

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

grand dagger
#

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.

dusty wigeon
# plain parrot what separates an intermediate coder from a advanced coder?

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.

compact ingot
plain parrot
#

thank you, some good answers.

sharp monolith
#

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

neat harness
#
[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.

tiny pewter
#

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;
}
untold moth
#

Basically to apply the attribute to the backing field rather than the property.

tiny pewter
#

dont cross post, stick to code beginner

rustic nest
#

ok

kind sigil
#

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?

fresh vortex
#

velocity?

#

you can manipulate the velocity

kind sigil
#

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?

fresh vortex
#

try it and see

fresh salmon
#

After impact. You can get the applied force with Collision:impulse (vector)

mystic saffron
#

bro my brain trying to read this is kekwait

#

its like yall speaking a different language.

misty glade
#

As a personal idiom, I use the following when I want to rebuild items in a container:

  1. Destroy all children (using Destroy() and transform.childCount with GetChild(i))
  2. 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?

tall ferry
misty glade
#

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..

#

If I don't DestroyImmediate() then my utility method GetMinimimSize() sees both the old and new game objects

tall ferry
misty glade
#

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)

misty glade
#

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?

misty glade
#

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..?

sly grove
misty glade
#

Like, I'd have to write a bunch of plumbing to add the original listeners back after the game is closed

sly grove
#

but yes this is editor only

misty glade
#

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

sly grove
#

Thinking about a clean solution here 🤔

misty glade
#

Yeah..

sly grove
#

My initial thoughts were also adding another "invisible" button on top

#

but then making the button transitions still work might be messy

misty glade
#

I'm honestly thinking the invisible button thing is best but.. it's sort of a lot of work

sly grove
#

I think the click logic itself would be simple

misty glade
#

It breaks too if I've created anything more complex then a button with "delete" on it

sly grove
#

you can just Invoke the onClick event

misty glade
#

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

sly grove
#

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;```
misty glade
#

I think the persistent events get called as a "separate thing"

#

I'd have to chceck

sly grove
#

Where ShowAreYouSureDialogue shows the dialogue and calls Invoke on oldEvt

#

nah it's all part of the UnityEvent object

misty glade
#

ie, I don't think modifying onClick has anything to do with the list of persistent listeners

sly grove
#

There's nothing about persistent listeners on Button

#

it's all part of the UnityEvent

misty glade
#

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!

sly grove
#

nice

misty glade
#

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

tender fern
#
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".

untold moth
#

probably any public field/property in GameObject.

#

This is basically the same as setting the fields/properties values after the constructor.

untold moth
tender fern
#

@untold moth Could you please provide an example?

untold moth
tender fern
#

Yes that was the original code

#

I understand now, thanks

misty glade
#

@tender fern That's not a unity feature, that's a c# feature ("object initializers").

tender fern
#

@misty glade Yep, initializing an object!

misty glade
#

Oh, uh, I see you messaged the same in general already

tender fern
#

😜

timber flame
#

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

novel plinth
#

I'd do just fake it with meta-ball + custom render feature for things like this

#

something like that

half pilot
#

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

half pilot
#

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?

tiny pewter
#

is it code question? probably ask in ui/ux or unity talk

half pilot
#

Yes I apologize it is Unity related. Just feeling my way around here is all

#

Thanks :)

ruby bison
#

can someone help me on how to raycast out of a sphere :()

#

i need someone to help me on the math :'()

sage spindle
#

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?

tiny pewter
#

dont cross post

#

keep the market in static list

cyan shuttle
# sage spindle I am implementing a market of goods per town, so 5 towns, 5 markets. What is a g...

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...

▶ Play video
#

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

dreamy cobalt
#

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?

dusty wigeon
cyan shuttle
#

🙂

weak zenith
#

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?

misty glade
#

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

feral dirge
#

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!

sage spindle
#

@feral dirgeEasy save can prob do it

dusty wigeon
upbeat path
feral dirge
knotty pollen
#

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

knotty pollen
#

not really looking for help, just curious if this type of behavior is a known thing.

sly grove
#

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

knotty pollen
#

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

sly grove
#

could be a script execution order issue

#

especially if there's coroutines involed and you're depending on WaitForSeconds delays

thorn flintBOT
stoic trout
#

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.

tiny pewter
#
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

stoic trout
tiny pewter
#

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

stoic trout
#

Ohh okay. This helps a lot, thank you!

vocal violet
#

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;
}
odd remnant
#

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 heartblue !

upbeat path
vocal violet
#

Yeah, but I can't use it from a Thread

#

And these are binary files

tiny pewter
#

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

vocal violet
tiny pewter
#

i guess there is no BufferedInputStream

scenic forge
#

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.

vocal violet
# scenic forge Why do you need to read it from a thread?

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

scenic forge
#

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.

tired fog
#

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

sly grove
tired fog
#

interesting

vocal violet
pseudo onyx
#

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);



untold moth
sly grove
#

(I assume this is 2d?)

pseudo onyx
#

This is 2.5 D

#

So its on a 3D plane but I want to restrict the movement to the x and y axis

sly grove
#

Then what I wrote should work

#

You don't need trigonometry

pseudo onyx
sly grove
#

Now if it's not rotating at all it's probably being overwritten by an animator or something

pseudo onyx
untold moth
#

None of these are advanced questions btw.

sly grove
#

effectively it will set the rotation of the Transform such that its right axis is facing in that way

full ledge
#

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.

tiny pewter
#

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

shadow shore
#

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```
#

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

tiny pewter
#

It sounds impossible (at least no efficient way to do this) but i am not expert in computer graphics....

tiny pewter
#

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

sage radish
#

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.

tiny pewter
#

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

dusty wigeon
shadow shore
#

I suppose i could assign each one of the spawned objects a small script with references to each other

scenic forge
#

I'm looking to migrate to STJ with Unity 2022 and IL2Cpp backend, is there any big caveat? How should I set the linker?

proper finch
#

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?

novel plinth
#

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>
novel plinth
#

not quite sure if this already fixed or not in Unity

scenic forge
novel plinth
#

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

scenic forge
#

Cool.

novel plinth
# scenic forge Cool.

why migrating? if you're planning to publish it as package/lib it will be pain tho, just a heads up

scenic forge
#

Nah it's for my own game, have some free time and figure now it's a good chance to look into STJ.

novel plinth
#

nice! 👍

novel plinth
# scenic forge Cool.

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

scenic forge
#

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.

pseudo onyx
#

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;
            }

sly grove
#

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;```
pseudo onyx
#

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;
            }

sly grove
#

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

terse oyster
#

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?

scenic forge
#

Are other users' accounts stored on the device, or are they stored on your backend server?

terse oyster
#

Well... I use unity authentication

scenic forge
#

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.

terse oyster
#

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?

obsidian glade
terse oyster
#

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?

spiral swift
#

and it doesn't try to go around it or anything

obsidian glade
pale lion
spiral swift
#

the actual detection works fine

#

the behavior is the issue

pale lion
#

Ok i suppose this is in your Update func? Can you also Show the behavior code

spiral swift
#
    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

terse oyster
pale lion
#

If Not an attacker has No reason to decompile your Code He can Just write the brute force himself

obsidian glade
pale lion
#

And im pretty sure unity has safety measures against brute force when authing

fresh salmon
#

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

spiral swift
#

still no idea what I could do

pale lion
spiral swift
#

no problem

#

still though, any tips for steering behavior?

#

or well, steering behavior where the target is always present

pale lion
#

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

spiral swift
#

they walk towards the target

pale lion
#

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

robust bramble
#

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.

vague pike
#

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

compact ingot
# vague pike Hey guys, sorry I'm not so active on this forum but I'd like some point of view ...

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.

spiral swift
# pale lion Your avoidance just turns them into the opposite direction but it should Turn th...

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

vague pike
sage spindle
#

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

prime mist
#

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

sage spindle
#

And skip onenable?

untold moth
sage spindle
#

@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

untold moth
#

Another option is using an event queue.

plain granite
#

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

sage radish
plain granite
sage radish
plain granite
#

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

tardy lynx
fallow dune
#

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.

bleak citrus
#

I see nothing inherently wrong there. You'll need to provide specifics.

plush talon
#

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.

thin mesa
plush talon
#

Lifesaver, thank you!

thin mesa
#

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

sage radish
thin mesa
#

yes

sage radish
#

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.

thin mesa
#

damn, alright

soft marlin
scenic forge
#

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.

terse oyster
# pale lion Are you storing your Account Info in your Code?

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.

sly grove
#

Why would player login info ever be involved at edit time in your Unity project

mortal owl
#

did you find a solution to this? I'm having a similar issue

jagged stone
mortal owl
vernal rose
#

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

proven crane
#

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.

scenic forge
#

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.

proven crane
# scenic forge First step is to figure out the issue is with your backend (PHP) or frontend (Un...

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.

scenic forge
#

WWW is obsolete though so you should probably not use it.

#

Should use UWR instead.

proven crane
#

Does UWR have the same functionality as WWW?

scenic forge
#

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)

noble halo
#

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 ?

dapper cave
calm hill
#

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

sage spindle
#

Anyone know how to utilize the tilemap rule tile system at runtime when I try to instantiate an object? Also in 3D

cerulean wasp
#

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

regal lava
#
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
  }```
sage spindle
#

@cerulean waspHmm okay, do you know how to get the gameobject prefab sitting on a tile when painting with prefab brush?

cerulean wasp
#

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.

sage spindle
#

But you instantiate a prefab on the tile? How do I get information on what gameobject sits on the tile?

cerulean wasp
#

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

sage spindle
#

So you only use the tilemap to align stuff?

cerulean wasp
#

what do you mean?

sage spindle
#

You store all the data outside the tilemap

cerulean wasp
#

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

sage spindle
#

Yeah so all you use it for is placing stuff on the right location

cerulean wasp
#

yes

#

that is tilemap's #1 job

sage spindle
#

Okay so instead of me trying to ask tilemap what is on tile X I should just create my own dictionary

cerulean wasp
#

that's what I do, because I can tie a fuckload of logic to a tile, separately as a scriptable object

sage spindle
#

Okay thanks, makes sense

cerulean wasp
#

example

#

big dictionary links a tilebase to this scriptable object, and scriptable object has a field for the tilebase it corresponds to

sage spindle
#

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

cerulean wasp
#

like an ingame level editor?

#

like in what's that game called that you build bridges

sage spindle
#

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

cerulean wasp
#

you probably want ruletiles for that

sage spindle
#

Ya exactly

#

But at runtime

cerulean wasp
#

let me get a p;ic

#

that is what a RuleTile looks like

sage spindle
#

Yep

cerulean wasp
#

it is all a ruletile, with different logic, but is all one tilebase

sage spindle
#

But I am using 3D

#

And place gameobjects ```cs
Vector3 cellCenterPoint = _tilemap.GetCellCenterWorld(cell);
gameObject.transform.position = cellCenterPoint;

cerulean wasp
#

you should check the implementation

#

it might have support for it

sage spindle
#

Because I'm not using SetTile I am thinking it would not detect my placement

cerulean wasp
#

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

novel plinth
#

cache it.. 1 time cost won't hurt

unborn relic
#

Hello, not sure this is the right place to post but here it goes.

I want my game to use the following Steam features:

  1. When a game is hosted by a friend, you can right click -> join to join their game
  2. 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!

sage radish
# unborn relic Hello, not sure this is the right place to post but here it goes. I want my gam...

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

unborn relic
tender wagon
#

Has somebody a tutorial or something for nintendo switch joycons

fossil tangle
#

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

dusty wigeon
compact ingot
edgy shard
#

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

dusty wigeon
edgy shard
#

uh
never used assembly

#

that sounds like it'd be overkill too,,

#

I might just deal with events

tall ferry
# edgy shard 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

plush elk
#

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

strong harbor
#

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

regal lava
#

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.

strong harbor
#

not sure what you exactly mean

regal lava
#

you have orders of the layers and layer groups, you'd have a group for each map

strong harbor
#

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?

regal lava
#

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.

strong harbor
#

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

regal lava
#

so the red tiling isn't per map?

strong harbor
#

what do you mean per map?

regal lava
#

are you using multiple tilemaps for the height

strong harbor
#

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

regal lava
#

ok, and you're asking if you can do the right setup on the left without multiple maps if not sorting layers?

strong harbor
#

yes

regal lava
#

no :)

strong harbor
#

man

regal lava
#

2D is already restricting

strong harbor
regal lava
#

if you look back at old 2D games they do just that anyway

#

for those isometric ones

strong harbor
#

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

regal lava
#

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

strong harbor
#

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

regal lava
#

honestly I'd continue with it. You're just rendering quads anyway so I'd worry less about the performance.

strong harbor
#

whatcha mean by continue with it

regal lava
#

well, if it doesn't break your game

strong harbor
#

example of man this doesn't work anymore

#

and its just because its rendering all the red over everything

regal lava
#

eh, I don't see why that would happen if you're rendering it per layer

strong harbor
#

maybe im doing the layering wrong

regal lava
#

top layer should always render last

strong harbor
#

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

regal lava
strong harbor
#

thank you lol

#

what do you think i should change it to lol

#

cause im a little noviced lol

regal lava
#

you can keep to groups for the most part (layers for raycast if needed)

austere jewel
regal lava
#

also probably not

strong harbor
#

that is fair, topic has probably left

#

where should we go?

austere jewel
strong harbor
#

this'll be my last for this then just to say ima pick 2d-tools since that makes more sense

sage spindle
#

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?

austere jewel
#

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

fickle ether
#

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?

tiny pewter
#

is the data reference type or the path and pathCache are pointer?

fickle ether
tiny pewter
#

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;
}
fickle ether
#

sorry my mistake if it's not advanced, but it's a reference

tiny pewter
#

a and b are pointing to the same thing

fickle ether
#

let me see if i can show u the code

tiny pewter
#

it doesnt tell much
where you assign pathsCache and paths

fickle ether
#

in the same class

tiny pewter
#

oh they are two difference list

fickle ether
#

yes

tiny pewter
#

so is pathsData class or reference type?

fickle ether
#

class

#

let me show

tiny pewter
#

no

fickle ether
tiny pewter
#

then the list elements in two list are pointing to same thing

fickle ether
tiny pewter
#

if you want to isolate them then you need deep copy everything

fickle ether
#

oh

#

like assigning every single value in the list, one by one

tiny pewter
#

no

#

btw the float x,y,x can be replaced with vector3

fickle ether
night cosmos
#

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]

plush elk
wet sail
#

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

fresh salmon
#

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

wet sail
#

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.

fresh salmon
#

What types are you using to recreate that Transform? The Unity types from the DLL, or the ones from System.Numerics?

wet sail
#

System.Numerics

fresh salmon
#

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

wet sail
#

Vector3.UnitY is (0,1,0) so i dont think so

fresh salmon
#

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

wet sail
#

alright

fresh salmon
#

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

wet sail
#

no im making a server in c# without unity

fresh salmon
#

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

tiny pewter
#

just compare the cross product? left hand system is negative of right hand system

wet sail
#

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...

tiny pewter
#

but whether y/z is "up" cant be determined......

wet sail
#

if it was a problem with handedness, they would be both same rotation axis, but diferent in unity. which is not the case

humble leaf
#

What is this for? 🤔

fresh salmon
#

Yeahhhh... suspiciousness increased by 3

wet sail
#

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

humble leaf
#

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.

wet sail
#

one sec

fresh salmon
#

"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

wet sail
#

its not. its a skin i could modify it rn. and thats not the pt guys...

fresh salmon
#

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

wet sail
#

what ????

#

does that even mean

#

whatever

#

forget about it

wet sail
fresh salmon
#

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

scenic forge
fresh salmon
#

You'll need to ask somewhere else

wet sail
#

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)

scenic forge
#

Ripping assets from another game is illegal.

wet sail
#

im not publishing something

fresh salmon
#

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

wet sail
#

i told you im making a server

#

not unity. a c# server for game

#

you wanna see the entire source code ?

fresh salmon
#

Unity has ways to run in headless mode for servers

wet sail
#

for the server?

#

and ?

#

like you are just being.... rn.

fresh salmon
#

I'm being suspicious yes. You buried yourself deep enough it seems, so ask in another server

wet sail
#

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

fresh salmon
#

Mods can see deleted posts so technically your images are still somewhere... But yeah I think we reached the end of the conversation

grave raft
#

How exacly do i do bullet holes?

sly grove
grave raft
#

Not the decals

#

I need to actualy change the geometry of a mesh

sly grove
#

Sounds like you know what you need to do then - modify the mesh as desired.

grave raft
#

What

sly grove
sage spindle
#

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.

sly grove
#

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));
sage spindle
#

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

sly grove
#

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

sage spindle
#

I do have box colliders on them atm

#

So basically you are proposing that I define the prefabs shape, like I, L, E etc.

sly grove
#

I think trying to use the physics engine would be incredibly awkward an inefficient for such a game

sage spindle
#

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

sly grove
#

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

sage spindle
#

Yeah but how does the object I hold on my cursor know what cells it is above, and especially if I add rotating function

sly grove
#

and Grid.WorldToCell

sage spindle
#

Right, because even if I have defined shapes beforehand I need to do math when rotating

sly grove
#

not if you use Grid.WorldToCell

#

also the math for rotating if it's tetris style rotation is trivial

upbeat path
errant thorn
craggy spear
#

Read the chat, it's stated a few times

fervent dagger
#

how can i access the mono compiler

#

im looking for a runtime scripting tool

flint sage
#

You ship it with your game

#

Roslyn has a bunch of libraries that let you invoke the compiler at runtime (but not il2cpp)

fervent dagger
#

how do i do that

sage radish
flint sage
#

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

sage radish
#

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.

novel plinth
#

Does linq.Expressions work on macos?

fervent dagger
#

apparently we can use Burst but i have no idea if it can access managed objects in any possible way

flint sage
#

I think so?

fervent dagger
#

(eg, use burst to dynamically create and add runtime objects while the game is running)

sage radish
#

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

fervent dagger
#

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

flint sage
#

It's slow

sage radish
#

I don't see how Burst relates to this discussion. It's compiled ahead of time.

fervent dagger
#

also idk if BURST can be used to manually compile code at runtime

sage radish
#

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.

novel plinth
# flint sage I think so?

huh? so IOSs allow dynamic code generation now? pretty sure we can't do this in the past not sure now

flint sage
#

It's a bit more nuanced but they have loosened the rules a lot

fervent dagger
#

basically i want some way of runtime code compilation with support for Windows, MacOS, and Android

sage radish
#

Because those are two different steps

#

That require two different solutions

tiny pewter
#

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

fervent dagger
#

preferably directly via embedded Mono JIT if possible

sage radish
fervent dagger
#

yea

#

as long as we can still have some way to communicate

sage radish
#

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.

fervent dagger
#

yea

#

max x86 is fine tho

sage radish
#

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.

fervent dagger
#

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

sage radish
fervent dagger
#

idk

#

basically i need to support compiling (with optimizations) and executing for x86 and arm64 at runtime

fervent dagger
#

where can i find prebuilt C# compilers for windows, mac, and android

#

as i notice Mono includes LLVM which itself takes ages to build

sage radish
fervent dagger
#

how do i do that ?

#

without paying for the Unity Asset version

#

and without the Free Trial version

sage radish
#

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.

fervent dagger
#

which version would be supported by Unity

sage radish
#

.NET Standard 2.0

fervent dagger
sage radish
fervent dagger
#
Microsoft.CodeAnalysis.CSharp.pdb
Microsoft.CodeAnalysis.CSharp.dll
Microsoft.CodeAnalysis.CSharp.xml

do i need all 3

sage radish
#

No, just the .dll.

fervent dagger
#

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

sage radish
#

I believe there is some way to strip localization from it, but I believe this has to be included.

fervent dagger
#

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

sage radish
fervent dagger
#

imma put them in Assets\C# Nugets\

fervent dagger
#

how do i get unity to use them

sage radish
fervent dagger
#

ok

sage radish
#

But it should work on the Mono backend, which can run on Windows, Android and maybe Mac x86.

real canopy
#

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.