#archived-code-advanced

1 messages · Page 21 of 1

undone coral
#

the raw json body of my request is encrypted not letting the api work as intended
what do you mean encrypted?

#

hmmm..

#

Do I need to manage this myself by creating/destroying texture objects as-needed
do you mean creating and Destroy (or Dispose) on Texture2D objects?

#

are you creating textures from files?

#

is this for creating a map?

torn basalt
#

Are you guys familiar with Mesh Generation? I am creating a plane from 4 points using a raycast. After creating the mesh (wall) I noticed that the mesh position and Rotations are zero'd out and not the position that it was created at.

The Mesh shows up in the correct place but not the origin point. Is is possible to generate a mesh from 4 points and the assign a position and rotation to the mesh based on those points? I am always calculating the center between the 4 points but that still hasn't helped.

tight tapir
tight tapir
# undone coral are you creating textures from files?

texture data is coming from a native plugin which is either generating it or loading it from a file.

It's on me to manage the system memory usage, but my question is "do I need to consider the GPU memory and avoid having too many Texture2Ds created, or does Unity somehow automatically evict textures from the GPU as needed (if so, how does it make that decision)".

It would be nice to know, but for now I'm just taking the naïve approach for now and I'll deal with issues when they come up.

torn basalt
tight tapir
torn basalt
#

I cast to a ground plane and instantiate an empty GO that has 4 empty GOs (points) inside. I set the first points position to that of the hit.point. Then I raise my hand diagonally up-right or up-left which moves the remaining 3 along the x,y axis relative to my raycast end points position from the first points position. I then click again and the positions of the points are locked.

I am keeping track of those positions in an Array[4]. I then add the typical mesh building stuff and then feed that positions array into the vertices of the MeshRender.

#

The position of the GO that was created at the point of the hit point is in the correct position but the actual mesh is not

#

Vectorwise

#

Visually is there. I need it to be accurate because I want to add a collider to the MEsh so that I can draw items ont he wall

tight tapir
#

The vertices you are defining are being transformed by the mesh renderer component when it draws the mesh.

#

so it sounds like your vertices are being generated in world-space, and then being offset by the mesh renderer object. Either you need to make the mesh renderer object be at origin (identity transform), or you need to calculate the mesh vertices in local-space (relative to the object position) (usually the better solution)

torn basalt
#

would something like this work?


for(int i = 0; i < PointPositions; i++)
{
  var convertedWorldToLocal = transform.TransformPoint(PointPositions[i]);

  _sharedMEsh.vertices[i] = convertedWorldToLocal ;

}
abstract folio
#

heya doc 🙂 I dunno! will take a look, thank you

tight tapir
#

depends on factors not shown, but also I think transform.TransformPoint does the opposite of what you want and transforms from local space to world.

If you take the time and come to understand what I'm telling you then the solution will become clear you'll be able to figure it out.

boreal yarrow
#

Hello! I currently have my code inside an asmdef file and I want to be able to reference code from another package, in this case from an asset I got from the asset store.
The code from the asset store doesn't bring asmdef files. Does this mean I'm stuck having to add my own asmdef file to the package and hope that once updating the asset it won't break?
Thank you!

dusky aurora
#

https://cdn.discordapp.com/attachments/497874004401586176/1027772260058140743/20221006_223717_1.mp4

So, the longer my game is on play mode, the laggier the gameplay seems to get.

This problem persists even after stopping and starting playmode again, and only goes away after restarting unity, only to come back again after enough time has been spent playing the game.

I don't know what to do next to debug the issue but here's the information I know.

Task manager showed the memory of Unity Editor increasing the longer the game was in play mode, and at some point got up to 2 gb. I cleared the log, and the game sped up drastically. I got rid of the debug spam now, but this leads me to believe that what is happening may be some kind of memory leak issue in my code?
The included video shows the very worst of it, back when I had debug.Log spamming the console. the issue is no longer so drastic but it's still very clear and ruins the feel of the game the longer it's open.

(Update: The memory is increasing slowly now, so I believe it is still a memory leakage issue, just not as fast as it was before.)

Does anyone have any advice on how I can go about debugging what is causing this issue?

undone coral
undone coral
#

unity can bind a Texture2D to a native graphics pointer

#

in the native API

#

you're sort of reinventing their streaming texturing, Granite, which exists and works well

#

and if something about it doesn't work well for your use case, the thing you are authoring probably will also not work well

undone coral
#

you should also probably check it in standalone

dusky aurora
kindred wyvern
#

I've got a 2D physics problem.
I'm trying to get a dynamic rigidbody with a frictionless circle collider over a hill. This hill is convex, meaning that the circle will disconnect from the hill if it travels in a straight line. I don't want this to happen, which means one of three things:

  1. I need to magically know ahead of time what force I need to keep that circle from disconnecting from the hill.
  2. I need to detect when the circle has disconnected from the hill, and adjust its position back to touching it.
  3. I need to somehow modify the way physics works in that particular scenario so that the circle always remains in contact with the hill.

1 is not possible because I would need to simulate the same rigidbody twice, effectively in two different timelines.
2 is not possible because between Transform.position, Rigidbody2D.position, and Rigidbody2D.MovePosition(), there is no way to move a rigidbody that will both keep interpolation and not disable physics for a frame. Not only that, but there's no post-internal-physics update to modify it from. FixedUpdate occurs before the internal update.
3 is not possible because Unity does not provide mechanisms for it.

Anyone know how I could tackle this?

sly grove
#

whether that's appropriate or not depends on exactly what kind of effect you're going for

kindred wyvern
#

If I looked ahead on the terrain collider for the position I want, I couldn't guarantee that the position would not intersect with terrain.

sly grove
# kindred wyvern If I looked ahead on the terrain collider for the position I want, I couldn't gu...

the terrain collider is basically never going to give you smooth anything because meshes are not smooth. They consist of flat surfaces. If you want apparently smooth motion you need to either have a very high detail mesh or something like a spline or distance field. In either of those cases you're likely wanting to take direct control of the object, rather than allowing the physics engine to do its thing.

kindred wyvern
#

Edge collider, actually. Like I said, this is 2D.
Either way, I need it to be hooked into normal physics, because I need it to respond to things like getting hit by, and moving over, other dynamic rigidbodies.

#

And because of that, I can't just up and set the position, for reasons mentioned for 2.

silk sable
#

I have nodes that can be connected to multiple other nodes.
These nodes can form loops.

I'd like to have a function that gives me a List of nodes representing the path from one given node to another (an optimized path would be great but not necessary rn).

I think breadth search first makes sense, but what I could find doesn't explain how to extract the full path.

    public List<Node> GetItinerary(Node dest, List<Node> alreadyVisited = null)
    {
        if (alreadyVisited == null)
            alreadyVisited = new();
        List<Node> iti = new();

        if (this.gameObject == dest.gameObject)
        {
            iti.Add(this);
            return iti;
        }
        if (alreadyVisited.Contains(this))
        {
            return iti;
        }
        alreadyVisited.Add(this);
        foreach (var node in nextNodes)
        {
           

            var tried = node.GetItinerary(dest, alreadyVisited);
            if (tried.Count != 0)
            {
                iti.Add(this);
                iti.AddRange(tried);
                return iti;
            }
        }
        return iti;
    }

This is the best i've got, it works 70% of the time (gives me actual paths in my complex graph), but since I basically made it up without putting much thought into it, i'm pretty it has many broken parts.
So yeah, am looking to pimp my algorithm or be pointed into a well documented implementation.

sly grove
#

Look up Djisktra's algorithm and A*

#

you're not incredibly far off from the structure of such algorithms here

kindred wyvern
sly grove
silk sable
#

Well the nodes definitely have positions in the world

sly grove
#

if they are weighted, then you use that

silk sable
#

so no worries bout that

sly grove
silk sable
#

yah

kindred wyvern
#

Or you could use Manhattan distance (dist = dx + dy), save on processing power.

#

Probably not worth it in this case, though. I doubt it's as data-dense as a grid.

silk sable
#

I can't find Djisktra's implementations for only one path rather than the whole tree

kindred wyvern
#

That's what A* is for.

sly grove
silk sable
#

Which one is easier to implement 🤔

sly grove
#

A* is basically the same as Djiktra's with an additional heuristic function

kindred wyvern
silk sable
#

Sebastian Lague is pretty cool yes

kindred wyvern
#

Oh shoot, Sebastian Lague made it?

#

Didn't even notice that. I found the video before I knew who that was.

silk sable
#

I'd like to save the path as a list of some kind, but I can't find any A* that do this, and I can't think of it myself

shadow seal
#

I recall in Seb's tutorial he gets a List<T> of nodes

silk sable
#

I'll look at the source

#

it's very complicated tho

#

I guess i'll implement it as a dictionnary

livid ledge
#

Does anyone know to change your curosr speed in unty with a slider

tight tapir
brisk pasture
#

iirc he later fixes it up to use a Heap and HashSet

compact ingot
celest kettle
#

is there a way to force a transform to recalculate? at this exact frame

#

i want to calculate a custom oblique matrix from the playercamera but with a custom position

sly grove
abstract folio
#

@sly grove👋🏻

celest kettle
#

yes its recalculated when its gets to it, Unity uses dirty flag intern so it just set a flag when I assign a new pos/rot/scale

#

I just need it in the same function but I did a hacky way to get it work 😎

#

prob not good for my performance

#

but hey

#

👋

abstract folio
celest kettle
#

so i cant force it through that

abstract folio
#

you change the position, it sets this dirty flag, then you call that function. if it doesn't not recompute the matrix, it would return the wrong value. I guess I misunderstand what you need.

silk sable
#

So I tried implementing a python A* algorithm into Unity.

It works perfectly 1/3 of the time on my complex procedurally generated node system (the rest fails to find the end).

Though I can't figure out why it would fail, so if anyone knows their pathfinding algorithm i'm sure they will be able to direct me towards a solution

#
private List<Node> FindPath(Node start, Node end)
    {
        PriorityQueue<Node> frontier = new();
        frontier.Enqueue(start, 0);
        var cameFrom = new Dictionary<Node, Node>();
        var costSoFar = new Dictionary<Node, float>();
        cameFrom[start] = null;
        costSoFar[start] = 0;

        while (frontier.Count > 0)
        {
            Node current = frontier.Dequeue();
            if (current == end)
                break;

            foreach (Node next in current.GetValidNexts())
            {
                float newCost = costSoFar[current] + current.DistanceTo(next);
                if (!costSoFar.ContainsKey(next) || newCost < costSoFar[next])
                {
                    costSoFar[next] = newCost;
                    float priority = newCost + CalculateWeight(next, start, end);
                    frontier.Enqueue(next, priority);
                    cameFrom[next] = current;
                }
            }
        }

        if (!cameFrom.ContainsKey(end))
        {
            Debug.Log("Failed to find path");
            return null;
        }

        Node tmp = cameFrom[end];
        List<Node> res = new();
        res.Insert(0, end);

        while (tmp)
        {
            res.Insert(0, tmp);
            tmp = cameFrom[tmp];
        }

        return res;
    }
#
def heuristic(a: GridLocation, b: GridLocation) -> float:
    (x1, y1) = a
    (x2, y2) = b
    return abs(x1 - x2) + abs(y1 - y2)

def a_star_search(graph: WeightedGraph, start: Location, goal: Location):
    frontier = PriorityQueue()
    frontier.put(start, 0)
    came_from: dict[Location, Optional[Location]] = {}
    cost_so_far: dict[Location, float] = {}
    came_from[start] = None
    cost_so_far[start] = 0
    
    while not frontier.empty():
        current: Location = frontier.get()
        
        if current == goal:
            break
        
        for next in graph.neighbors(current):
            new_cost = cost_so_far[current] + graph.cost(current, next)
            if next not in cost_so_far or new_cost < cost_so_far[next]:
                cost_so_far[next] = new_cost
                priority = new_cost + heuristic(next, goal)
                frontier.put(next, priority)
                came_from[next] = current
    
    return came_from, cost_so_far
jolly token
silk sable
# jolly token And what does `GetValidNexts`, `DistanceTo`, `CalculateWeight` looks like?
private float CalculateWeight(Node n, Node start, Node end)
    {
        return Vector2.Distance(n.transform.position, start.transform.position) + Vector2.Distance(n.transform.position, end.transform.position);
    }
    public List<Node> GetValidNexts()
    {
        return nextNodes.Where(node => node.gameObject.activeInHierarchy).ToList();
    }

    public float DistanceTo(Node node)
    {
        return Vector2.Distance(transform.position, node.transform.position);
    }

Basic stuff like weight calculation, getting the connected notes, and the distance to another node

jolly token
#

Also irrelevant from the issue, not sure why CalculateWeight counts distance from start..

silk sable
silk sable
valid totem
#

trying to rotate an object by adding 90 degrees and lerping between the previous and the new euler angles. when i get to a certain point when its going between -90 and 180, it will go all the way around the other way. ive tried setting the numbers to something else to no avail, anyone know euler angles?

#

Relevant code snippets (ignore that im not using a coroutine as i cant in this situation)

jolly token
#

It’s not a good idea to use result of transform.eulerAngles though, it’s better to manage your own variable

lilac peak
#

should be able to do some basic conversion stuff to do what you want

#

i dont really understand quaternions

valid totem
#

alright

#

if i remember quaternion has a method for rotating by a certain amount

#

works like a charm! thanks

brisk spruce
#

Anyone here managed to get Entity Framework to work with a net standard 2.1 application, targeting specifically android?

I have it working for windows, but I get the following error for Android, despite the fact I have the "linux arm x64" dll in my plugins folder (and I have it setup to deploy for Android x64)

#

inside of sqlitePCLraw.e_sqlite package, it has these releases and I think linux-arm64 was the one I wanted

#

it contained libe_sqlite3.so which I added to my plugins with this configuration

#

I will note doing the /exact/ same steps, but for the win-x64 release, it works perfectly fine on windows without errors and I am able to generate my sqlite DB

jolly token
brisk spruce
#

it builds fine yeah

#

its a runtime exception

jolly token
#

Are you building with Mono?

brisk spruce
brisk spruce
jolly token
brisk spruce
#

yeah I am building with Mono

#

this is the config in question right?

jolly token
brisk spruce
#

_>;

brisk spruce
jolly token
jolly token
#

Config in question xD

brisk spruce
#

I wonder if its an issue with the fact that we have 3 different arm releases and maybe I just mis-set which CPU for them?

#

in the package we have: "linux-armel" "linux-arm64" and "linux-arm"

#

I grabbed "linux-arm64" and set that one to ARM64 in unity

#

My phone is using the following cpu which I am pretty sure is ARM64...

Octa-core (1x2.9 GHz Cortex-X1 & 3x2.80 GHz Cortex-A78 & 4x2.2 GHz Cortex-A55)

jolly token
#

Hmm I think what you did make sense.. what about managed dll part?

brisk spruce
#

which part?

#

I wonder if the issue is simply that I am using the linux-arm64 runtime and there just isnt an android specific one, maybe the linux one just wont work for android

#

oh wait maybe its fine if I use the matching version for it, 2.0.4, lets see

#

nah it still wants mono.android, hmm

jolly token
#

Could be just compatibility like you said… never ran EF on Android. I know there is some plugin/projects using SQLite on Android, but not through EF

brisk spruce
#

yeah the main thing is I want to be using an ORM as well, I dunno if there are other ORMs that are an option

jolly token
#

It wouldn’t be fancy as EF but still ORM

brisk spruce
#

that looks pretty solid, Ill give it a spin, Im not tightly coupled to EFCore, I primarily just want a database for storage/retrieval of saved game information without having to load the entire savegame all at once, but instead have the ability to query just parts of it at a time that I need, so sqlite is ideal

#

but I want to avoid just having to write out "magic string" raw SQL queries, cause thats a super great way to get runtime exceptions out the whazoo, and I much prefer an ORM since then, you know, compile time errors instead

round wharf
#

How does il2cpp know what assemblies to load?

brisk spruce
#

then I gotta figure out how to set this bad boy up with Zenject so I can actually start doing some for realsies dependency injection

undone coral
#

hello soralin

undone coral
#

entity framework as cathei said is pretty solid but hard to use in Unity

undone coral
brisk spruce
undone coral
#

i remember investigating this before

#

i think someone made a Dapper build that works with unity

#

i don't think any of this will work on android 😦

brisk spruce
undone coral
#

it's very hard

brisk spruce
#

it has an android target included, testing if it works on android atm

undone coral
#

yeah raw sqlite based stuff should work well

brisk spruce
#

finally got it to compile, unity was being dumb and was trying to shove the windows dlls into the android build

brisk spruce
#

a very lightweight one, but it works, its like diet Entity Framework

undone coral
#

good good

brisk spruce
#

oh mah gawd

#

it worked, finally found one that works

undone coral
#

excellent

brisk spruce
#

gotta get it working with zenject now, but that looks simple enough, and then I should have a nice clean ORM for querying/writing save data

#

I /hate/ the idea of being tightly coupled to something like a json file where I would have to load the entire file into memory, when I may only need to just, in the moment, only access a piece of it

#

Inspecting with DB Browser and the table did indeed get written as well, so the schema is applying

#

My code:

var dbPath = Path.Join(saveFolder, "saves.db");
if (!File.Exists(dbPath))
{
    using var tempDb = new SQLiteConnection(dbPath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.FullMutex);
}

using var db = new SQLiteConnection(dbPath);
_ = db.CreateTable<Login>();
#

I was really scared Id have to leave my safe and comfy ORM territory to have data persistence for my android games D:

jolly token
#

All good? 😄

jolly token
round wharf
#

Could i create and load a il2cpp domain at runtime?

fallen viper
#

hello i posted this yesterday in code-general but it kinda got buried so im re-posting it here if that is okay since im assuming that meant it was a harder problem then i initially thought:

anyway Im trying something out where i need the texture coordinates of a sphere cast collision and i noticed unity acting strangely. Raycast texture coordinates and Spherecast texture coordiantes seem to not match up i keep getting 0,0 on the sphere cast even thought they hit the same point. Googling it shows a dead forum post from 2012 with the same issue:
https://forum.unity.com/threads/problem-with-spherecast-and-hit-texturecoord.206295/

Im wondering if this is intended behavior for this.

Heres the code im using to test:

RaycastHit rayHit;
if(Physics.Raycast(transform.position,Vector3.down,out rayHit,3f,paintMask)){
  Debug.Log("---RC----")
  Debug.Log(rayHit.point);
  Debug.Log(rayHit.textureCoord);
}

RaycastHit[] sphereHits = Physics.SphereCastAll(transform.position,1,Vector3.down,3f,paintMask);
foreach(RaycastHit hit in sphereHits){
  Debug.Log("---SC----")
  Debug.Log(hit.point);
  Debug.Log(hit.textureCoord);
}
jolly token
#

Which you can do cheaper with Collider.Raycast instead because you know it hit.

fallen viper
#

the documentation also dosnt seem to mention anything about it

jolly token
#

So I guess it's just some special code exists for raycasts to get uv

fallen viper
jolly token
#

Is there a way I can get extraScriptingDefines of current build from IShouldIncludeInBuildCallback?

jolly token
#

Or at least from IPreprocessBuildWithReport? Can't believe they don't have that

ancient iron
#

Hi, I am using I2 localization plugin. I have such a ScriptableObject in my project but I need to localize it.
Despite reading the documentation in detail, I haven't been able to figure it out yet.
https://gyazo.com/5a6bbff6a865fb185293827b1c29796a
Since I don't have "Add component" in my ScriptableObject entity I can't localize it, but there must be a way. I am using spreadsheet google in I2 localization entity. I request your help for this. How can I replace TheTipList string with the localized string?

My code;

using UnityEngine;
using System.Collections.Generic;

namespace LoadingTips
{
    public class bl_SceneLoaderManager : ScriptableObject
    {

        [Header("Scene Manager")]
        [Reorderable(elementNameProperty = "myString")]
        public TheSceneList List;

        [Header("Tips"), Reorderable("Tips")]
        public TheTipList TipList;

        public bl_SceneLoaderInfo GetSceneInfo(string scene)
        {
            foreach(bl_SceneLoaderInfo info in List)
            {
                if(info.SceneName == scene)
                {
                    return info;
                }
            }
            
            Debug.Log("Not found any scene with this name: " + scene);
            bl_SceneLoaderInfo sInfo = new bl_SceneLoaderInfo();
            sInfo.SceneName = scene;
            return sInfo;
        }

        public bool HasTips
        {
            get
            {
                return (TipList != null && TipList.Count > 0);
            }
        }
    }
}```
humble onyx
ancient iron
humble onyx
ancient iron
#

I've been waiting for an hour for someone to reply to my message, and thank you very much..

ancient iron
humble onyx
#

i dont know the plugin so that is probably not much help
i only use my own localisation system

wooden cedar
#

Me too, I also don't use serialized objects all that much - I do use a lot of SimpleJSON however. You could ask the dev you bought it from via their support channel - the chances of someone having the plugin and wanting to modify it for serialised objects and being in this discord and being active and wanting to help - is all very very slim. Especially someone wanting to give free one on one AnyDesk support.

But the process outlined above makes sense to me. You'll need to write something to do it the way you want I think

jolly token
ancient iron
#

I would be really happy if you could help. If necessary, I can share the relevant code in my project with you.

jolly token
ancient iron
#

oh yes

ancient iron
jolly token
#

You should start using term to indicate localizable text

undone coral
ancient iron
ancient iron
undone coral
ancient iron
#

yess one min.

undone coral
#

okay well i think you have to write an editor script to migrate your fields

#

you can also try doing it using your IDE and modifying the .asset file directly

ancient iron
#

Yeah I'll try that I guess it looks that way.

round wharf
#

How do i add a ascript to appdomain at runtime?

ancient iron
# humble onyx https://docs.unity3d.com/Packages/com.unity.localization@1.0/manual/index.html

Thank you for that, it's a really nice package. But the I2 is extremely used to it, so I don't want to give up.
I'm just looking for an answer to my problem, if possible I will be really happy with the.
I realize I'm taking up a lot of your precious time, but it's something important to me.
I'm happy to be a part of this family, if it weren't for Unity, I would have had to make ridiculously expensive payments to a meaningless game engine like the Hero Engine.

#

All I want is to localize my strings and be able to link to the spreadsheet.

sturdy comet
#

event EventHandler > event Action ? when yes why

lusty iron
#

hello friends - I'm having issues with my webGL build

I'm using Photon Fusion, and when I load into the primary game scene as a host, the build crashes with this error:
https://hatebin.com/tcgpsqdpet

it seems to be related to something with animations? this could make sense as there are no animated components until the scene is started. thanks for any help

undone coral
lusty iron
#

it does

undone coral
#

the requestAnimationFrame part is a red herring

#

you are at the start of a very long journey

#

requestAnimationFrame is just how unity runs the player loop in webgl

#

it's something from the DOM

#

i don't think there are any peer to peer multiplayer frameworks that will work in webgl

#

does your game work in il2cpp on PCs?

lusty iron
#

it's claimed to

#

i'm not familiar with IL2CPP

undone coral
#

okay

#

have you tried building and running your game as a standalone desktop application?

#

just a simple yes or no

lusty iron
#

yes

undone coral
#

and does it work

lusty iron
#

yes

undone coral
#

okay, is it set to build with the il2cpp runtime?

#

it's in player settings

#

go ahead and check that box, and try that

#

have you tried building a webgl development build with stack traces enabled?

lusty iron
#

i need to install ilcpp but I will try, thanks

#

i tried with deep profile?

karmic sand
#

Hey, I was wondering if i could get a bit of help. I'm having trouble building on my mac to WebGL. I tried uninstall uniy and re installing it. Same three errors ever time

austere jewel
karmic sand
austere jewel
#

Is there any tangible information further down that error past all the arguments?

karmic sand
#

it happens when it uses ilcpp building if that matters

#

I saw earlier messages my player setting configuration is set to defualt not ilcpp but ive read that default is ilcpp nowadays.

austere jewel
#

No idea. Perhaps post that whole error to a paste site (remove/alter anything you feel isn't relevant and could be private).
Usually those sort of errors I see on Windows at least is generally a setup issue where they haven't installed the C++ build tools and windows SDK.
I think the equivalent on Mac is having the right version of Xcode is installed, but I don't know the details

undone coral
# karmic sand

have you ever started unity or unity hub as an administrator?

undone coral
karmic sand
undone coral
#

don't

#

it will really screw things up

karmic sand
#

ohh. @undone coral okay. I didn’t.

undone coral
#

it's hard to know why it won't build on windows if it builds on macOS

#

that is usually how people put themselves into some jeopardy

#

otherwise if the path is very long or has weird characters

#

that can muck things up

karmic sand
#

Yea… so it may have to do with the file sharing?

#

Hopefully it doesn’t muck up the windows.

#

I set the appropriate setting for the metadata.

undone coral
#

when you say file sharing

#

what do you mean

karmic sand
#

Is Thier something I can do to clean the muck?

undone coral
#

git isn't file sharing

karmic sand
#

Version controll.

undone coral
#

is that what you mean by file sharing?

#

okay

#

did you use a .gitignore you found online

#

or did you author your own?

karmic sand
#

Sorry I thought they were kinda interchanable.

undone coral
#

do you use any plugins / libraries / assets with their own .dll files?

karmic sand
#

Yes to the .dell files. I have an infinite runner engine from more mountains.

undone coral
#

hmm

#

probably fine

#

they build webgl stuff all the time

#

is this an old machine?

#

with a lot of development usage

#

so it might have old versions of VC / old configuration?

karmic sand
#

Also I think thier was a .gitignore place in for me when I set up the version control.

#

It’s a MacBook Pro 11.

undone coral
undone coral
#

have you tried cloning your repo fresh on the mac

#

and trying to build

#

it probably will build fine

#

and hence has nothing to do with source contorl. it's probably what vertx said

karmic sand
#

Working on it. Thanks. I feel like this will fix the issue.

round prism
#

What is a better approach to reduce the apk size. Addressables or AssetBundle.

#

I just want to reduce the apk size and download all the asset on splash screen.

blazing verge
#

Can someone recommend any mvvm framework for unity?

blazing verge
#

They already implemented bindings?

compact ingot
#

idk, but if not, nobody else did either partially (for editor UI)

#

i usually end up making my own little data binding jig when its needed for runtime things

lapis solstice
#

does anybody know if it is possible to have two fullscreen displays running each with their own vsync? i think Unity vsync is dictated by the primary display set in windows

#

i use unity for prototype development for a new AR device that has two display adapters and tearing in HMD is really bad

tawny bear
#

Have you Googled it?

lapis solstice
#

sure 🙂

tawny bear
lapis solstice
#

the documentation is not that detailed regarding vsync implementation in unity

tawny bear
#

Hm fair

#

Outside of the docs?

#

Maybe some stack overflow posts?

lapis solstice
#

i tried, also for directx in general - but it seems that this is a very uncommon thing 😦

tawny bear
#

Bummer

lapis solstice
#

yep - so far the only hacky workaround i can think of is to render to textures from unity entirely and then create separate d3d rendering code that displays these textures fullscreen with vsync... not a very elegant solution

compact ingot
#

traditionally interfaces cannot have static members, you can however use any old base or abstract class to achieve the same thing as with using interfaces, minus the constraints but plus some project specific conventions you define. Having static members in an interface makes little sense however and is indicative of a design/architectural flaw (at least that used to be the case).

#

starting with C# 8 however you can use static members and default implementations in interfaces, they must be implemented in the interface and cannot be overridden (virtual static members are a feature of C# 10+ iirc)

undone coral
#

you are saying tearing

#

are you saying that the two displays are not synchronized?

#

when you say the AR device is new, do you mean it is also a prototype?

#

displays running each with their own vsync?
this is concerning to me because tearing is a specific thing, and it wouldn't be resolved by this

lapis solstice
#

what do you mean by synchronized? they are attached by two displayport cables, both featuring 120 hz - but their vblanks would most likely occur at different times

undone coral
#

do you mean enabling vsync at all?

lapis solstice
#

yes, a prototype ar device

undone coral
#

okay

lapis solstice
#

no, i know how to enable vsync in unity

undone coral
#

so the displays are not synchronized

lapis solstice
#

exactly

undone coral
#

okay...

#

so when you say tearing, is there tearing or no?

lapis solstice
#

yes, there is tearing

undone coral
#

okay

#

but tearing is when there is no vsync

lapis solstice
#

yes

undone coral
#

so you have neither vsync enabled, nor are the displays synchronized

#

i guess, are you responsible for designing this AR device? is this for an academic environment?

lapis solstice
#

i have vsync enabled in unity, but this only applies to the primary display set up in windows, so when one of the headsets display is the primary display, then this display has no tearing

#

yes, academic

undone coral
#

okay

#

like in a graduate lab?

lapis solstice
#

phd

undone coral
#

okay cool

#

not fluid interfaces right?

lapis solstice
#

no

undone coral
#

okay

#

if you are using nvidia graphics, you can configure it to force v-sync on for both displays

#

in the nvidia settings panel

lapis solstice
#

i'm just wondering if it is in principle possible for d3d to enable vsync on two different display adapters at the same time

undone coral
#

if you want to synchronize the displays, and they support gsync, you would need a quadro card, and then it's another checkbox

lapis solstice
#

from my understanding, this should be possible if each device has its own swap chain

undone coral
#

directx simply asks the graphics driver to do this, you can also ask the graphics driver using the appropriate panel in windows

lapis solstice
#

yes, i'm using nvidia - never knew this options exists

undone coral
#

vsync can be enabled on both displays

lapis solstice
#

do you know how this is called?

undone coral
#

but that's separate from synchronizing it

#

it's called... vsync

lapis solstice
#

🙂

undone coral
#

you will find this on google

#

which graphics card do you have*?

lapis solstice
#

rtx 3070 in my development machine

undone coral
#

okay

#

so you will never be able to do this, i am sorry

#

you have to buy a quadro card. i suggest an A5000

lapis solstice
#

nice

#

very cool, thx

undone coral
#

if you want the two displays to present at the same time, it's a checkbox, provided they support gsync

lapis solstice
#

they don't support gsync

undone coral
#

i don't remember if this is a quadro specific feature, or only quadro specific if it's multiple graphics cards

#

okay

#

then this will never work

#

under any circumstances, i am sorry

#

a gsync / freesync display allows the graphics card to instruct the monitor when it should refresh

lapis solstice
#

why exactly? couldn't i just set up my own d3d renderer with a swap chain for each display adapter?

undone coral
#

this also enables it to run the refresh exactly after a frame is prepared, at basically any framerate

undone coral
lapis solstice
#

why? 🙂

undone coral
#

do you aspire to use HDRP?

lapis solstice
#

no

undone coral
#

okay

#

so you do not want or need immersive graphics?

lapis solstice
#

nope, basic graphics is fine

undone coral
#

are you confident your displays cannot have their refresh rate driven programmatically?

#

are these experimental displays?

lapis solstice
#

these are 2.9 inch and 3.1 inch mini displays

undone coral
#

you are getting hung up on this directx stuff... you can check a box and vsync will be turned on

#

that problem is solved

#

that will solve tearing

lapis solstice
#

but only for one display 🙂

undone coral
#

no, for both displays

#

i'm talking about a checkbox in the nvidia settings panel

#

this is what i mean

#

i am repeating myself

#

and you're repeating yourself, by talking about directx

#

so what is your actual objective?

#

do you want to be able to create a stereo experience with two displays?

lapis solstice
#

having independent vsync for each attached display

undone coral
#

see, you say independent

lapis solstice
#

its not stereo vision

undone coral
#

okay i only have a few more minutes and i know a lot more about this than you

#

so what would be the highest yield thing you would want to learn

#

you do not need to touch a swapchain or directx anything

lapis solstice
#

this is not a classic ar or vr device with two displays, there will be more than 2 displays eventually

undone coral
#

none of that has anything to do with anything

#

you said tearing, you can turn it on in the panel

#

done

#

you never have to think about it again

#

i can't tell if you want the frame presentation to be synchronized

#

across displays

#

if it's not stereo, if it's not one display to one eye, it's not necessary, but i haven't been filled in on what the idea is here

#

what do you mean by independent?

#

are you trying to say you don't know how to do it in Unity's API? it seems it can only control vsync for one display adapter?

lapis solstice
#

the headset features displays for peripheral vision, so there is no stereo vision involved. a number of display elements will be placed in the user's peripheral field of view

undone coral
#

okay

lapis solstice
#

i know how to set up vsync in the unity api...

#

i already experimented with this and vsync only applies to the main display adapter, tearing is present on any other display

undone coral
#

well did i give you an adequate solution?

lapis solstice
#

i even tried the nvidia force vsync

#

no luck

undone coral
#

alright i gotta go

lapis solstice
#

sure, thank you for your help!

calm ocean
#
// In an event listener
        void Update()
        {
            if (Input.GetKeyDown("q"))
            {
                _channel?.SubscribeListener(Respond);
            } else if (Input.GetKeyDown("e"))
            {
                _channel?.UnsubscribeListener(Respond);
            }
        }

// In an event channel
        private UnityAction _onEventRaised;

        public void RaiseEvent()
        {
            _onEventRaised?.Invoke();
        }

        public void SubscribeListener(Action listener)
        {
            _onEventRaised += listener;
        }

        public void UnsubscribeListener(Action listener)
        {
            _onEventRaised -= listener();
        }

Right now _onEventRaised += listener and _onEventRaised -= listener isn't working because the signatures don't match. Is there a way to pass a reference to a method into a different method, and subscribe that method to unity action?

#

What I have done is put the listener in an anonymous function, but that makes unsubscribing impossible.

#

I could also make the UnityAction public, but then I would be exposing an implementation. It's quite interesting that I can subscribe a method directly to a unity action, but I can't put that method into an action and then subscribe to a unity action.

#

The input get key down is for testing purposes.

undone coral
#

@calm ocean this isn't really advanced code

#

what is your objective?

#

why are you reinventing UniRx?

calm ocean
calm ocean
calm ocean
# undone coral why are you reinventing UniRx?

I checked a little bit of it, but it seemed an overkill for what I am trying to do. I am trying to create an event-based scriptable object architecture, so the event channel above is a scriptable object. I was following Unity's open project 1, Chop Chop, and noticed that they used a public Unity Action in order to subscribe and unsubscribe listeners. I am trying to see if there is a way do this but without the public Unity Action. But if it is not possible, I will just drop unity actions completely.

jolly token
#

Also event keyword exists just for this purpose

hard loom
#

Does anyone know how to set the value (programatically) for Input.GetAxis("Horizontal") ? I want to set this value inside a script, something like:
Input.SetAxis("Horizontal").to(1)

My goal here is to be able to create a Test Case for my player controller. However, since my player controller gets its turnSpeed value from this input, I have to somehow set this beforehand in the script to be able to test it. By the way, I'm trying to do it using TDD.

An alternative would be to stub the return value for Input.GetAxis("Horizontal"), but I don't know how to do that in C#

jolly token
#

Not the Input class

hard loom
frozen imp
#

It's hardly an advanced coding issue. Just replace the variable you actually use with your own and feed it different value. And for new input system #🖱️┃input-system , resources are pinned in the channel

hard loom
undone coral
#

I am trying to create an event-based scriptable object architecture,
this is a bad idea

undone coral
#

it is the correct implementation of publish and subscribe for unity

calm ocean
wooden cedar
#

So adding events or custom logic to it is odd and likely to not do what someone would expect due to how it persists and functions

compact ingot
calm ocean
compact ingot
#

Generally in gamedev you want to tightly control the freedom you give to designers and really everyone, so you can focus on the important stuff instead of tracking careless mistakes, SOs invite carelessness

calm ocean
#

Oh so scriptable objects open more opportunities for misuse, hmm, okay I understand, though perhaps good documentation and interfaces can mitigate that?

compact ingot
#

generally stuff that is configurable makes things more complicated

#

so if you have a choice, put it into code, not into config data

#

This is somewhat an antithesis to the common recommendation to make everything data

#

it is however important to be very clear (in each project) what data is good data and what should really not be put into data but remain in code to establish conventions

#

SOs make it very easy to err on the side of configuration and make a lot of the games flow implicit… ie you can’t understand the project anymore without the editor to look at it

#

this eventually happens to all projects but it’s worth it to make it as hard as possible for implicit stuff to become relevant

lone fog
#

Hi everyone ! I have researched this for several days and can't seem to be able to find the solution as why it doesn't work. I have searched for this a lot so any help would be appreciated ! Thank you in advance.

To give context :

I developed an API using Symfony (v6.1), API-Platform (v3.0) and Doctrine (v2.7) with a MySQL database (v5.7) I want to use the API in a game made with Unity 3D (v2021.3.8f1). I can retrieve the data from the API with GET requests with no problem at all, everything works just fine. However, when I try to send POST/PUT/PATCH requests, the data is not updated. In Unity, I get 200 responses, that are treated as a GET request. I am trying to update the amount of given object in the user's inventory.

I tried a lot of different things :

At first, I thought that it came from the API because I get no errors in Unity, so I tried updating the data in API platform's UI, which works just fine.
Then, I thought that it might come from Unity's web request functions (UnityWebRequest), so I tried using the native C# HttpWebRequest which doesn't change my problem.
Lastly, because I thought that it may come from an authorization problem, I exposed my api online (it was run on a local server since then) and I tried to send a PUT request using https://reqbin.com/, with the exact same parameters entered in Unity and it works ! But it still does not work from Unity 3D, even with the online url. I have no idea where it might come from because the logs that I have on the server don't show much except that the UPDATE query to the database was not sent by Doctrine, but I don't see errors, or even changes from a request that did work : I have no idea why.

I linked the logs from the requests (sent via Unity - doesnt work & sent via Reqbin - works)

Here is my code to send the request via Unity: https://imgur.com/a/FCu0A9k (I didn't have enough characters to write it directly in the message)

Here are the logs I get in Unity : https://imgur.com/a/CjcrHui

  • 1st log is the content sent
  • 2nd log is the url that was called
  • 3d log is the response content
  • 4th log is the boolean that says if the request was successful
  • Last log (empty) is the error message

Here is the picture from the successful request sent via reqbin.com : https://imgur.com/a/oRJCmT7

I don't know what else would be relevant to send. I really don't think that it comes from my API, since the request works, only not sent via Unity. Thank you !!

compact ingot
#

best code is no code

compact ingot
lone fog
# compact ingot Post code not screenshots and screenshots that are legible

yes, sorry !

 public class JsonResultModel
    {
        public string ErrorMessage { get; set; }
        public bool IsSuccess { get; set; }
        public string Results { get; set; }
    }
    // HTTP_PUT Function
    public static JsonResultModel HTTP_PUT(string Url, string Data)
    {
        string url = API_BASE_URL + Url;

        Debug.Log(url);

        JsonResultModel model = new();
        string Out = String.Empty;
        string Error = String.Empty;
        WebRequest req = WebRequest.Create(url);

        try
        {
            req.Method = "PUT";
            req.Timeout = 100000;
            req.ContentType = "application/json";
            byte[] sentData = Encoding.UTF8.GetBytes(Data);
            req.ContentLength = sentData.Length;

            using (Stream sendStream = req.GetRequestStream())
            {
                sendStream.Write(sentData, 0, sentData.Length);
                sendStream.Close();

            }

            WebResponse res = req.GetResponse();
            Stream ReceiveStream = res.GetResponseStream();
            using (StreamReader sr = new(ReceiveStream, Encoding.UTF8))
            {

                Char[] read = new Char[256];
                int count = sr.Read(read, 0, 256);

                while (count > 0)
                {
                    String str = new(read, 0, count);
                    Out += str;
                    count = sr.Read(read, 0, 256);
                }
            }
        }
        catch (ArgumentException ex)
        {
            Error = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
        }
        catch (WebException ex)
        {
            Error = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
        }
        catch (Exception ex)
        {
            Error = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);
        }

        model.Results = Out;
        model.ErrorMessage = Error;

        if (!string.IsNullOrWhiteSpace(Out))
        {
            model.IsSuccess = true;
        }

        Debug.Log(Out);
        Debug.Log(model.IsSuccess);
        Debug.Log(model.ErrorMessage);

        return model;
    }
compact ingot
compact ingot
lone fog
# compact ingot Through a paste site

Sorry I'm not used to asking for help on discord :p I don't know any paste site :/ And it seems like i'm sending the request because I get the json from the inventory resource but it's not updated. I'm new to API calls in C# so I am not sure if I was supposed to add a line of code somewhere. I call this HTTP_PUT function (which I sent in my previous message) in another script, which I thought was not relevant

compact ingot
jolly token
lone fog
lone fog
lone fog
compact ingot
compact ingot
# lone fog I will try with HttpWebRequest when I get home !

you can more or less reduce the required code to this:

private async Task<HttpResponseMessage> Put(string uri, string data)
{
    HttpClient client = new();
    HttpContent content = new StringContent(data);
    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
    HttpResponseMessage response = await client.PutAsync(uri, content);
    response.EnsureSuccessStatusCode();
    return response;
}
misty glade
#

Anyone know any workarounds to get global using or something similar to that in a unity project? My usings are getting to be a bit much to manage

misty glade
#

..?

compact ingot
#

how can using statements be a problem, ever?

misty glade
#

I use a few enums that I want to using static so I don't have to fully qualify them

#

I think VS still automatically adds usings when I need them but.. the static thing.. I'd like to have in all my UI cs files

#
using static RuleOfCoolStudios.ISG.Utils.Logging;
using static RuleOfCoolStudios.ISG.ScriptableObjects.AudioDatabase.AudioClipType;

ideally I don't need to paste these lines into the files that were created before I added them to my 81-C# Script-NewBehaviourScript.cs.txt template

lone fog
misty glade
#

Because this is a little easier to type (and looks cleaner IMHO) than this

misty glade
#

(but I only started doing that using static recently so I have .. dozens/hundreds of files that are using the old way)

compact ingot
#

it obfuscates what the thing is

misty glade
#

you prefer the later with the fully qualified thing?

compact ingot
#

yes

misty glade
#

It might be better, I suppose.. I just am getting tired of it (probably because i'm implementing these clips now so I'm typing this line or variations on it like... dozens of times lol)

compact ingot
#

but i'm generally distrustful of methods my coworkers write to actually do what they say they do and variables to be what they say they are

#

i also don't trust my own methods from two weeks ago 😄

misty glade
#

I'm generally distrustful of methods my coworkers I write to actually do what they say they do and variables to be what they say they are

#

ha, you beat me to the punchline

compact ingot
#

i'm not a fan of small methods

#

makes it too hard to check if everything is correct... at least in games where there are no tests

misty glade
#

What do you mean by "small methods" here?

stray plinth
#

Hey 👋
Not sure if this is the correct channel, but here goes...
I need to instantiate a spineSkeleton and immediately read it's mesh's bounds, however they are not correct. Calling LateUpdate on the skeletonAnimation and RecalculateBounds on the mesh does nothing at this point...
In the next frame, everything is fine, but I need it in the frame where I instantiated...
TL;DR: Can I force bounds recalculation so that it is actually correct in the same frame as the mesh was created?

misty glade
#

LateUpdate() happens before rendering - you probably need to put logic like that later, like OnPostRender or whenever in the render cycle it's appropriate

stray plinth
#

Not sure I understand what you mean? I know when LateUpdate happens. The problem is that this is an editor script and I need to execute some logic before a build by instantiating a renderer and calculating it's bounds.

misty glade
#

Hm, not sure then, sorry. 🤷‍♂️

#

I don't know much about mesh boundary calculation, but I know for layout components there's some methods in the API that can force a recalc.. I would imagine the same should be true of RecalculateBounds - like a ForceRecalculateBounds or something. My guess would be that because the mesh isn't sized until rendering - there is no size available to you until the "Scene Rendering" events happen.. but how that works with the editor lifecycle... 🤷‍♂️

stray plinth
#

Yes for UI elements that exists, but haven't been able to find anything similar for meshes/spine Renderers

jolly token
stray plinth
#

Yes.

jolly token
# stray plinth Yes.

You can manually call skeletonAnimation.Update(0f) and that usually do the job

stray plinth
#

Yes, unfortunately not here.

#

The bounds are huge in the first frame, not sure why in particular.

jolly token
stray plinth
undone coral
undone coral
calm ocean
undone coral
#

got it

#

well what would be most helpful

calm ocean
# undone coral you were working on a rewrite of a game right?

Also thanks for sharing UniRx, it is indeed very powerful. However, I feel that it is not mutually exclusive to scriptable objects. Suppose I got a player model, who has a jump action. Suppose when the player jumps, I want a sound to play, cool explosion particle effects and the camera shakes, instead of putting it all in the player, I could put all those events else where, like in another monobehaviour. However, there needs to be a form of communication between the player model and all the events which are now intentionally separate. Using UniRx, I imagine I could get the player model to provide an observable, and a possible thing for the observable to emit is a jump (or perhaps the observable contains info about the jump, but that's besides the point). There needs to be a way for all the events to know about this observable. Why not store this observable in a scriptable object?

undone coral
calm ocean
#

Hold up...

undone coral
#

from yours truly @jolly token

calm ocean
#

I just watched a unity talk about anti monobehaviours, and now I am seeing one on anti SO...

undone coral
#

instead of putting it all in the player,
the jump is the coupling

#

you can of course decouple all those individual pieces

#

but it has to be coupled SOMEWHERE

#

just couple it in a method

#

do not program inside scriptable objects

#

does that make sense @calm ocean

#

the unity people don't know what they are talking about, that talk is cursed

#

that's just how it goes sometimes

#

is there something ineffective about what i authored there? i mean it could be a coroutine, i haven't used a coroutine in a while because i find unitask to be "better coroutines"

#

this is also, essentially, why DOTS is kind of stupid for the vast majority of games, but i hardly use DOTS so i can't really say with certainty

#

DOTS is "an idiosyncratic set of patterns that disguise a strongly coupled networked first person shooter engine as a collection of decoupled names that are near zero value without all of them together"

#

scriptable objects are also "an idiosyncratic set of patterns that disguise a strongly coupled ordinary method miswritten as a collection of icons in your Assets window"

#

DOTS: if you aren't writing a networked first person shooter, it is negative ROI**

jolly token
undone coral
#

i shouldn't say it's useless. it appears useful, it does what it's supposed to do. the cost massively outweighs the benefits for everything but networked first person shooters

#

scriptable objects are very similar

#

@calm ocean they do something, they're not useless, they just have an implementation cost that far outweighs the benefits

#

you can find high ROI uses for them, they're in @jolly token 's link

compact ingot
wooden cedar
#

I'm sure a lot more can be added to that list :D. They have a place and time for sure, but I think they are all universally used unnecessarily

#

But I digress 😄 and am overly opinionated on that subject I think

calm ocean
calm ocean
#

The alternatives in the Cathei's article is very interesting, I will have to check those out. But until I learn the alternatives, I will need the scriptable objects so that the features I am working on can be completed by the end of my sprint. I am keeping in mind that scriptable objects can fail on me at any time and so I am not making any design decisions that are irreversible/a massive pain to reverse. I would also leave documentation and design the interfaces such that the scriptable object implementation can be swapped out for something else. But anyway, thanks for sharing.

quartz stratus
#

I have a question simply stemming from implementation curiosity:

/// <summary>
///   <para>Returns the length of this vector (Read Only).</para>
/// </summary>
public float magnitude
{
    [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (float) Math.Sqrt((double) this.x * (double) this.x + (double) this.y * (double) this.y);
}

I'm looking at Unity's code in their Vector2 class for the magnitude property, pasted above. I'm just wondering why they're casting the floats x and y to doubles, only to cast the operation's result back to a float. Anyone care to enlighten me? Thanks in advance 🙂

shadow seal
#

I'm pretty sure all Math methods use them, and Unity wraps them into Mathf

glass anvil
#

Mathfloat

#

🤓

quartz stratus
#

Oh snap mind blown

#

Thank you

jolly token
quaint dragon
#

So I've encountered an extremely weird bug. I'm trying to set a time limit for cubes that I'm gonna put in various locations throughout the map, and for some reason when I write timeLeft -= Time.deltaTime; Instead of decrementing every second, it goes straight to zero. Even when I set the time scale to 1f, it still goes straight to zero.

My game manager has another variable called elapsedTime, and that one works perfectly. I'm using the exact same strategy for timeLeft as I am for elapsedTime, except elapsedTime counts upwards, and timeLeft counts downwards. Frankly I have no idea how this is even possible. Why would the exact same code work for one thing, but not another?

jolly token
lyric dragon
#

I have a theoretical question

I created a gameobject, let's say some human model, it doesn't have renderer within its components, how does it get rendered then?

What is the difference between the renderer(component) and the actual renderer (the one that draws gameobjects)?

Can I access that renderer?

quaint dragon
quaint dragon
#

The code in screenshot 4 gets called whenever a cube is shot.

austere jewel
#

Use the debugger and add breakpoints to see whether anything's getting called, and what timeLeft is before and after the logic runs.
Just note that the next time a frame is run deltaTime will likely be maxed because the debugger was paused for the amount of time you were inspecting the first frame

jolly token
austere jewel
quaint dragon
jolly token
#

But yeah debugger is good solution for general issues like this 😄

#

And auto formatting too

quartz stratus
#

If/when you're ever feeling down about your code, just remember that the OVRManager Update method written by Meta engineers is 303 lines long

heavy badger
quartz stratus
heavy badger
#

I'm not even advanced Im a little lousy beginner so let's go

#

know some c#, making mods for games the one I'm working on happens to be in unity so I thought it couldn't be hard since I know basics of c#

#

yeah no.... that was a lie

quartz stratus
#

Just a matter of learning the unity api stuff as needed, you got it

heavy badger
#

Do you have any good pointers for learning about object references and static feild errors

#

I can't find any and unity doc makes little sense to me

trail cloak
#

Hello there, is there a way to create a EditorGUILayout.DelayedTextField using GUILayout.TextField?

hardy nymph
#

I have classes like this

#

class uiElement

#

then derived ones

#

class ButtonElement
class TextElement
class InputFieldElement
...

#

etc

#

I have a function like this

#
void onElementClicked (uiElement element) {
    // some code here
}
#

The input argument is of type uiElement so I can pass all of the derived ones in the function

#

but, for-example buttonElement has an attribute 'normalColor', how do I access that ?

#

something like

#
void onElementClicked (uiElement element) {
    element.normalColor = "#FF00FFFF"; // of course this will give an error
}
hardy nymph
#

Yea to some extent I can do element as ButtonElement but I don't know that it's a button element

#

I just need to cast it to whatever derived class it was before.

#

It can be Button, or Text, or InputField

#

Was looking for something like

(some cast code which converts to the original object).normalColor = "#FFFFFFFF";
jolly token
#

Do you know is operator

hardy nymph
#

not really, let me search

#

how can i use it here

#

The is operator is used to check if the run-time type of an object is compatible with the given type or not. It returns true if the given object is of the same type otherwise, return false. It also returns false for null objects.
Syntax:
expression is type

#

okay thats useful

inland raft
#

Hi, I'm trying to make a click and drag script. It works pretty well except for the fact that the object I'm trying to rotate rotates slower on each click. Does anybody know where I'm doing it wrong? _NewMousePos keeps becoming bigger and bigger, I assume that is what is forming the problem, but I don't know how

devout hare
#

You have to set both variables to zero vector on mouse up

#

also you shouldn't create the quaternion like that, should use Euler angles

inland raft
obsidian glade
celest kettle
#

advanced code

#

kzooem

quartz stratus
lone fog
regal olive
tawny bear
#

Could be one of the reasons it's jittery, regardless it should be fixed

#
    void FixedUpdate()
    {
        float desiredHeight = crouching ? crouchHeight : standHeight;

        if (controller.height != desiredHeight)
        {
            StartCoroutine(Crouch(desiredHeight));

        }
    }

You're starting a coroutine every frame c.height isn't your desired

compact ingot
#

coroutines also have no business in a character controller

regal olive
#

Out of interest, would anyone know a way to create a smooth transition of all assets being saturated and then becoming desaturated

#

and vica verca

regal olive
#

with post processing probably

compact ingot
#

with a color post effect... depends on your RP which one

regal olive
#

yes, but i am unsure on how to go about making it smooth so it isnt like going from fully saturated to fully desaturated in a blink of an eye

#

im asking for a friend of mine

compact ingot
#

animate the intensity value with a lerp over time

regal olive
#

hm ok ill have a look thank u

mossy gust
# regal olive yes, but i am unsure on how to go about making it smooth so it isnt like going f...

Hello I am that friend, Hijacking from this:

  • using URP
  • two layers in the game, one post processing one excluded from post proc
  • if objects are within range of player it gets moved to no post processing later
  • if objects are outside range they get moved to post processing layer
  • I have no experience with shader graph / HLSL
  • I can't necessarily lerp the saturation levels due to it being layer based

Any suggestions?

tawny bear
mossy gust
regal olive
grizzled solar
#

Anyone that can see the issue?

#

they rotate down-right on start, whilst it should be working correctly

tawny bear
#

Why does your index start at -1

#

booleans are by default false

#

floats are by default 0

tawny bear
grizzled solar
#

wait

#

how do a change from where it rotates

tawny bear
#

You can add an empty gameobject as a pivot

jolly token
#

Nothing wrong with being explicit to show that default value is intentional

tawny bear
#

I guess that's fair

grizzled solar
#

how do i change the pivot?

#

i guess thats the problem

tawny bear
#

Though every dev would know what the implicit value would be so eh

tawny bear
tawny bear
grizzled solar
jolly token
tawny bear
#

I guess so

jolly token
#

idk this one’s intention tho

plucky sparrow
#

Hey sorry to interrupt but does anyone here know how to make a random building spawn area generator? I am working on atm and I am having some problems with stopping the spawning of objects in walls and pathways. I was thinking of setup of a raycast from a box collider over the map to the buildings from spawning objects if they were not tagged with terrain (Like pathways and other preset buildings)

tawny bear
#

If not, it shouldn't matter too much if it spawns in objects

#

It'll just pop out if it has a collider and rigidbody

plucky sparrow
#

oh sorry for the confusion I am trying to setup a script that will look at the map and find the open areas allowed by a tag to spawn in buildings

tawny bear
#

Make an array of possible spawn points

plucky sparrow
# tawny bear Make an array of possible spawn points

I could do that but I was trying to make it able to look at any map and be able to spawn buildings in the areas allowed. (yes I could do that for every map but then it would become repeatable) for instance each time a player goes through an area it will be very different allowing me to have one map forever changing. An example of this is when I am using 3 scripts to spawn in areas of the map one for each goal. One that keeps player data and allows objects to be stored there forever and others that resets their loot tables and missions. Those buildings will never be in the same spot. One a player leaves that area it moves it over into the new area (unless it is a boss) so it will have completely new building spawn points.

midnight venture
#

Easy, but inefficient (and theoretically infinite) - Mark the forbidden spots with colliders and test against them with OnTriggerEnter

analog oar
#

Hello, where I can find some good examples about game architecture in Unity. Like MVC, ECS, MVVM sample projects

regal lava
plain abyss
#

I am generating a procedural mesh based off of some locations I read from an external file. What would be the best way to "inflate" the mesh so that it is just a tad larger than the polygon that list of points defines, without changing the scale of the entire object?

Context: I have a polygon that defines an "inner" space, and I need to generate a mesh to put walls around it, but I want the walls to have some thickness, meaning I'd need to move them out by half the wall's thickness for them to not shrink the "inner" polygon space.

compact ingot
plain abyss
#

But I don't do this too often I can probably take the time

#

Actually I should just be able to do SetVertices, I don't think I'd need to change any UVs, Triangles, etc., since those are all referencing vertices by index

#

I just need to make sure they're in the same order

#

Perfect, except my normals are flipped, but that's a different problem

#

Thanks!

compact ingot
plain abyss
compact ingot
plain abyss
compact ingot
plain abyss
#

Hm, it separates the corners. I might need to add new faces between the corners?

compact ingot
tired creek
#

The following:

public static GameObject CreateGameObjectFromMeshData(string name, Pose pose, List<Vector3> vertices, List<int> triangles, Material mat)
        {
            GameObject obj = new GameObject(name);

            obj.transform.position = pose.position;
            obj.transform.rotation = pose.rotation;
            
            MeshFilter mFilter = obj.AddComponent<MeshFilter>();
            mFilter.mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
            MeshRenderer mRenderer = obj.AddComponent<MeshRenderer>();
            
            mFilter.mesh.SetVertices(vertices);
            mFilter.mesh.MarkDynamic();

            List<Material> materials = mRenderer.materials.ToList();
            materials.Add(mat);
            materials.Add(mat);
            mRenderer.materials = materials.ToArray();

            mFilter.mesh.SetTriangles(triangles, 0);

            mFilter.mesh.RecalculateNormals();

            List<int> backwardTriangles = new(triangles);
            for(int i = 0; i < backwardTriangles.Count(); i+=3){
                (backwardTriangles[i], backwardTriangles[i+1]) = (backwardTriangles[i+1], backwardTriangles[i]);
            }
            mFilter.mesh.SetTriangles(backwardTriangles, 1, false);

            return obj;
        }

Results in Failed getting triangles. Submesh index is out of bounds at mFilter.mesh.SetTriangles(backwardTriangles, 1, false);.
What am I doing wrong?

#

nvm, apparently you have to SET materials.subMeshCount

#

bruh

sly grove
#

or the second

#

your code is setting the second right now

#

0 = first
1 = second

tired creek
#

im setting both first and second submeshes

#

either way it works right now

ember peak
#

im not sure if this is advanced or not but Im making a fps game and I can't figure out how to make a good camera shake when the player shoots the gun. Help would be appreciated! (I can easily detect the gun shot, but I don't know how to make a nice camera shake)

compact ingot
ember peak
#

is it complex

plain abyss
#

I have a procedural mesh generated by a polygon (list of points) and a height. I am inflating the polygon slightly with a shader by moving each vertex out slightly along their normal, but this separates the corners (first picture). I'd like to add another face between the corners, but I'm running into issues. You can see my attempt in the commented out section, where I try to make two triangles between the previous points and the current ones before adding triangles between the current point and the next. The results are a mess (second picture), leading me to believe my very idea of how to insert these faces is wrong.

http://pastie.org/p/7mv9Fcm4BYC0UguaeLq2BI

sly grove
plain abyss
#

As it is now, it's exactly the same position as some walls (this one is a test mesh that's not aligned with a wall), so there's Z-fighting

#

So I want it to enclose the polygon, but not actually be in the polygon

sly grove
#

so what's the shape/pattern of this mesh and its vertices. Like which order are the vertices coming in in this vertex list? Is the mesh rectangular?

For example is it something like:

0   2   4

1   3   5
```?
plain abyss
#

It's a closed convex 2D polygon guaranteed

#

So, currently, the shape looks like this:

1    3

0    2

With triangles 012 and 231
With a flat panel making up each edge between two vertices. I want to essentially make a face between 3 and 2 with the next 0 and 1, which I think I did and gave me some messed up shapes so I think that very concept is wrong

#

I don't want to add new vertices, because then they'd just be moved along their normals and it'd still be split

#

I just need a face between all these already existing vertices

sly grove
#

I want to essentially make a face between 3 and 2 with the next 0 and 1
you could do 23 and 0 prime yes

#

then it'd be 3 1prime 0prime

plain abyss
#

So, what I want is:

1    3    1'

0    2    0'

I have 012 and 213, then I want 230' and 0'1'3?

#

Actually, hang on, I'm doing this with the previous point, after the vertices are added, so it would actually be:

3'   1    3

2'   0    2

and I want 2'3'0 and 013'

lament salmon
plain abyss
lament salmon
#

thought so, thanks

plain abyss
#

Oh, I am doing that I just typed it wrong again

#

Gah I can't keep all these indices straight

lament salmon
#

I just noticed that 2'3'0 is clockwise and 013' is counter clockwise

lament salmon
plain abyss
#

When I'm writing the code I usually have a post it or something I can look at so I make the code correctly but when I'm reading it I get stuff transposed

sly grove
#

sorry I skipped you and osmal's discussion

#

there are many ways to skin the cat yeah

plain abyss
#

So what am I not doing right in the code? Because from what it looks like I am doing that, and it's giving me these weird shapes when I apply the vertex position shader

lament salmon
plain abyss
#

Should I not be?

lament salmon
#

you should, just checking

plain abyss
#

Yeah, I do it after all the submeshes for this mesh are finished. I am also calling Optimize which could actually be the culprit now that I think about it

#

these extraneous faces are exactly the kind of thing something called Optimize would remove

#

Dang, still wonky.

lament salmon
#

remember you can examine your mesh with Shaded wireframe mode in scene view, if that helps at all

#

To see how your triangles are actually formed

plain abyss
lament salmon
#

top left of scene view

plain abyss
#

Wireframes make sense, shading does not

#

Seems the normals are very wrong

gray pulsar
plain abyss
gray pulsar
plain abyss
gray pulsar
#

oh, so this isn't the 2nd pass of generating the mesh? It looks like it already has vertices that you're keeping

plain abyss
#

I want to potentially support submeshes, so I am keeping the old vertices, the setTriangles only affects that specific submesh. It's currently unused, so every time this is run it's a new mesh

#

That's just some future proofing

gray pulsar
plain abyss
plain abyss
#
  1. If they have a question they should ask it
  2. That's not a very good question
  3. Probably doesn't belong in advanced
chilly nymph
#

Editor script for adding gizmo / node to the scene inspector? I just need to grab positions.

#

Need to know the API functions.

chilly nymph
#

Looks good, thank you!

livid kraken
#

Im trying to implement this technique https://tellusim.com/mesh-shader-emulation/ but Im strugling to make it fit with unity's API. Anyone more knowledgable can give any pointers? I think I need to call draw procedural indexed once and essentially render my meshlet polygon soup as one big mesh, but I fail to understand how I can push the meshlets vertecies into one big buffer once and then index them after a culling step.

wispy terrace
#

How could I get the world position of a sprite vertex that's got a sprite skin component?

tawdry laurel
#

I was trying to convert a json file and I got stuck on this part, how the hell do I convert something like this? example[[1, 2 3][2, 3, 4][4, 5, 6]]

flint sage
#

Well that's not valid json so you don't

tawdry laurel
#

thats also just an example

flint sage
#

It's like a list<list<int>>

#

But again, not valid json no matter where you put it

tawdry laurel
flint sage
#

Yeah sure, { "example": [[1,2,3], [2,3,4], [5,6,7]] } something like this would be an array of int arrays

flint sage
#

float[][]

tawdry laurel
flint sage
#

Yeah because unity doesn't serialize it

tawdry laurel
flint sage
#

If you want to assign values in the inspector no, otherwise yeah

tawdry laurel
flint sage
#

No worries, it's just hard to say whether it's failing because of the invalid syntax or because of the data type

tawdry laurel
icy aspen
#

Im having a bit of a problem with the way I should implement a user inventory in my game in unity.
I get the list of the inventory from the database, this is just a list of titles from the inventory without any further information. But now I want to append some information to those values. How can I do this knowing that I can’t send that information to the database?

iron pagoda
turbid stirrup
#

Within C# scripts, does byte endianness differ between platforms? We're targeting Desktop, Android and iOS?

flint sage
#

When doing what?

tawdry laurel
flint sage
#

Show code

sly grove
sly grove
grim oak
#

Guys, I have a question and it has been bothering me for a week now. Basically, I am making a WebGL build of a game. In this game you can record audio through your browser using your microphone and have it played back. That all works. Now I want to save the recorded audio clip to a .wav, so I need to get the raw data. For this, I use AudioClip#GetData. The documentation states that this returns a float array with values between -1 and 1, but for some reason I also get values outside of this range and NaN values. Anyone know what could be wrong?

#

https://gist.github.com/darktable/2317063 I used this script I found through the Unity forums. For some reason it works for everyone, except for me. My audio clip is not corrupted, since I can play the audio back without any trouble.

undone coral
grim oak
undone coral
grim oak
#

Alright, thx!

sand quail
undone coral
plain wind
#

can someone advanced help me make third person movement fix? in dm

fresh salmon
muted ridge
#

Hey, im trying to use a kinect V1 with unity by using the Microsoft.Kinect.dll. However, i get an error stating:

EntryPointNotFoundException: #1 assembly:<unknown assembly> type:<unknown type> member:(null)
Microsoft.Kinect.KinectSensor..cctor () (at <db268133f35341fe808d1e204c642ce2>:0)
Rethrow as TypeInitializationException: The type initializer for 'Microsoft.Kinect.KinectSensor' threw an exception.
Test.Start () (at Assets/Test.cs:15)

Why is this happening? The DLL works fine in visual studio by just adding the reference.
this error occurs when running the game

midnight violet
#

Do you guys know a good way of recording ios and android screens in Unity without nested frameworks? Like unity provides the replaykit for iOS, but is there any equivalent to Android?

cosmic tendon
#

I have a small question

#

i have 2 scripts

#

both in different Assembly Definition

#

how can i reference from script A to Script B

#

?

midnight violet
cosmic tendon
#

BECAUSE AM NOT NORMALLY REFERENCING 2 SCRIPTS

#

EACH SCRIPT IN DIFFRENT ASSEMBLY DIFINITION

#

SO I CANT REFERENCE IT

midnight violet
#

You better fix your caps

#

@cosmic tendon

hallow elk
#

So I suddenly cannot Attach to Unity for debugging. I have already regenerated my project files. When I click "attach to unity" VS builds something and then does nothing. The debugger isn't started.

#

I am using VS 2022 and Unity 2020.3.5f1

obsidian glade
jolly token
arctic lake
#

Do I have to ask for permission in order for another PC to have voice recognition enabled on their end

zenith ginkgo
#

Windows? Don't think so. though you should have it written in the terms of service that it requires microphone.

undone coral
#

you probably do not have all its dependencies

#

@muted ridge did you install the Kinect for Windows SDK?

#

and are you on windows 7, 8 or 10?

#

@muted ridge anyway here is my source repo for recording particle clips from the kinect

sand quail
hallow elk
#

Here's a fun one. I have a game that is playable in both VR and desktop. The only difference between launching the game in VR or Desktop is whether XRGeneralSettings.InitManagerOnStart is set to true—the game's initialization scripts handle everything else.

Rather than have to juggle two separate builds, I'd love if I could create a command line argument I could pass to, say, steamworks, that sets this option on or off. But I am having difficulty finding relevant documentation.

hallow elk
#

I found a tutorial that breaks down one way to do it, but now, no matter what I do, it still initializes XR. I don't want it to initialize XR if the desktop argument is set.

hallow elk
#

Ugh. How do I stop XR from initializing?!

limpid prairie
#

I just realized Unity's Script Order Execution doesn't work at all on an Android build, and it took me way too long to figure that out.

#

Anyone know an alternative to that feature but without using it?

flint sage
#

It does work?

#

Maybe not in the way you expect but it does work

#

(or you might be on a version where it's bugged but I doubt that would be in a full release)

sand quail
limpid prairie
limpid prairie
# errant thorn Wait what why?

Reviewing it again, perhaps it was working, but I also had other scripts, that were running in random order, but had a tendency to be in a certain order in Android and in another order on PC.

#

Not that one should be relying on the Script Order Execution for a massive amount of scripts, but I just have a few that I need to be in order, so I did the solution similar to above.

random dust
#

Script execution isn't in a set order

#

Execution order of methods are

#

You can add scripts to be invoked earlier in settings

pastel wedge
#

sorry, don't have much experience with HPC#
but I just can't find an obvious way to get local ref to an element in NativeArray. seem very natural thing to have for native container, is there any?

real plume
#

i'm trying to add a "pipe" type functionality to a game, and the aim is to be able to detect if end-pieces are connected by other pipe pieces so that they can be considered connected entry/exit points. i already have a system to detect end pieces (just having 1 pipe neighbor) but i'm not sure how to make each pipe group considered a separate pipe when they're not connected and the same when they are. is there a known/recommended technique for this type of thing?

tawny bear
void blaze
#

What's a good storage platform for saving private user files? I'm cross-platform iOS-> PC so Ideally it would be compatible with a restAPI for my users.

void blaze
#

Actually a P2P solution would probably be just fine...

stuck onyx
undone coral
jolly token
oak barn
#

can someone help me with this small part of code ?

#

public FsmInt SceneIndex;

    public FsmString SceneName;
    private Scene ptitescene;

    // Code that runs on entering the state.
    public override void OnEnter()
    {
        ptitescene = SceneManager.GetSceneByBuildIndex(SceneIndex.Value);
        SceneName.Value = ptitescene.name;
        Finish();
    }
#

I'm trying to get the name of a scene from the build settings using a int, and it seems to not give me any result

sly grove
#

If the scene is not loaded you'll get an invalid Scene struct

oak barn
#

ok thanks

oak barn
#

is there any kind of way i can do to avoid this and just get the name from int ?

fresh finch
pure bough
#

Hey, could I get an hint for tech solution?
I am trying to add payment gateway(paypal, stripe) in Unity mobile.
how can I do this?
could you help me?

jolly token
#

Trying to write custom struct Linq with bunch of generics
Would there a way I can hide type info or make this tooltip simpler (for any user)? 😅

compact ingot
jolly token
#

Yeah I probably have to refactor 😌
Currently it's gonna explode to 2^x, that was dumb approach lol

#

But it's still gonna be pretty long, maybe extension method can make it look better somehow..

fresh salmon
#

The entirety of LINQ is extension methods so yep, it'll lighten this monstrosity

real carbon
#

Why Unity is calling constructors on private fields of classes that are marked as Serializable? I thought only public fields were serialized. Is this a bug or am I missing something?

public class Test : MonoBehaviour
{
    private TestClass testClass;
}

[Serializable]
public class TestClass
{
    public TestClass()
    {
        Debug.Log("Constructed"); 
    }
}

This log is called after scripts are compiled. I have to mark the field [NonSerialized] to make it ignore the serialization

hushed fable
#

If for no other reason

long ivy
#

yep, private variables can be serialized in the editor when scripts are reloaded

real carbon
#

But that makes the [SerializeField] meaningless, as it just makes the private field visible in inspector then. It doesn’t actually force it to serialize 😄

hushed fable
#

I imagine there is a difference when it comes to the build

#

Also prefabs and such

real carbon
#

The constructors are actually also called on the prefabs when scripts are reloaded

long ivy
hushed fable
#

Yes, but the values won't carry over through instantiation

#

.. right?

#

At least they wouldn't survive editor rebooting, since they aren't actually serialized to disk

real carbon
#

Haven’t tested the values. My concern was about the constructor call, which were breaking something in my game

long ivy
#

add [NonSerialized] to the private field, counter-intuitive as it seems

real carbon
#

I’ll move the code out of the constructor but Unity documentation is misleading

#

As it states

To use field serialization you must ensure that the field:
Is public, or has a SerializeField attribute
#

Well its neither but still gets serialized

real carbon
hushed fable
real carbon
#

So I guess there is really no point of [SerializeField] other than make the private field visible in inspector

hushed fable
real carbon
small torrent
#

Hey folks! I was wondering if something was already a solved problem or a known algorithm or something. I don't want to reinvent the wheel if I don't have to. I have a really weird problem I want to figure out for a weirder game
If you have a cube box, and you have X sides each with a hole on them, how do you take every configuration for any number of X sides having a hole and any multiple of 90 degree rotations on a cartesian axis, how do find any combinations that are duplicates of another combination if you rotate them to align? How do you make a list of the ones that aren't duplicates and also sort the list somehow?

edgy goblet
#

Where is problem??


    public float speed = 20f;
    public float gravity = -50.81f;
    public Joystick joyStick;
    private Animator animator;


    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;

    public float rotationSpeed = 600f;
    Vector3 velocity;

    bool isGrounded;
    void Start()
    {

        animator = GetComponent<Animator>();


    }
    void FixedUpdate()
    {

        // checks is player touching ground

        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);

        // Player Movement

        float x = joyStick.Horizontal;
        float z = joyStick.Vertical;

        Vector3 move = new Vector3(x, 0, z);
        move.Normalize();

        transform.Translate(move * speed * Time.deltaTime, Space.World);

        // Player rotates to side he walks

        if (move != Vector3.zero)
        {
            animator.SetBool("IsMoving", true);
            Quaternion toRotation = Quaternion.LookRotation(move, Vector3.up);

            transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
        }
        else
        {
            animator.SetBool("IsMoving", false);
        }

    }
#

My gravity dont work after i sownloaded my game in phone...

hardy nymph
#
public void onElementClicked (uiElement elementID) { 
    Debug.Log (elementID.GetType ().GetProperty ("normalColor")); 
}```
#

Why does this output null when elementID is clearly a upcast* of ButtonElement that has 'normalColor' (uiElement is superclass)

#
public void onElementClicked (uiElement elementID) { 
    Debug.Log ((elementID as ButtonElement).normalColor); 
    Debug.Log (elementID.GetType ().GetProperty ("normalColor")); 
}
#

Output:

fresh salmon
#

Oh I see what you mean now, wasn't very clear that you passed an instance of ButtonElement as the argument

#

Should get the property as expected, it does on my side with a simple 2-class setup

#

Outputs B, Int32 X as expected.

hardy nymph
fresh salmon
#

You sure .normalColor is a property, not a field?

hardy nymph
#

Here's the full class

#

Line 90 is where I detect click event and pass this

hardy nymph
shadow seal
#

That looks like a field

fresh salmon
#

It's a field yep

#

Properties have { get; set; }

#

In VS properties will have that small white wrench icon when you hover over it, fields it's just a blue cube I think?

hardy nymph
#

Hmmmm okay, how so I access the field ?

fresh salmon
#

Also I hope the class you're deriving from uiElement isn't a MonoBehaviour nor derives from one

#

.GetField(string)

hardy nymph
#

Yea uiElement isn't MonoBehaviour

#

Oh it worked thanks alot. Need to learn the difference between field and property.

swift prism
#

the cubes need to instanciate exactly at the cube's position and scale

#

a destruction voxel system

fresh salmon
#

When you instantiate subtract all XYZ components by 0.5 to clear out the offset

#

Or subtract (the old cube's size / 2) to be more precise

#

You're also adding transform.position twice in the Instantiate call, with v and localPosition

fresh salmon
#

You'll have to be more explicit than this

#

What I would first do is get rid of all the unnecessary stuff your IDE says it's redundant

#

That will clear out the code

swift prism
#

the cubes will spawn the same, it dose not matter the size

fresh salmon
#

(GameObject) is grayed out before Instantiate for example, it's very much not needed here

#

Then I would split the whole "final position of a cube" calculation out of the Instantiate and in a local variable before it, so it's easier to debug out

warped mural
#

Hello! I want to generate a Guitar Hero-like List of beats before the song starts and based on difficulty multipliers.

I have found this that gets me some music data, but for an ongoing song and just a piece of it.
https://docs.unity3d.com/ScriptReference/AudioSource.GetSpectrumData.html

For code reasons, I need to get the entire song's data before ever doing Play().
Getting something like this is enough, I don't really care about frequency, amplitude or anything that needs calculations and performance damage, just a simple Winamp like wave. Thank you kindly

swift prism
fresh salmon
#

haha the more I look at the code the worse it gets

#

Like I just saw .gameObject.GetComponent<Transform>()

swift prism
clear wedge
#

hey yo - sorry to ping after so long, but I'm running into tons of problems with assembly definitions - it's like a cascade effect that forces me to add asmdefs in tons of other folders in my project to be able to use that one i made for conditional compilation. any other ideas? 😓

swift prism
jolly token
clear wedge
#

I'm making a package, if I add asmdef, then everyone consuming my package needs to add their own asmdefs that reference mine, right?

real plume
#

I'm hoping someone here can give me advice here: i'm trying to make a "pipe" type mechanic in a tilemap game (doesn't have to be tilemap though), and the aim is to have an intake pipe where water goes in and any number of exit pipes, but obviously i only want the water to transfer from intake to exit if they're in the "same pipe". my strategy so far (just starting) was to make a list or dict of intakeValve type classes and then inside of those i will have another list or dict of connecting pipes, which i would obtain by going through the entire tilemap multiple times to determine iterative partners and adding them to each appropriate list if they have intersections with previous connecting pipes in the dict in the intake valve class. so as you can see this is extremely tedious to even think about let alone implement, and i have a feeling the performance is going to be pretty bad. are there any better ways to do something like that, or is that pretty much the way this type of thing is done?

real plume
midnight violet
#

Not sure, what you mean? Can you explain a bit?

real plume
# midnight violet So what you want is like, draw a pipe form left to right and then top to bottom,...

that was my first version and it worked well enough by averaging the pipes, but i found the performance hit was a bit much and the waterflow is extremely slow. player would have to wait like 10 minutes for a relatively small pool to transfer from one place to another. so my new version (to keep things understandable) is to have a single intake point designated per pipe, and then any number of exit pipes. it would be simple for me to just transfer water from all entries to all exits, but i want an entry and exit to only be paired if there are connecting pipes. so in other words, they are "a single pipe".

#

sorry i should say entry pipe tile and exit pipe tile and any number of connecting pipe tiles

#

to make up a single "full pipe"

midnight violet
#

You cant modify an array while iterating through it

#

Thats why its being copied

real plume
midnight violet
real plume
# real plume yeah, if they have connecting pipes between them, i want them to be considered '...

the trick is that there can be multiple of these "full pipes" in the game and if they were to somehow connect to other pipes i would want them to be then considered a single full pipe, with all the entries and exits to then be a single "full pipe", and if a section were destroyed that changed that to being untrue, reevaluate to see which full pipes we have left. yeah i guess i probably do want to do pathfinding? not quite sure tbh

midnight violet
#

thats what I meant with my, left to right and top bottom. you draw one full pipe [ENTER][INTERSECTION][EXIT] and than the same from top bottom, than the intersection of both full pipes would combine and get a new full pipe with 4 entries/exits?

real plume
real plume
midnight violet
#

I did a little pipe minigame a while ago and actually used trigger collisions on all opening sides to check if its attached to something

#

you could also let the pipetiles on creation check their surroundings, what type of pipes there are and what do do with them

real plume
real plume
midnight violet
#

yeah, if its like 2d, you would have a matrix of 3x3 to check on creation of one tile for example

real plume
real plume
midnight violet
#

Yeah, I got you 😄

#

I would get the pipe position on your grid and then update it depending on its neighbours

real plume
#

like if i told the detroyed pipe neighbors to look at their neighbors, all of them would say "yep we're pipe X"

real plume
midnight violet
#

And you can always filter like, if the new tile is touching two existing pipes, just update those pipe tiles, and if they touch another pipe, update those tiles if necessary. You will update them only on creation anyway.

lament salmon
midnight violet
#

I guess it will not even be called every frame.

#

But I dont know the mechanic he tries to implement in gameplay

midnight violet
real plume
lament salmon
real plume
undone coral
clear wedge
#

will do!!!

jolly token
#

Unless you build them into dll that is, but it won't be easy if you have Unity references from your assembly

clear wedge
#

got it, makes sense. I might use some awful hack like on build start move the folder somewhere else

jolly token
clear wedge
#

appreciate all the help 🙏🙏🙏

sterile snow
#

So I have an odd pickle I'm in, I have a myriad of classes in my game that are used for describing individual selectable stages and player characters. Not MonoBehaviours, simple classes inheriting from common parents. But I need a way to keep some sort of "list" of all of them so that, when they're selected, their constructor can be easily called (maybe through an ID lookup?). The way I have it now is that all of them are instantiated before the game starts and it keeps references to those, then simply uses whichever one is needed through a lookup table. But this feels kinda terrible since it means a ton of wasted, unused instances, and much of their information specifically needs to be loaded through the constructor, so whatever happens in their constructors also get wasted. I'll only ever need one of those stages and one of those player characters at any time loaded, after all. Any thoughts?

jolly token
sterile snow
#

I'll show a sample, one moment

#

Oh that looks kinda odd in Discord, actually hang on

jolly token
sterile snow
#

This'll do

#

Veni's constructor looks like the bottom image

jolly token
#

Ah. So you are loading assets

#

Well you can load the asset when you actually need it

sterile snow
#

Suppose that's true, could set that aside into a method

jolly token
#

Yeah other things like reference, names or some variables, that's not going to take much