#archived-code-advanced
1 messages · Page 21 of 1
hmmm..
Do I need to manage this myself by creating/destroying texture objects as-needed
do you mean creating andDestroy(orDispose) onTexture2Dobjects?
are you creating textures from files?
is this for creating a map?
yes that's what I mean
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.
Maybe this helps? The data you define when creating a mesh is in local-space, then when you draw the mesh you supply a matrix that transforms it from local to world space. If you're assigning the mesh to a mesh renderer component, the matrix will come from the gameoject's transform component.
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.
Right now I am not feeding it into a Matrix. I should probably feed it there.
well, how are you rendering the mesh?
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
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)
would something like this work?
for(int i = 0; i < PointPositions; i++)
{
var convertedWorldToLocal = transform.TransformPoint(PointPositions[i]);
_sharedMEsh.vertices[i] = convertedWorldToLocal ;
}
heya doc 🙂 I dunno! will take a look, thank you
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.
https://docs.unity3d.com/ScriptReference/Transform.InverseTransformPoint.html to go from world to local-space.
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!
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?
do I need to consider the GPU memory and avoid having too many Texture2Ds created
yes
or does Unity somehow automatically evict textures from the GPU as needed (if so, how does it make that decision)".
no
that said, you know unity has a virtual (streaming) texturing solution?
texture data is coming from a native plugin which is either generating it or loading it from a file.
when you say texture data, do you mean byte buffers, or actual graphics API textures?
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
you can look in the profiler to see what is making the game slow down
you should also probably check it in standalone
thank you so much! i will take a look at the profiler, and standalone
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:
- I need to magically know ahead of time what force I need to keep that circle from disconnecting from the hill.
- I need to detect when the circle has disconnected from the hill, and adjust its position back to touching it.
- 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?
- Is possible - you could use a spline.
whether that's appropriate or not depends on exactly what kind of effect you're going for
More broadly, I'm trying to make this possible with a dynamic rigidbody of indeterminate shape, and terrain which can be both convex and concave.
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.
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.
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.
either way - it's straight lines
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.
You want a pathfinding algorithm
Look up Djisktra's algorithm and A*
you're not incredibly far off from the structure of such algorithms here
What would be the distance estimate in this case? You'd have to calculate a path between nodes to count how many steps it takes.
if your edges are not weighted, the distance between any two nodes can just be considered 1, right?
Well the nodes definitely have positions in the world
if they are weighted, then you use that
so no worries bout that
then you can use the actual Vector3.Distance as the edge weight
yah
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.
I can't find Djisktra's implementations for only one path rather than the whole tree
That's what A* is for.
you either use A* or your just run Djisktra until it chances upon your desired destination
Which one is easier to implement 🤔
A* is basically the same as Djiktra's with an additional heuristic function
I really like this video. https://youtu.be/-L-WgKMFuhE
Welcome to the first part in a series teaching pathfinding for video games. In this episode we take a look at the A* algorithm and how it works.
Some great A* learning resources:
http://theory.stanford.edu/~amitp/GameProgramming/
http://www.policyalmanac.org/games/aStarTutorial.htm
Source code: https://github.com/SebLague/Pathfinding
If you'd...
Sebastian Lague is pretty cool yes
Oh shoot, Sebastian Lague made it?
Didn't even notice that. I found the video before I knew who that was.
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
I recall in Seb's tutorial he gets a List<T> of nodes
I'll look at the source
it's very complicated tho
I guess i'll implement it as a dictionnary
Does anyone know to change your curosr speed in unty with a slider
Alright that's the answer I was looking for (though I assumed that'd be the case), thanks. No I didn't know it had an SVT api, I'll look into leveraging that
iirc he later fixes it up to use a Heap and HashSet
Cursor speed is an OS setting, you can however hide the hardware cursor and make your own and make it move as fast as you like relative to the movement reported by the OS
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
What are you calculating it from? Simply moving or rotating it will force it to recalculate for all typical intents and purposes
aye, the TRS transformation of a gameobject is recomputed when you assign it a position, rotation or scale. The camera matrix, you can ask the camera for e.g. https://docs.unity3d.com/ScriptReference/Camera.CalculateObliqueMatrix.html
@sly grove👋🏻
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
👋
I dunno about that.. but you can always ask the transform for it's matrix. that would HAVE force it. https://docs.unity3d.com/ScriptReference/Transform-localToWorldMatrix.html
and that is just read only
so i cant force it through that
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.
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
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
Your A* is not tile based? That leaves some possibility that your nextNodes contains wrong values
Also irrelevant from the issue, not sure why CalculateWeight counts distance from start..
I saw some implementations doing that
I'm pretty sure the GetValidNexts is good from testing
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)
There is LerpAngle and Slerp
It’s not a good idea to use result of transform.eulerAngles though, it’s better to manage your own variable
if I remember right, this is one of the potential drawbacks of using euler angles as opposed to quaternions, direction is sometimes ambiguous
should be able to do some basic conversion stuff to do what you want
i dont really understand quaternions
alright
if i remember quaternion has a method for rotating by a certain amount
works like a charm! thanks
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
Afaik Entity framework massively uses runtime code generation, I would be surprised if you even make it to build.
System.Reflection.Emit and System.Linq.Expression is not supported on IL2CPP
Are you building with Mono?
where are you seeing references to those?
yeah I think so
EF would require them
Yeah it is coding question
this question lol
What is your stripping level?
Oh sorry read wrong lol
Config in question xD
Looks like it is disabled at the moment
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)
Hmm I think what you did make sense.. what about managed dll part?
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
Id like to try this package out, but its complaining that I am missing Mono.Android it seems
https://www.nuget.org/packages/SQLitePCLRaw.lib.e_sqlite3.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
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
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
You might have better chance with this one
https://github.com/robertohuertasm/SQLite4Unity3d
It wouldn’t be fancy as EF but still ORM
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
How does il2cpp know what assemblies to load?
So far, testing on windows, its working, so time for the android test
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
hello soralin
zenject 😱
i think there might be a sql to c# thing like JOOQ
entity framework as cathei said is pretty solid but hard to use in Unity
this looks nice
I tried to get it to work, it worked for windows but failed for android
i think this is the closest thing
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 😦
This is the one I am testing atm https://github.com/robertohuertasm/SQLite4Unity3d
it's very hard
it has an android target included, testing if it works on android atm
yeah raw sqlite based stuff should work well
finally got it to compile, unity was being dumb and was trying to shove the windows dlls into the android build
its an ORM
a very lightweight one, but it works, its like diet Entity Framework
good good
excellent
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:
All good? 😄
Looks like you managed to get it working, nice
Could i create and load a il2cpp domain at runtime?
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);
}
I don't think textureCoord property is valid on any other query than raycast/linecast.
You could do raycast to hit position again when the hit is detected.
Which you can do cheaper with Collider.Raycast instead because you know it hit.
hmm i see
Your solution def seems like the way to go. Ty!
Out of curiosity though would u happen to know why that is the case for the spherecast? given that both still output a RaycastHit I would assume they would still be able to get back the texture coordinate
the documentation also dosnt seem to mention anything about it
Yeah they just use RaycastHit as common interface but the behavior is different depending on query
For example distance represent different thing depending on when you do Raycast or Spherecast (though this one is documented)
So I guess it's just some special code exists for raycasts to get uv
interesting guess i gotta look into this to avoid other weird pitfalls in the future. Thanks for the help and clarifications!
Daily Unity: Fails to write proper Regex for package name 😇
https://forum.unity.com/threads/define-constraints-are-not-filtering-plugins-pluginimporter-defineconstraints-also-has-no-effect.1246426/#post-8499701
Is there a way I can get extraScriptingDefines of current build from IShouldIncludeInBuildCallback?
Or at least from IPreprocessBuildWithReport? Can't believe they don't have that
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);
}
}
}
}```
the default easy add comonent and you are done feature will not work with your scriptable object
you probably have to integrate with the localisation system to request the translated text each time one of the tips in TipList is requested / uesed
Yes, I'm asking how can I do that. Also, thank you very much for your reply. 🙏
i dont know, i dont have the plugin so i cant look into that
I've been waiting for an hour for someone to reply to my message, and thank you very much..
I can provide AnyDesk if you can help.
i dont know the plugin so that is probably not much help
i only use my own localisation system
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
Can’t you do LocalizationManager.GetTranslation?
The problem is that every time I add a hint text in the ScriptableObject I have to type the term for that hint text. So I don't know how to do it. Because I am using spreadsheet google.
I would be really happy if you could help. If necessary, I can share the relevant code in my project with you.
So you wanna convert your texts in SO into I2 terms?
oh yes
But it should be without losing SO logic, because that's just how my loading screens work.
I don't think there is feature to convert translate language to term.
You could manually loop through terms convert with editor script.
You should start using term to indicate localizable text
I2 localization plugin.
why are you using this instead of unity's plugin?
Oh, no that's not what I'm trying to say.
Hint texts are information that appears on the game loading screen. So I just want to sync the hint texts I've added there and the hint texts I'll add in the future to google spreadsheet.
Actually that's basically all I've tried to do. I'm not asking for anything fancy, and I'm really sorry to take up your precious time.
Because it's easier and something I'm used to. I don't know what the Unity plugin is.
Is TheTipList the scriptable object?
yess one min.
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
Yeah I'll try that I guess it looks that way.
How do i add a ascript to appdomain at runtime?
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.
event EventHandler > event Action ? when yes why
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
does photon fusion work with webgl?
it does
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?
okay
have you tried building and running your game as a standalone desktop application?
just a simple yes or no
yes
and does it work
yes
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?
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
What's the first error say?
So a little background... I use Mac os and windows with github desktop. I am able to build on windows, but not on mac. Is there a problem with the filesharing perhaps?
Is there any tangible information further down that error past all the arguments?
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.
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
have you ever started unity or unity hub as an administrator?
there's a lot you still have to leran but you'll get there!!
No. I’ll try that.
ohh. @undone coral okay. I didn’t.
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
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.
Is Thier something I can do to clean the muck?
git isn't file sharing
Version controll.
is that what you mean by file sharing?
okay
did you use a .gitignore you found online
or did you author your own?
Sorry I thought they were kinda interchanable.
do you use any plugins / libraries / assets with their own .dll files?
Yes to the .dell files. I have an infinite runner engine from more mountains.
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?
Also I think thier was a .gitignore place in for me when I set up the version control.
It’s a MacBook Pro 11.
11...
hmm
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
Working on it. Thanks. I feel like this will fix the issue.
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.
Can someone recommend any mvvm framework for unity?
They already implemented bindings?
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
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
Have you Googled it?
sure 🙂
Because I certainly don't know the answer, but Google might
the documentation is not that detailed regarding vsync implementation in unity
i tried, also for directx in general - but it seems that this is a very uncommon thing 😦
Bummer
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
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)
this isn't going to resolve your problem
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
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
do you mean enabling vsync at all?
yes, a prototype ar device
okay
no, i know how to enable vsync in unity
so the displays are not synchronized
exactly
yes, there is tearing
yes
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?
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
phd
no
okay
if you are using nvidia graphics, you can configure it to force v-sync on for both displays
in the nvidia settings panel
i'm just wondering if it is in principle possible for d3d to enable vsync on two different display adapters at the same time
if you want to synchronize the displays, and they support gsync, you would need a quadro card, and then it's another checkbox
from my understanding, this should be possible if each device has its own swap chain
directx simply asks the graphics driver to do this, you can also ask the graphics driver using the appropriate panel in windows
yes, i'm using nvidia - never knew this options exists
vsync can be enabled on both displays
do you know how this is called?
🙂
rtx 3070 in my development machine
okay
so you will never be able to do this, i am sorry
you have to buy a quadro card. i suggest an A5000
if you want the two displays to present at the same time, it's a checkbox, provided they support gsync
they don't support gsync
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
why exactly? couldn't i just set up my own d3d renderer with a swap chain for each display adapter?
this also enables it to run the refresh exactly after a frame is prepared, at basically any framerate
hmm, that you keep asking this is concerning me
why? 🙂
do you aspire to use HDRP?
no
nope, basic graphics is fine
are you confident your displays cannot have their refresh rate driven programmatically?
are these experimental displays?
these are 2.9 inch and 3.1 inch mini displays
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
but only for one display 🙂
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?
having independent vsync for each attached display
see, you say independent
its not stereo vision
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
this is not a classic ar or vr device with two displays, there will be more than 2 displays eventually
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?
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
okay
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
well did i give you an adequate solution?
alright i gotta go
sure, thank you for your help!
// 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.
@calm ocean this isn't really advanced code
what is your objective?
why are you reinventing UniRx?
My objective is to subscribe a method to a unity action that exists in a different class such that you can unsubscribe that same method again.
I am not sure what that is, I will look into that.
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.
It's not about signature, it's a delegate type that is different
Also event keyword exists just for this purpose
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#
You can do with new input system
Not the Input class
Hmmmm awesome, do you have any reference for that? What is this new Input System?
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
Thanks for the reference Fogsight! by the way, the variable I'm using here is private, so that's why I could not change it from the Test Script. Moreover, I don't see a reason in my case to make it public, so that's another reason I was looking for an alternative
i think you should stop doing that
I am trying to create an event-based scriptable object architecture,
this is a bad idea
you should use unirx
it is the correct implementation of publish and subscribe for unity
I am taking a much deeper look at UniRx, it's very interesting, I didn't know it existed until today. But out of curiosity, why is the scriptable object approach a bad idea?
I suspect they said that because scriptable objects are really just a data container for Unity.
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
It’s makes stuff hard to debug and generally can create a lot of confusion, when used carefully, with discipline and where it makes sense, it is perfectly fine
Wait, I know it depends on the situation, but aren't scriptable objects generally easier to debug because they are scene independent?
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
It depends 🙃
Oh so scriptable objects open more opportunities for misuse, hmm, okay I understand, though perhaps good documentation and interfaces can mitigate that?
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
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 !!
Need for documentation is an anti pattern, best doc is unnecessary doc
best code is no code
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;
}
Through a paste site
At a glance I don’t see you awaiting any async code, are you actually sending the request? (Maybe I’m blind)
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
Paste sites are linked in #854851968446365696
ok, questions, why aren't you using HttpWebRequest?
You are saying your API server treats PUT request from Unity as GET request? That doesn't make sense, maybe something to do with your serverside logic?
Ok sorry, I did read the read me but not all the way (shame lol) ! And the confirmation that my request is being sent is in the logs from my api, just thought of that
It just does that when I send my request from unity, and works with other ways of sending requests (reqbin.com for example)
I will try with HttpWebRequest when I get home !
actually, you shouldn't you should use HttpClient, WebRequest is obsolete/deprecated
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;
}
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
use a better IDE 😄
..?
how can using statements be a problem, ever?
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
Thank you so much I will try that tomorrow actually, I'm not sure to come home early enough
Because this is a little easier to type (and looks cleaner IMHO) than this
i'd say its worse
(but I only started doing that using static recently so I have .. dozens/hundreds of files that are using the old way)
it obfuscates what the thing is
you prefer the later with the fully qualified thing?
yes
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)
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 😄
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
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
What do you mean by "small methods" here?
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?
LateUpdate() happens before rendering - you probably need to put logic like that later, like OnPostRender or whenever in the render cycle it's appropriate
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.
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... 🤷♂️
Yes for UI elements that exists, but haven't been able to find anything similar for meshes/spine Renderers
Are you talking about Spine 2D animation runtime?
Yes.
You can manually call skeletonAnimation.Update(0f) and that usually do the job
Yes, unfortunately not here.
The bounds are huge in the first frame, not sure why in particular.
Hmm. is Initialize getting called when you create it?
Maybe your spine's initial pose has something big.
That is a good idea(initial pose) I'll check that, thanks.
you were working on a rewrite of a game right?
you should be using UnityWebRequest
The question I had just now was for a different project
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?
I feel that it is not mutually exclusive to scriptable objects.
don't use scriptable objects for anything!!
Hold up...
here is a good one - https://github.com/cathei/AntiScriptableObjectArchitecture
from yours truly @jolly token
I just watched a unity talk about anti monobehaviours, and now I am seeing one on anti SO...
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
async UniTask Jump() {
m_Sound.Play();
m_JumpParticles.Play();
m_Animator.Trigger("Jump");
await UniTask.Until(() => m_Animator.IsInState("Landed"));
m_LandedParticles.Play();
m_Camera.GetComponent<MMFeelShake>().Play();
}
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**
Low key agree, ECS is not a fit for every game. Only games that meant to be ECS fits for ECS IMO 🤔
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
dots is potentially fantastic for simulation/systems based games where it enables much more fine grained systems, whether anyone can leverage for more meaningful gameplay is an open question, it can certainly also be done without DOTS with a custom engine, but those being wildly out of reach of the average indie who would attempt such a game, i think DOTS has something valuable to offer
I generally agree DOTS, URP, SO, even automated testing is very often not needed and often more work than any value a developer will get out of them, in most practical cases.
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
ROI uses for scriptable objects? And what's ROI?
Okay I agree on this so far, I am not sure what UniTask is, so I will have to look into that.
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.
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 🙂
Math.Sqrt wants doubles
I'm pretty sure all Math methods use them, and Unity wraps them into Mathf
Yeah Mathf source is just bunch of type casting lol
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?
Well... which part is setting initial value to timeLeft?
And also post your code in readable form pls 😅
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?
Oh yeah, sorry, I didn't realize how blurry it was. 
Will do.
Sorry for the delay. Here are all relevant screenshots. 👍
The code in screenshot 4 gets called whenever a cube is shot.
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
Ok thanks, I'll try that.
You put =- not -= 😅
Good spot. Debugging would have narrowed it down to that pretty quick, but the eyes are speedier in this case 😄
Oof lmao! Thanks so much!
But yeah debugger is good solution for general issues like this 😄
And auto formatting too
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
thanks bro I feel so much better
anytime Chase
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
I bet you know more than most though, if you already have some familiarity with c#
Just a matter of learning the unity api stuff as needed, you got it
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
Hello there, is there a way to create a EditorGUILayout.DelayedTextField using GUILayout.TextField?
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
}
Do you know casting?
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";
And you said normalColor is only on button
Do you know is operator
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
Yeah and probably move to #archived-code-general
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
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
If I set the _NewMousePos to 0 at OnMouseUp, the object I'm trying to rotate always snaps to a certain rotation
question better suited for #💻┃code-beginner - worth reading the docs on Transform.Rotation & Quaternion, also worth a rethink/debug on how you're getting the mouse world pos & updating the position (what do the vectors actually represent at each stage?)
What's the specific error message you're receiving?
My issue is resolved ! I tried your code earlier and it still didn't work. I added a profiler to my api, to see the requests and content, etc. Turns out I was sending a null body 😅 I feel relieved that it now works but at the same time so dumb not to have had the simple idea to add Debug.Log(data) in my request function. Thank you so much for your help 🙏
how do i make crouching properly? im getting jittery stuff here https://gyazo.com/08967a66edeb500c1f929515028f3bf0
https://gdl.space/qedaponoli.cs
You're making the same mistake as Yzaka in #💻┃code-beginner #💻┃code-beginner message
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
coroutines also have no business in a character controller
i was tryna make a proper lerp
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
wdym by "all assets"?
with a color post effect... depends on your RP which one
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
animate the intensity value with a lerp over time
hm ok ill have a look thank u
https://gdl.space/ufokeyurul.cs
i tried fixing it is it the right way?
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?
I think so, but you shouldn't use coroutines for it
Adding to this: I originally looked into using a stencil shader but I have literally no experience with it
yeah i realised that i wont be able to uncrouch until crouching is fully finished
Anyone that can see the issue?
they rotate down-right on start, whilst it should be working correctly
Why does your index start at -1
booleans are by default false
floats are by default 0
Is the cube the door?
You can add an empty gameobject as a pivot
Nothing wrong with being explicit to show that default value is intentional
I guess that's fair
Though every dev would know what the implicit value would be so eh
This.
Having a variable called index at -1 is still a bit questionable though
well its so it doesnt interact with the other object in the array (in this case)
I think it’s more of showing intention by setting the default value than value itself
I guess so
It is, unless it’s ‘before start’ state, IEnumerator does it xD
idk this one’s intention tho
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)
Does the player see the enemies spawn in?
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
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
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.
Easy, but inefficient (and theoretically infinite) - Mark the forbidden spots with colliders and test against them with OnTriggerEnter
Hello, where I can find some good examples about game architecture in Unity. Like MVC, ECS, MVVM sample projects
Unity has a bunch of sample game tutorials which you can load up and tear apart if you want to do that. You can find them on the asset store or their githubs.
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.
Displacement of vertices along their normals?
That could work, I'd need to generate the mesh twice though I think, since I'd need to have the mesh to have the normals
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!
You could do it all in a shader if it’s a slight enough visual effect
Probably, but I'm quite bad at shaders. I suppose I could probably figure something like this out though
It’s trivial with shadergraph/ASE
So just Normal node times some value plus Position node to the Vertex input node?
Basically yes, it doesn’t work with hard edges though as they are effectively made from separate vertices with different normals
Hm, it separates the corners. I might need to add new faces between the corners?
Either smooth the edges or calculate a 2nd set of smoothed normals associated with each vertex for the shader to use. You‘ll have to do this for displacement through modifying the actual mesh too.
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
Are you trying to set the first submesh triangles?
or the second
your code is setting the second right now
0 = first
1 = second
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)
with DOTween, for a start i'd just copy a reaction-animation i like from an existing game and recreate it
Cinemachine has impulse if you wanna use it https://docs.unity3d.com/Packages/com.unity.cinemachine@2.3/manual/CinemachineImpulse.html
is it complex
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.
what's the reason for the vertex displacement shader?
I need the visible area to be slightly larger than the actual polygon
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
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
```?
It's a 2D Polygon with a height, so it's essentially a series of squares
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
012 seems right.
231 seems backwards
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
Oh, you're right, I misread my own code, it's 213
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'
This all makes sense, and it's what I thought I was doing. Maybe the implementation itself is the problem after all?
http://pastie.org/p/7mv9Fcm4BYC0UguaeLq2BI
quick question, what does ' denote here?
The vertex of that index from the previous iteration
thought so, thanks
you want 03'1 not 013' no?
Do I? I do, don't I? Let me try that
Oh, I am doing that I just typed it wrong again
Gah I can't keep all these indices straight
I just noticed that 2'3'0 is clockwise and 013' is counter clockwise
ah alright lol
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
I think you want 2'3'0 , 012, 230+ right?
sorry I skipped you and osmal's discussion
there are many ways to skin the cat yeah
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
do you ever call mesh.RecalculateNormals?
I do, after all this is done.
Should I not be?
you should, just checking
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.
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
That sounds handy, where is that setting?
Wireframes make sense, shading does not
Maybe it's the shader? It worked fine on a normal rectangle, but it breaks badly when I add in these extra points. Here's me dialing up the "inflate" from 0:
https://streamable.com/eotqxz
Seems the normals are very wrong
interesting that the right side seems to be moving what I assume is correctly, but everything else is twisting
Yeah, but there's still no face between the front and back and the right side, so something's gone wrong with that as well
is it intentional that you're throwing out all of the original triangles from the mesh? I'm not 100% sure of the desired end point
It's a completely procedurally generated mesh, there aren't any original triangles
oh, so this isn't the 2nd pass of generating the mesh? It looks like it already has vertices that you're keeping
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
I think the missing face on the right side is probably the i=0 case. Still have to wrap around and add that in at the end, right?
Right, but that would only be affecting one of the corners, not both. Still not sure why adding in these extra faces makes the normals go berserk
- If they have a question they should ask it
- That's not a very good question
- Probably doesn't belong in advanced
Editor script for adding gizmo / node to the scene inspector? I just need to grab positions.
Need to know the API functions.
Looks good, thank you!
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.
Tellusim Technologies Inc. Mesh Shader Emulation
How could I get the world position of a sprite vertex that's got a sprite skin component?
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]]
Well that's not valid json so you don't
thats just part of it
thats also just an example
Is there a way to change how its written to make it valid?
Yeah sure, { "example": [[1,2,3], [2,3,4], [5,6,7]] } something like this would be an array of int arrays
so like float[float[]]?
float[][]
I tried that before but it doesn't show up in the inspector
Yeah because unity doesn't serialize it
But I'm guessing you can still use it?
If you want to assign values in the inspector no, otherwise yeah
also sorry I was meant to write it as { "example": [[1,2,3], [2,3,4], [5,6,7]] } like you did but I wrote it wrong
No worries, it's just hard to say whether it's failing because of the invalid syntax or because of the data type
also since I can't use it in the inspector which is what I usually do, how do I add to it in code?
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?
Posting the same issue in multiple channels is considered Cross-Posting, and is against the rules.
Within C# scripts, does byte endianness differ between platforms? We're targeting Desktop, Android and iOS?
When doing what?
I tried the float[][] method but I doesn't seem to be working
Show code
Unity's JSONUtility doesn't support naked arrays like this so it's not going to work with JSONUtility
Nor can Unity serialize jagged arrays
This should go to #archived-code-general
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.
Yes it can be different.
WebGL: The sample data of audio clips is loaded asynchronously in the WebGL platform. This makes it necessary to check the loadState of an AudioClip before reading the sample data.
Yea, I do that. Also, I do get sample data. It's not like its returning just 0s
then i don't htink there is more to this story. you will have to write a ticket to unity
Alright, thx!
Does any one know how to compile the libvips library for android platform? https://github.com/libvips/libvips I want to use it for shrinking downloaded images before showing them. Thanks in advance!
you probably want to use a jar from maven that has it embedded
can someone advanced help me make third person movement fix? in dm
Don't post the same message in multiple channels.
No DMs here. If you need a collaborator make a request on the Forums.
Ask your question directly in the relevant channel (ie. probably not here), and provide the required information as per the rules in #854851968446365696
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
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?
I have a small question
i have 2 scripts
both in different Assembly Definition
how can i reference from script A to Script B
?
This is for sure not advanced code , #💻┃code-beginner
yea its advanced
BECAUSE AM NOT NORMALLY REFERENCING 2 SCRIPTS
EACH SCRIPT IN DIFFRENT ASSEMBLY DIFINITION
SO I CANT REFERENCE IT
You better fix your caps
@cosmic tendon
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
try updating to the latest VS package in Unity
It’s not advanced, literally adding an assembly reference to your assembly definition. Everyone reference a class in other assembly all the time.
Do I have to ask for permission in order for another PC to have voice recognition enabled on their end
Windows? Don't think so. though you should have it written in the terms of service that it requires microphone.
well this is a trip down memory lane
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
Thanks. I will give it a try and see if it works out.
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.
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.
Ugh. How do I stop XR from initializing?!
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?
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)
How about making your own manager to manage all the script?
class MyScript: Monobehaviour {
void MyAwake();
void MyStart();
void MyUpdate();
...
}
class MyScriptOrderManager: Monobehaviour {
List<MyScript> OrderedScripts;
Awake(){
foreach(var script in OrderedScripts){
script.MyAwake();
}
}
...
}
Wait what why?
I ended up doing something like this, to have better control over the scripts.
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.
Well yes
Script execution isn't in a set order
Execution order of methods are
You can add scripts to be invoked earlier in settings
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?
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?
This is really funny
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.
Actually a P2P solution would probably be just fine...
To all Jetbrains Rider developers, please upvote this issue, since you might come across to it soon or later:
https://youtrack.jetbrains.com/issu...aks-and-game-freezes-for-IL2CPP-on-iOS-device
Upvoting just takes a second and someday you might come across this bug, thanks for your help
that link doesn't work it has ellipses where it should have the rest of the link
Can Rider debug IL2CPP compiled code?
don't overthink it.
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
all of the SceneManager.GetScene methods only work for currently loaded scenes
If the scene is not loaded you'll get an invalid Scene struct
which can you check if it's valid/invalid with https://docs.unity3d.com/ScriptReference/SceneManagement.Scene.IsValid.html
ok thanks
Without loading the scene you can use this https://docs.unity3d.com/ScriptReference/SceneManagement.SceneUtility.GetScenePathByBuildIndex.html
is there any kind of way i can do to avoid this and just get the name from int ?
thanks
*moved to #archived-code-general *
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?
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)? 😅
looks like there is some recursion in the API, i've never seen a generic fluent API that has nice type info in tooltips and error messages
😱
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..
The entirety of LINQ is extension methods so yep, it'll lighten this monstrosity
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
I would guess everything is serialized anyway for the inspector debug view
If for no other reason
yep, private variables can be serialized in the editor when scripts are reloaded
That actually makes sense, haven’t thought of the debug inspector
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 😄
The constructors are actually also called on the prefabs when scripts are reloaded
yes, you're seeing behavior specific to the editor. See "hot reloading" https://docs.unity3d.com/Manual/script-Serialization.html
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
Haven’t tested the values. My concern was about the constructor call, which were breaking something in my game
add [NonSerialized] to the private field, counter-intuitive as it seems
Yeah that fixes it, but a bit weird 😅
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
Its probably because of that. Maybe they should've stated that it works different in editor 😄
They probably just mean persistent serialization
I have just tested it and it actually persists 😅
So I guess there is really no point of [SerializeField] other than make the private field visible in inspector
Yea it probably will in memory, but you won't see them written to the files used in builds and the values thus likely won't survive editor reboots.
You are right, It doesn't serialize it to a file. Thanks for the clarification
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?
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...
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:
Check: does elementID.normalColor compile? If not, then it's normal the second log logs null, it's not there on that type
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.
Yes, this is what it looks like, I pass this:
buttonComponent.onClick.AddListener (() => {
(outputCode.FindObjectOfType (typeof (outputCode)) as outputCode).onElementClicked (this);
});
You sure .normalColor is a property, not a field?
It's a property
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Here's the full class
Line 90 is where I detect click event and pass this
elementID.normalColor does compile yes
That looks like a field
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?
Hmmmm okay, how so I access the field ?
Also I hope the class you're deriving from uiElement isn't a MonoBehaviour nor derives from one
.GetField(string)
Yea uiElement isn't MonoBehaviour
Oh it worked thanks alot. Need to learn the difference between field and property.
hey can anyone help me solve the this issue
the cubes need to instanciate exactly at the cube's position and scale
a destruction voxel system
Looks like an offset issue, the new cube's center looks like it's at one of the old cube's vertices
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
not working
You'll have to be more explicit than this
You dared posting in #archived-code-advanced be ready to suffer the consequences
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
the cubes will spawn the same, it dose not matter the size
(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
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
wait, the problem is with the small cubes, the size is double the originals cube
haha the more I look at the code the worse it gets
Like I just saw .gameObject.GetComponent<Transform>()
aaa, i think when i blackout i do some strange shit
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? 😓
imma clean that out
Creating asmdef is pretty much standard thing to do, how many are there and what is your problem?
I'm making a package, if I add asmdef, then everyone consuming my package needs to add their own asmdefs that reference mine, right?
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?
or is there perhaps some kind of way to do this by creating child pipe pieces? i apologize if this question is a little bit too theoretical but i'm just thinking that i'm making this much harder on myself than i need to.
So what you want is like, draw a pipe form left to right and then top to bottom, they intersect in the middle and if you throw some water in whatever of the 4 openings, it shoould exit the other 3?
Not sure, what you mean? Can you explain a bit?
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"
Okay, and you want to match like exit pipe and new entry pipe, if they fit, flow water
You cant modify an array while iterating through it
Thats why its being copied
yeah, if they have connecting pipes between them, i want them to be considered 'connected', and therefore point A (entry) starts transferring to point B (exit). the connecting pipes don't have to have logic for gameplay
So you actually want to do pathfinding for pipes
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
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?
if i'm understanding you, yeah. assuming we've got 1 full pipe coming from each direction, i want adding a pipe piece to intersect them to make them all a single full pipe, and removing it to reverse that
or if the top piece was just an exit, then all 3 of the intakes would then be connected to the exit
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
i think that's probably the best way to do creating the pipes in the first place.. the issue would be if i remove a piece how to handle the logic of reassigning it given the new state of the overall map
err, reassigning which pipes were connected etc
yeah, if its like 2d, you would have a matrix of 3x3 to check on creation of one tile for example
the pipe tiles are currently on a tilemap like the terrain but it wouldn't necessarily have to be just Tilemap tiles, it could be painted gameobjects if that would matter.. here's what the early prototype looks like
err, when i say painted i just mean added to grid
Yeah, I got you 😄
I would get the pipe position on your grid and then update it depending on its neighbours
hm. i'll have to think about it bc they'd all be part of the same 'full pipe' before the intersection is destroyed so looking at neighbors would just tell it the same thing
like if i told the detroyed pipe neighbors to look at their neighbors, all of them would say "yep we're pipe X"
can you give me an idea of what type of pathfinding might be appropriate for this type of situation? i can try looking at some tutorials and see if that can apply. i def appreciate you taking the time to spitball this though i am basically just hoping to find a silver bullet lmao.
I think, iterating through the tiles and update them depending on their neighbours will not break your performance to be honest
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.
yeah especially if it happens just frame by frame
I guess it will not even be called every frame.
But I dont know the mechanic he tries to implement in gameplay
you would tell them to update their neighbors
nope i would only really need this to happen at start and then each time a connecting pipe type tile is added or removed. thanks for your help too. i think i have something to work with here 🙂
oh i see now, I was thinking some kind of cellular automata. Good luck 😁
my water tiles are sorta doing that actually, which is why i'm kinda iffy on adding more performance heavy stuff. i need to figure out a manner of making the water tiles settle after a time, but that's a whole other topic xD
take a look at the docs, see what Auto-referenced means
will do!!!
You do. I think that would be something you need to bear with, same workflow as you need to reference TMP or Cinemachine, etc
Unless you build them into dll that is, but it won't be easy if you have Unity references from your assembly
got it, makes sense. I might use some awful hack like on build start move the folder somewhere else
You can also use assembly definition reference asset, if that helps
appreciate all the help 🙏🙏🙏
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?
Any code example? Generally you don't have to worry about having your data cached on memory, unless it's loaded asset (texture or video, etc)
I'll show a sample, one moment
Oh that looks kinda odd in Discord, actually hang on
You can use triple ` to format code, more info on #854851968446365696
Suppose that's true, could set that aside into a method
Yeah other things like reference, names or some variables, that's not going to take much