#archived-code-advanced
1 messages · Page 68 of 1
yeah after turned back on and off
Check the animator documentation. There's a property called keepAnimatorStateOnDisable.
but that would mean they are at diffarent points as they come back on a diffarent times no?
I would say have a static variable they all reference when the turn back on
alright what about animator if i call animator.play?
will it update accordingly and predict future ahead?
Another thing
why it says gameobject but not component?
Controls the behaviour of the Animator component when a GameObject is disabled.
Set to true to keep the current state of the Animator controller.
Set to false to clear the current state of the Animator controller.
The default value is false.```
how animator will work even then?
getting this odd error when I swear that currently I'm not ever touching the indices nor the vertices:
https://hastebin.com/share/gabetegomo.csharp (my code is 32 characters too long for discord... sorry)
I swear that my code in its current form should just create a blank mesh with all 6 indices set to 0 and all 4 vertices being the default of my Vertex struct..... As such I'm very confused on how I'm getting this error.... Am I making a mistake somewhere?
Those native vertices/indices buffers are probably not initialized.
ah thanks I'll try using the unsafe utilities to wipe the memory and hopefully that should fix it then, thanks!
Animator.Play just causes the animator to transition to the specified animation state. It is still part of it's state.
Not sure what you mean by predicting the future. I'm afraid that kind of technology does not exist yet.😅
Is for why it says GameObject, but not component, I don't know, but it's probably the same in this context.
When the game object is disabled it's the same as if the component is disabled, so it wouldn't work(update) in that state.
what will happen. Will it detect the transition change even? By predicting future i mean i turned off animator then turn it back on again after 10 minutes. Will everything be same or what?
Everything would be the same as before you disabled it.
Theoretically
It will not update when it's disabled, so it wouldn't detect anything.
so basically its useless? Ugh... Would be tricky to do that myself.
What would you guys say the duties expected from a junior developer role are?
(I'm writing up a team member to recommend promotion, and need to say how he's been meeting or exceeded requirements of his current role.)
hi guys, just testing a basic scene transition with networking
ive set up everything correctly i think but i get this error
NullReferenceException: Object reference not set to an instance of an object
NetworkLobbyManager.StartGame () (at Assets/Scripts/Lobby/NetworkLobbyManager.cs:297)
LobbyUI+<>c.<Awake>b__10_1 () (at Assets/Scripts/Lobby/LobbyUI.cs:32)
UnityEngine.Events.InvokableCall.Invoke () (at <4746c126b0b54f3b834845974d1a9190>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <4746c126b0b54f3b834845974d1a9190>:0)
...
public void StartGame()
{
if (!IsLobbyHost()) { return; }
try
{
Debug.Log("Starting game");
NetworkManager.Singleton.SceneManager.LoadScene("BattleArenaScene", LoadSceneMode.Single);
}
catch (LobbyServiceException e)
{
Debug.Log(e);
}
}
which makes me think it cant find the scene.. but my understanding is you just give it a string it and finds it?
Guessing NetworkManager sets it's singleton in Awake and your code executes before that
Ah, perfect, thanks!
Mmm, the problem is that my native array already comes from mesh data
I guess set data will be it
He should be performing in, or acting as if in the target role already before he is promoted.
He is.
I need to describe how he's meeting the requirements... and there's not yet a formal list of responsibilities.
So I need to write that up. And then say how he meets them.
The requirements of the previous role should not factor in it, imo. If the target is not specified there is no argument for a promotion
maybe specify what he’s capable of and use that as a target and argument for creating a better role for him.
Um, OK.
But we've got a parent company and a process for recommending the promotion, which requires them to be meeting or exceeding requirements for their current role.
Nothing about the future role.
🤷 so I need to follow the process.
I do get to decide the requirements and responsibilities of the current and future role, though. Because those aren't defined (because we're growing fast)
ic so it’s sort of a staging for potential promotion
I’d say look at common expectations of a mid level developer (mainly autonomy in problem solving and accurate problem/solution fit)
Fortunately I don't need to create a new role. Developers can stay in a "developer" role and be promoted from junior through to senior.
Don't even have to move him to a new team. I can just say "he's working at a higher level and deserves a promotion"
(So yay, that makes it easier for everyone!)
Senior if they can eloquently talk about their work, solve complex hard problems and can basically solve anything in their general space for themselves and guide others towards solutions.
Yep. When I think he should be promoted I can put the recommendation forward.
I don't imagine it'll be rejected.
It's just weird this first time because we don't have the job requirements written out for the different levels. That's what I'm doing now.
Great opportunity to shape the future
It’s hard to clearly draw these boundaries
What's REALLY cool is I can also recommend someone for a pay increase WITHOUT a promotion.
Because your job title shouldn't be == your pay == how much we value you.
But making metrics/expectations clear helps everyone focus on the right things
Also consider that senior is not the end. You should also provision for more advanced roles that have multi-team impact that aren’t management
You want a role with lots of impact for someone who can successfully negotiate between the most gnarled conflicting requirements and convince everyone how to solve them in a simple way.
We'd consider that to be a technical senior
Seniors should have their areas where they have deeper knowledge.
A technical senior could focus on that area instead of project management or leading teams.
And those technical areas don't necessarily have to be programming. Could be working with clients, animation etc.
(But usually it'd be programming, since they're developers. Otherwise they'd be a senior artist or project manager or something.
But there's value to having cross-discipline people)
i tested that and thats not the case cause startgame is a command i run after the game has started
Is your scene in the build list? It has to be for this
yeah its in the build list
I'm creating random Mesh at runtime and computed the bounds and give them almost accurate BoxColliders,
and now I need to be able to drag & drop & throw them, but the problem is their pivots are all starting from the corner,
so using ScreenToWorld(clickPos) will move them but there will be a annoying offset and the result will also be different based on its rotation
any ideas?
I'm thinking about giving all of them a empty offset parent, but all the Meshes will be affected by Phyx as well
Hi, I'm having some problems with my GUI: I'm trying to show in the inspector only some fields based on the value of an enum. The only problem is that when I have to draw the GUI for an array of custom classes the element is drawn twice.
The code of the property drawer is this: https://pastebin.com/hTHDJQZh
And this is the code of the property that im trying to draw: https://pastebin.com/VtxtgHZ3
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
This is how it looks in the inspector
The problem is in the Steps list, which is a List<QuestStep>
Guessing that since you iterate over all properties, you draw the list then you iterate over all list elements and draw each again
Thats pretty much right but I dont know how to avoid going over both the list and the elements
Where should I use it? I have the OnGUI override, the GetPropertyHeight override and a function to check if I want to show the field
Any ideas why a Scan and compact algorithm is way faster at reducing the size of a compute buffer, than doing it with an AppendComputeBuffer?
Append has to use atomic operations, which are slow if you have a lot of threads competing to write to the buffer.
So it could make sense
Dont know if this is the place to ask
is there a way with unity ik to make it so it always grabs a point even if it means stretching
for example a character always holds the railing even if he is 100m away from it
stercthing the arms mesh?
like in a bad way or like pointing to it
is someone here familliar with ANTLR?
yeah
i mean if i tell it to grab something and its out of reach, i want the shoulder to stretch just so it can grab it
After writing a grammar in g4 and putting it into my Output Folder, there is no BaseVisitor File created after compiling with ANTLR, which i need. I am running
java org.antlr.v4.Tool -o -visitor -listener -o "Output Directory" -Dlanguage=CSharp "Input File.g4"
in the command line, and only the files on the image are being created.
i already tried upgrading ANTLR, but that gave no solution.
ive resolved it, i dont see why there was a "-o" before "-visitor"
Hello, can anyone explain please why this happens:
If I create a new 2d empty project and just put in it a square with this code:
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
[SerializeField] private float MovementSpeed = 5;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
}
void FixedUpdate()
{
rb.velocity = new Vector2(-MovementSpeed, rb.velocity.y);
}
}```
The square doesn't have a smooth movement, it actually feels a bit jittery/laggy.
Can anyone explain why this happens or how can I fix this?
Turn on interpolation on your Rigidbody2D
This is also not an advanced coding topic
You were also already helped in the beginner channel: #💻┃code-beginner message
Interpolation makes it much worse, it makes the game really laggy
you're doing something wrong then
Well how do I understand what I am doing wrong?
Go to the appropriate channel ( #💻┃code-beginner or #⚛️┃physics ) and start showing screenshots of your setup and your code and the behavior you're seeing
I'm trying to run this code
void LoopAddCopy<TComponent>(
Dictionary<string, GameObject> sourceObjects,
Dictionary<string, GameObject> destObjects
) {
foreach((var name, var sourceGo) in sourceObjects) {
var sourceComp = sourceGo.GetComponent<TComponent>();
if (sourceComp == null) continue;
var dest = destObjects[name];
TComponent destComp = dest.GetComponent<TComponent>();
if (name == "Hips") Debug.Log($"what is dest comp?: {destComp}");
if (destComp == null) {
} else {
if (name == "Hips") Debug.Log($"not null {destComp}");
}
if (name == "Hips") { Debug.Log($"(hips){name} {sourceComp} -> {destComp}");
}
CopyComponent(sourceComp, destComp);
}
}
and I'm getting a log not null null
As if the destComp == null comparison fails, but when I try to log what it actually is it's logged as a null?
(I should put more effort into connecting a debugger, but I'm on osx+vscode and ran into problems, so stuck with logs for now)
if (name == "Hips") Debug.Log($"not null {destComp}");
so name is Hips and destComp is null
so this
TComponent destComp = dest.GetComponent<TComponent>();
failed
yes, but it's logged inside if (destComp == null) { } else { so how can it be null and fail destComp == null?
I changed it to:
if (destComp == null) {
Debug.Log("never logs");
} else {
if (name == "Hips") Debug.Log($"not null {destComp}");
}
and never logs is never logged
try
TComponent destComp = dest.GetComponent<TComponent>();
Debug.Log($"{destComp} {destComp.GetType()}");
Ah it's probably because of the fact that TComponent is not constrained, so comparing it with == does not check for Unity's object lifetime stuff (destroyed but not null yet) state.
You might want to constrain that type parameter where TComponent : Component
hmmm... I also tried this:
void LoopAddCopy<TComponent>(
Dictionary<string, GameObject> sourceObjects,
Dictionary<string, GameObject> destObjects
) {
foreach((var name, var sourceGo) in sourceObjects) {
var sourceComp = sourceGo.GetComponent<TComponent>();
if (sourceComp == null) continue;
var dest = destObjects[name];
CopyComponent(sourceComp, dest);
}
}
void CopyComponent<TComponent>(TComponent src, GameObject dst) {
Debug.Log("generic");
}
void CopyComponent(Rigidbody src, GameObject dstGo) {
Debug.Log("concrete");
Rigidbody dst = dstGo.GetComponent<Rigidbody>();
if (dst == null) {
dstGo.AddComponent<Rigidbody>();
}
}
this doesn't work either because only the generic variant gets called... :/
I thought the concrete implemention would be preferred
@fresh salmon sorry new, to csharp, where to I put this constraint on the LoopAddCopy declaration ? TComponent:Component?
After the method arguments
void Sample<T>(string s) where T : Component
{
}
(will try to go back to the original question and see if this fixes the destComp comparison, but in the mean time is there a way to get rid of this error?
cannot convert from 'TComponent' to 'UnityEngine.Rigidbody' [Assembly-CSharp]cshar
(this comes up on CopyComponent(sourceComp, dest); if I don't provide a generic definition, and only provide concrete ones for CopyComponent (but if I do , then only the generic one gets called)
@fresh salmon with the constraint the destComp == null works correctly! (any thing I can google to explain why? : )
It's because when the type is not constrained, it'll choose the most general implementation for ==. But as Unity overrides == on its objects to account for the destroyed state (== null will be true if the object is destroyed, but has not been freed in memory yet), having no constraint short-circuits that
hmmm... I don't think I have a destroyed component there... but I guess the explanation is still valid!
GetComponent might not return null for a component that wasn't found, after all
Maybe you get a fake-null, that passes == null checks
I'm actually back to the second problem now, even if I can add the components in a loop, I can't call an overloaded method?
the whole point of this excercise I was trying to abstract away the looping and matching armature game object and have custom functions for copying components... but it just seems impossible
(https://stackoverflow.com/questions/19491928/how-to-call-a-method-overload-based-on-closed-generic-type turns out it doesn't work like I thought it would in csharp)
C# generics are quite different from C++ templates.
One option is passing Action<TComponent, TComponent> copyComponent as parameter then call that function.
Other option is just using Component class than downcast to specific classes
Ah that's a nice idea! I'll try that when I confirm I can get it working with the many ifs
How do you mean use a component class that downcast?
Have you implemented chunk generation using job system in a voxel game?
My problem is when same chunk should be updated while the previous one is not completed yet.
I have created a dictionary with chunk index as a key and a list of chunk requests which should be updated.
Different chunks are regenerated independently but same chunks are regenerated by order sequentially.
Is it OK?
Requests, for example first chunk 1 changes, then chunk 4, then again chunk 1,..
If they run sequentially it will be completely OK but I want to utilize paralisim
Such as..
void CopyComponent(Component src, Component dst)
{
switch (src, dst)
{
case (Rigidbody srcRigidbody, Rigidbody dstRigidbody):
// do something...
}
}
Of course not that pretty so I'd prefer just passing Action
Need to try this, cause judging from the other errors I've been getting I'm half expecting for the action approach to not work either. Will a copycomponent(rigidbody a, rigidbody b) work as an action of tcomponent type? Won't it just tell me it can't cast from tcomponent to rigidbody?
As long as you are calling it with TComponent as Rigidbody then it should work (i.e. LoopAddCopy<Rigidbody>(..))
Hello, I need some help on calculating my procedural mesh normals, I have no idea on how to do it
I have used some code chat gpt provided but it does not look correct, it looks like it is still missing something important so I always see a part of the mesh with correct normals while the other side is completly white
Here is an example
This is what I am using for calculating normals (I am using mesh data API)
for (ushort i = 0; i < meshData.Length; i++)
{
meshData[i] = new VertexData
{
Position = vertices[i],
Normal = CalculateNormals(i),
};
}
SetTriangles(faceCount);
}
float3 CalculateNormals (int vertexIndex)
{
float3 vertexNormal = float3.zero;
// Calculate the face normals and add them to the corresponding vertices
for (int i = 0; i < triangles.Length; i += 3)
{
int vertIndexA = triangles[i];
int vertIndexB = triangles[i + 1];
int vertIndexC = triangles[i + 2];
float3 vA = vertices[vertIndexA];
float3 vB = vertices[vertIndexB];
float3 vC = vertices[vertIndexC];
float3 faceNormal = math.cross(vB - vA, vC - vB);
if (vertIndexA == vertexIndex || vertIndexB == vertexIndex || vertIndexC == vertexIndex)
{
vertexNormal += faceNormal;
}
}
// Normalize the vertex normal
return math.normalize(vertexNormal);
}
The reason of why I need to calculate normals by hand is because my own vertex attributes won't apply if I do so, If I happen to use mesh.recalculateNormals, the model looks as expected but just my vertex attributes would be overriden by the Unity default vertex attributes
Great! Thankyou, passing my overloaded method as an action worked. In combination with the TComponent : Component constraint it's finally looking like I wanted it (almost 🙂
void LoopAddCopy<TComponent>(
Dictionary<string, GameObject> sourceObjects,
Dictionary<string, GameObject> destObjects,
Action<TComponent, TComponent> operation
) where TComponent : Component {
foreach((var name, var sourceGo) in sourceObjects) {
TComponent sourceComp = sourceGo.GetComponent<TComponent>();
if (sourceComp == null) continue;
var dest = destObjects[name];
TComponent dst = dest.GetComponent<TComponent>();
if (dst == null) dest.AddComponent<TComponent>();
dst = dest.GetComponent<TComponent>();
operation(sourceComp, dst);
}
}
void CopyComponent(Rigidbody src, Rigidbody dst) {
}
void CopyComponent(BoxCollider src, BoxCollider dst) {
dst.center = src.center;
dst.size = src.size;
}
void CopyComponent(SphereCollider src, SphereCollider dst) {
dst.center = src.center;
dst.radius = src.radius;
}
void CopyComponent(CapsuleCollider src, CapsuleCollider dst) {
dst.center = src.center;
dst.radius = src.radius;
dst.height = src.height;
dst.direction = src.direction;
}
(I didn't want to explicitly copy the component configs, but just have it happen magically, I saw some Editor methods to copy component values, but this is close enough!) Thank you again!
Maybe I just havent' spent enough time searching but could someone point me in the right direction for finding a specific object in a scene using the UnityEditor code? It's code that won't need to be in builds it's more for helping build the maps properly.
Example for how it's used:
SceneA is transitioning to SceneB
SceneA has GameObject1
SceneB has GameObject2
When GameObject3 touches GameObject1, GameObject3 moves to GameObject2's position in SceneB.
The code for this is already functional, I just want to code a way to verify that this connection exists and that the object can be found (In Editor) so that there aren't problems in builds
If it is using UnityEditor then it would fail to build
EditorSceneManager
get scenes, use GetRootGameObjects()
use GetComponent on those
I'm currently having a weird issue that may just be super simple to solve but my brain cannot figure it out for the life of me (also please tell me if this is the wrong channel and I'll move the message to the correct channel).
I've stemmed off of the Sebastian Lague tutorial for perlin-noise based procedural landmass generation and currently have the noise being generated onto a 2D plane (think end of 4th episode, maybe a tad further).
My current noise function is as follows:
public enum NormalizeMode {Local, Global};
public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, int seed, float scale, float zoom, int octaves, float persistance, float lacunarity, Vector2 offset, NormalizeMode normalizeMode) {
float[,] noiseMap = new float[mapWidth,mapHeight];
System.Random prng = new System.Random (seed);
Vector2[] octaveOffsets = new Vector2[octaves];
float maxPossibleHeight = 0;
float amplitude = 1;
float frequency = 1;
for (int i = 0; i < octaves; i++) {
float offsetX = prng.Next (-100000, 100000) + offset.x;
float offsetY = prng.Next (-100000, 100000) - offset.y;
octaveOffsets [i] = new Vector2 (offsetX, offsetY);
maxPossibleHeight += amplitude;
amplitude *= persistance;
}```
scale = 0.0001f;
}
float maxLocalNoiseHeight = float.MinValue;
float minLocalNoiseHeight = float.MaxValue;
float halfWidth = mapWidth / 2f;
float halfHeight = mapHeight / 2f;
for (int y = 0; y < mapHeight; y++) {
for (int x = 0; x < mapWidth; x++) {
amplitude = 1;
frequency = 1;
float noiseHeight = 0;
for (int i = 0; i < octaves; i++) {
float sampleX = (x-halfWidth + octaveOffsets[i].x) / scale * frequency;
float sampleY = (y-halfHeight + octaveOffsets[i].y) / scale * frequency;
float perlinValue = Mathf.PerlinNoise (sampleX, sampleY) * 2 - 1;
noiseHeight += (perlinValue * amplitude) / zoom;
amplitude *= persistance;
frequency *= lacunarity;
}
if (noiseHeight > maxLocalNoiseHeight) {
maxLocalNoiseHeight = noiseHeight;
} else if (noiseHeight < minLocalNoiseHeight) {
minLocalNoiseHeight = noiseHeight;
}
noiseMap [x, y] = noiseHeight;
}
}
for (int y = 0; y < mapHeight; y++) {
for (int x = 0; x < mapWidth; x++) {
if (normalizeMode == NormalizeMode.Local) {
noiseMap [x, y] = Mathf.InverseLerp (minLocalNoiseHeight, maxLocalNoiseHeight, noiseMap [x, y]);
} else {
float normalizedHeight = (noiseMap [x, y] + 1) / (maxPossibleHeight/0.9f);
noiseMap [x, y] = Mathf.Clamp(normalizedHeight,0, int.MaxValue);
}
}
}
return noiseMap;
}
}```
The issue I am trying to solve is having the "zoom" parameter zoom inwards towards the centre of the screen adjusting to match the zoomed out image. Trying to achieve this with an increased Noise Scale variable changes the shape of the terrain, which is something I'm trying to avoid.
The final product I'm looking for would be the ability to increase the zoom function and have the pixel ratio stay the same as it zooms (ie. stay within a 256 x 256 grid), however no matter what I have tried I can't seem to make it zoom towards the centre of the screen, It will always either do one or both of:
a) Move the whole function in a direction, leading to the zoomed area being thousands of units away
b) Change the function completely, leading to a different piece of land being displayed upon zooming
Anybody know about this error?
i know its about some script that require to reference some thing, but i already assigned it into the script that needs it
You doing any custom editors
before i created an Editor folder but i already deleted it because i even didnt make any costum editor
the error shows after i create this script
Sounds lke a bug in your unity version
public class LevelScoreCounter : MonoBehaviour
{
public int targetScore = 100;
public float increaseSpeed = 10f;
[SerializeField] private TextMeshProUGUI textMeshPro;
private int currentScore;
private float currentDisplayScore;
private void Start()
{
currentScore = 0;
currentDisplayScore = 0f;
UpdateScoreText();
}
private void Update()
{
if (currentScore < targetScore)
{
currentDisplayScore += increaseSpeed * Time.deltaTime;
currentScore = Mathf.FloorToInt(currentDisplayScore);
UpdateScoreText();
}
}
private void UpdateScoreText()
{
textMeshPro.text = currentScore.ToString();
}
}
its an old version, 2021. 3. 9f1
Try updating to the latest 2021.3 patch version
Ooops silly me, it seems like the result was because i open two inspectors at the same time
im thinking on buying a new pc to fix it lol
Might work too 😄
But believe me, some library folders can mess up things a lot, so its a proven solution sometimes 😄
oh yeah sure, i was thingking about doing that. But need a little bit research before went onto that
Yeah thats like the bazooka of "fixing" if nothing else helps. More power to research for sure first 😄
Is it possible Raycast2D skip frames occasionally? I'm using Physics2D.Raycast against Collider2D in Update, and my problem shows in the screenshots
moved the logic to FixedUpdate but not working
the red and green line are debug rays, when ray hit collider character should stop. I moved my character horizontally from left to right, sometimes character get into the obstacle collider one step further, which is the problem I want to fix
rays are extended by speed factor?
Yes, ray start from character collider surface + a small skin width, and the length is character speed in this frame. Green ray means no collision detected
not sure whats going on there, most likely its your code
here's part of the code
Anybody here has experience with rect transform?
I want to do this on an Object wich has a Rect Transform Component:
transform.position = new Vector3(x,y, transform.position.z );
but x and y always end up as a completly different value
RectTransforms should be moved using anchoredPosition
Could you provide more detail or an example pls?
@devout hare thx that was it
How could I "shatter" a polygon into smaller pieces of itself, keeping the original texture?
Like this, but dynamically, with a decent range of control over the new poly count and spacing?
Easiest way is to just create two versions of the model, a whole version and broken version that has the various pieces separated out
Hardest way is to generate custom meshes to simulate the pieces
That makes sense - I was interested in the generate approach, but that may be overkill... Thank you!
Something like this?
https://www.youtube.com/watch?v=pe4_Dimk7v0
Tutorial video for my Open Source Unity tool for breaking sprites into fragments for destruction effects!!!
https://github.com/mjholtzem/Unity-2D-Destruction
http://forum.unity3d.com/threads/free-open-source-unity-2d-destruction.382416/
Yeah exactly that!! Thank you! I'll see if a 3D version exists!
Dynamically generated pieces will be a lot more GPU intensive, so keep that in mind if you have a setup where you will "break" a lot of objects
You won't get any of the benefits of GPU instancing
You can avoid lag by Pre-generating a couple of those broken models before the game starts
Hello! I am encountering a weird bug: I am trying to load a texture from the disk into a sprite, the texture being a picture taken from an Iphone, but when loading it with the following code, the width and height are inverted. But on some other picture it is not ? AM I missing an option ?
byte[] pngBytes = System.IO.File.ReadAllBytes(imgPath); Texture2D tex = new Texture2D(1,1); tex.LoadImage(pngBytes); Debug.Log("WIDTH " + tex.width + " HEIGHT " + tex.height + " " + imgPath);
And here is the picture in question
The problem is that photos from phones are always landscape, but the phone adds metadata into the image file that tells software that the image should be displayed with a 90° rotation. Clearly, Unity doesn't check for this metadata and just reads the raw data, which is the landscape image.
@sage radish Oh wow thank you so much!
I'm working on a little multiplayer game and I've got something working using Photon Fusion. The rotations on the player after the first isn't being stored correctly. Anyone here familiar with Photon Fusion and know what the problem might be?
#archived-networking
There's also a photon discord server which you'd probably find more discreet help
oh great! I couldn't find it before
I am wanting to move an object at 6 units per frame per 60 fps or (6 * 60). I am wanting to do this in fixed update which runs at 50fps. How can i make a function like Mathf.MoveTowards(velocity.x, top speed * 60, acceleration * 60). This function is like this because velocity is measured in velocity per second not per frame. How do i need to edit this function to have desired results? I am thinking I need to use Time.FixedDeltaTime.
Just to be clear, you want the object to move 6 * 60 = 360 units per second?
add 3 * 60 * Time.FixedDeltaTime to the velocity until it reaches 360
Mathf.MoveTowards(velocity.x, top speed * 60, acceleration * 60 * Time.FixedDeltaTime). So this is what i am wanting?
probably
Hey guys, does anyone know how can I simulate a muscle in real-time in unity?
Thanks for the hel
For example I want to contract the biceps in an arm, skinned meshes don't actually contract the biceps, is there a way i can achieve this feat?
You move the transform directly. Given that your mesh has a rig.
There are some github projects or assets that aproach this, but doing this by hand could get messy if you never coded procedural mesh stuff
I think the best place for asking this would be into Photon offcial discord, they are usually very active and likely you will get responses from a dev or an expert
Hello I want to learn scripting in unity but I don’t understand anything from YouTube tutorials
😦
Wrong channel.
Attend School, follow an online course or motivate yourself to actually learn something instead of just listening.
already there, thanks ;)
Do you know any articles which are similar to this and can help me in implementing it ? I have a rig with muscle meshes on it (they are separate meshes)
ok thanks for pointing me in the right way
Not sure what you mean. You move the transform associated with the SkinnedMesh.
Don't you mean that I change the underlying mesh data when the animation is performed?
No. The transform.
There is multiple transform that form the rigs. You move them.
Like an animation would do.
How would it perform a stretch and squishing animation? I want to perform it on a single muscle i.e. a single mesh. For example when your flex your hands your bicep actually moves inwards and when you relax your hand the muscle then moves outward / to normal position.
I want to simulate some kind of soft body mechanic over one single mesh for squishing them..
You would rig your mesh accordingly.
If you want to simulate soft body, this is not the right engine.
Unity is a Runtime engine.
Soft body simulation is usually done in other engine as it is not something that can be done fast enough to satistify runtime.
That being said, there is exception such as Cloth.
And some water system.
Can I move a bone on runtime using C# script?
yes
For example when the character's arm flexes i want to interpolate the location of the tail / head of a bone accordingly
You can
However, you should look into creating an animation or use Inverse Kinematic library.
I have Inverse kinematics on my body are you talking about activating such muscles using inverse kinematics too ?
rather than writing a script for doing the same?
I am currently switching from BinaryFormatter to Json(newtonsoft) for my save game system. Are there any other alternatives to BinaryFormatter that can serialize and deserialize with minimal manual mapping? I'm trying to make the system as flexible as possible, being able save/load with minimal configuration as possible. I'm using JSON and already I ran into some issues where properties that are classes with a collection of values(i.e HealthStat{Hp=5,MaxHp=10}) rather than Data types like int or string. I was able to find a converter that seems to be working and now they are deserializing as expected but would be nice to know if there are better alternatives to JSON.
Serializing classes within classes like that is no problem, as long as they are marked as [Serializable]
as long as it's different fileid and guid it's different gameobject and components right?
I have a Jagged Array for Images, but I cant see them in my Inspector to add the gameObjects to the array so the code knows where to put the pictures. How do i get the Jagged Array to show up in my Unity Inspector so i can move the Images into specific Array.
public Image[][] mPortraits = new Image[9][];
void Awake(){
for (int i = 0; i < 9; i++)
{
mPortraits[i] = new Image[10];
}
}```
Serializing nested collections
Unity cannot directly serialize nested collections.
Instead of directly serializing a collection inside of another, create a serializable type that you can nest your collection inside.
// 🔴 Will not serialize
public List<float[]> Values;
// 🟢 Will serialize
[System.Serializable]
public class ValuesWrapper
{
public float[] Values;
}
public List<ValuesWrapper> Values;
(I haven't added this to my troubleshooting site yet so it's a copy paste from the source 😉 )
You can't serialize jagged arrays either, so your choices are either nesting as above, or using ISerializationCallbackReceiver and serializing it manually into a flattened array
thank you, just trying to figure out how I am suppose to do this. I seem to be coding beyond my capabilities.
so i can do like
public class PortraitHolder
{
public Image[] mPort0 = new Image[10];
public Image[] mPort1 = new Image[10];
}
PortraitHolder portraitHolder = new PortraitHolder();
for (int i = 0; i <2; i++){
string fieldName = mPort + i;
Image[] currentArray = portraitHolder.fieldName
for(int j = 0; j<10;j++){
currentArray[j] = getSpriteCode();
}
}```
Have a wrapper for one of the dimensions of the jagged array like vertx suggested.
And just create an array of that type - the wrapper.
Literally just made this, very little testing done
should be able to do [SerializeField] private JaggedArray<Image> _images; and it should appear in the inspector and work as you would expect.
Thank you for the help, I used the Class with Arrays inside it and
this seems to be working for me.
Wait why on earth do you need to use reflection for this?
Is that some other unrelated part of your implementation
I dont know what I am doing! lol :
if(emptyMiningSlot != -1){
if(foundObject.Task == "Idle"){
MiningArea[SelectNumber][emptyMiningSlot] = foundObject;
string fieldName = "mPort" + SelectNumber;
Image[] currentArray = (Image[])typeof(PortraitHolder).GetField(fieldName).GetValue(portraitHolder);
SetMonsterPortrait(currentArray[emptyMiningSlot], foundObject.Name);
foundObject.Task = "Mining";
foundObject.nodeLocation = emptyMiningSlot;
foundObject.Location = nodeName[SelectNumber];
emptyMiningSlot = -1;
CheckForIdleMonsters();
}
}}```
i would have used a video but i dont know how to do that.
I don't understand why you're not just accessing the fields on portraitHolder
It would be way easier if you used my implementation #archived-code-advanced message
instead of declaring the indexed arrays manually
I'lll take a look, but I have 9 different areas and with this code it lets me use the int SelectNumber as a way to tell which area they player is trying to add the monster to.
solved, in case anyone want to know, you cannot query Collider2D.center in Update() because its value does not guarantee to update on time. Use transform position and collider offset instead
Update and FixedUpdate run at different rates, so the answer to your original question was yes if frame rate > physics rate
that's right
{
itemAmounts = new int[inventory.inventory.Count];
int iteration = 0;
foreach (var item in inventory.inventory)
{
if (inventory.inventory[iteration].itemData == null)
{
itemAmounts[iteration] = 0;
iteration++;
}
else if (inventory.inventory[iteration].itemData != null)
{
itemAmounts[iteration] = inventory.inventory[iteration].stackSize;
iteration++;
}
}
yield return null;
}```
``` private IEnumerator UpdateInventoryItemAmountsToDB(PlayerInventory inventory)
{
yield return UpdateInventoryItemAmounts(inventory);
try
{
DBreference.Child("users").Child(User.UserId).Child("InventoryItemAmounts").SetValueAsync(itemAmounts)
.ContinueWith(task =>
{
if (task.IsFaulted)
{
// Handle the error here, such as logging or displaying an error message.
Debug.LogError("Failed to update InventoryItemAmounts: " + task.Exception);
}
else if (task.IsCompleted)
{
// Handle the success case, if needed.
Debug.Log("InventoryItemAmounts updated successfully");
}
});
}
catch (Exception e)
{
// Handle any general exceptions that may occur.
Debug.LogError("An error occurred: " + e);
}
}```
Im trying to save data to firestore, but this is causing major memory leakage, ultimatly causing unity to crash
Use the profiler/memory profiler to see what is being allocated.
I want to move a camera in 3d world space to it's UI in 2d space how do I move and rotate according to it's Ui
Not sure what you mean. UI is directly render on the camera.
Just like this see in the first pic there is a 2d UI which is controlling the position and rotation of the world camera which is rendring it's output on render texture ig in the second pic
see in the first pic the UI of a video cam
so u mean like they are controlling the camera with the help of world space UI
icon
There is definitely no overlay UI there.
aight i didn't think it in that way i'll try by world spce UI thanks mate
{
if (axeReturn)
{
if (time < 1f)
{
axeThrow = true;
rbAxe.position = QuadraticBezierCurvePoint(time, oldPos, curvePoint.position, targetAxe.position);
rbAxe.rotation = Quaternion.Slerp(rbAxe.transform.rotation, targetAxe.rotation, 50 * Time.deltaTime);
time += Time.deltaTime;
}
else
{
ResetAxe();
}
}
}
[Command]
public void ReturnAxe() //AnimationEvent
{
RpcReturnAxe();
}
[ClientRpc]
void RpcReturnAxe()
{
rbAxe.gameObject.GetComponent<AxeController>().activated = true;
time = 0f;
oldPos = rbAxe.position;
rbAxe.velocity = Vector3.zero;
axeReturn = true;
rbAxe.useGravity = false;
rbAxe.isKinematic = false;
}
Mirror Multiplayer System
(Includes ax network transform.)
I couldn't sync the axe's return
Hey guys, Is there a way to properly rotate one characters bone transform to another (retargetting it?) I made a script which maps the rotation values for the bones however, the rotations seem to be off...
No automagical way with unity, unless retargeting with mecanim at runtime.
Even with external tools such as blender, Animation retargeting is tough and requires manual resolve at many points.
(moving this to #archived-networking)
#archived-networking
also there's a link to the unity multiplayer server pinned in that channel where a lot of people who use N4GO hang out.
as for testing, there's packages you can get like ParrelSync or unity's new Multiplayer Play Mode (this is only available in 2023.1+ though)
got it - I'll move there, thanks!
Hey so idk if anyone can help me but im working on a project that i have a inventory system (for a game so its not going to be attached to a specific avi) but I am trying to figure out what the code would be if I would want to push downwards or push upwards on the right joy stich and which than after a second or 2 the inventory (the one i have made) be enabled
So since my inventory is based on a interactable UI in unity im thinking that the code would be related to the UI coding and stating that if the foat value range is greater than or equal to 1 the menu will open and if not closes but idk if i have the right idea with this
if anyone has any articles or references that could help me or replying to me Id really appreciate it
This is not a code question but more of a #archived-game-design one.
Given that the implementation does not seem to be hard to make, I would suggest you do it then test it. You could also take reference in what is being done in other game as it is most of the time a good start.
yea id figure it be a code because of im trying to link the controler functions to a spawninable player (the box that is attached to each person that comes into the world)
This was not the nature of your question.
Is wave function collapse a good solution to creating randomized racetracks or no? I'm kind of on the fence about it because it could be used to only generate valid tracks, but it doesn't have to return to the same origin, considering its all random. It could very easily just go out of bounds and then it doesn't have to complete a circle
no
you can in theory if you find closest point to start and generate another one with hopes to hit it closer, iterate until you can carve a straight segment right through
and probably generating a racetrack with curve is something that need infinite state which is unsolvable
im assuming the wfc is used only as a guide for sampling
which can probably be done with noise and circling slopes or something like that
i was picturing something like trackmania hearing wfc
that does look interesting
basically my idea was, create one piece of track. considering it can only connect to other track pieces, it should connect to itself in the end
The easiest way to handle it is to start with a circle, and then apply distortions to that, rather than trying to start with a line like you're drawing on paper
bullet problem?
i like this solution the most
Has anyone tried the new Rigidbody2D.Slide method in 2023.1? I'm a big fan of Godot's built-in solution for 2D kinematic character controllers and I'm pleased to see a similar effort from Unity
I'm curious about Unity's implementation here -- Godot's CharacterBody2D works well enough but the code is a nightmare mess
Would love to see Rigidbody2D.Slide implemented on the C# end sometime
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
I have a question regarding MonoBehaviour in Authroing scripts or just Components, is it only needed to assign variables from the inspector?
Can you rephrase the question, I don’t get what you mean..
here, we're inheriting from monobehaviour
I know that bake will separate everything into entities, components etc
the question was regarding on why do we need MonoBehaviour, is it only to attach these components to Game Object in the editor?
In quantum ECS or ENTITAS you have a single script that can take components you wrote
so you don't have to use monobehaviour in every component or authroring scripts of yours
Oh you mean in DOTS. Surely you can make script with EntityManager if you want to generate entities runtime without GameObject?
And #1062393052863414313 might give you better answer
alright thank you for your time then!
https://codeshare.io/dwPMqZ
I am trying to do PCG, having tiles generate at a random gap, with tiles generating 50 ahead of the player, and my script wont work, I think it is line 59
You only need these authoring components and bakers for the editor, once your game has been build everything will be serialised into the scene instead
You need to inherit from monobehaviour in order to attach it to a game object
Although in runtime you can instantiate entities using EntityManager or an EntityCommandBuffer
Does anyone know how i can get avatar/profile picture from steam?
this is more #archived-networking related.
the answer really depends what you are using, but really this isnt hard. Facepunch and steamworks both list how to on their documentation
im using steamworks
you just plug in the steamID then (GetLargeFriendAvatar, GetMediumFriendAvatar, or GetSmallFriendAvatar)
https://partner.steamgames.com/doc/api/ISteamFriends
can you give me an example code?
there are definitely tutorials out there for this, its a common task. I also use facepunch which is slightly different
you'll have to convert the image to a texture or sprite, which is also definitely covered in tutorials
Yeah Facepunch's version is way better, it's actually real C#. The others are just wrappers around the C++, and it feels like you're doing C++ in C#
yeah but its too late to switch to facepunch ive already coded everything with steamworks
At least steamworks has uh some documentation. Facepunch is literally just a list of method names, it's a godsend if any method has a 1 sentence description
xd yeah
Most of what you'll do is in the repo's README anyway
public static Texture2D GetSteamImageAsTexture2D(int iImage) {
Texture2D ret = null;
uint ImageWidth;
uint ImageHeight;
bool bIsValid = SteamUtils.GetImageSize(iImage, out ImageWidth, out ImageHeight);
if (bIsValid) {
byte[] Image = new byte[ImageWidth * ImageHeight * 4];
bIsValid = SteamUtils.GetImageRGBA(iImage, Image, (int)(ImageWidth * ImageHeight * 4));
if (bIsValid) {
ret = new Texture2D((int)ImageWidth, (int)ImageHeight, TextureFormat.RGBA32, false, true);
ret.LoadRawTextureData(Image);
ret.Apply();
}
}
return ret;
}
would this work?
just found it on google but i dont know how to use it
Call it, pass the ID of the user to get the avatar, and it returns a Texture you can apply to some image
call ret?
What?
oh nvm u meant the method
Of course, reading the code should be self-explanatory enough
It's not the most complicated stuff that's in this method
theres a readme
hey. is it possible to change a local git commit's date and push it to origin? I want yesterday's local commit to appear as today's when pushing to origin
asking for a friend
Yes but this isnt really unity specific. Theres many tutorials on how to do this online
ah, is there a keyword for it to use to search for? because I didn't find anything
also, yeah it's not Unity specific, but I thought it's related to code-advanced topic. if not I'll gladly delete it
"Change git commit date"
I've only really seen friends do it for school to lie about submitting on time.. not sure why anyone would this otherwise tbh
answers are mostly manual time changing. I was sort of looking for a way that's designed specifically for this scenario: to update the timestamp to the push date
but yeah those workarounds do work fine
I mean there's no functionality for this
Sinec tehre's no real reason to do so
You did the work on day x and pushing jsut syncs taht work to the server
Building something to do it automatically is probably overkill. Would probably be easier just doing it manually this one time, and then changing how you commit for later times
Could even save the changed version and undo the commit if it's just like a file that was changed. I maybe wouldnt do this if it was like a scene change
this is faster than interactive rebase. good idea, thanks!
how do i get the id?
That's a good question
If you have a username then you somehow need to ask Steam to give you an ID from that, if that's even possible
The documentation surely has resources on that
to grab the texture as a image i need to pass a int iImage
and on the steamid its a type csteamid?
how do i convert it to int?
nvm i converted it to int and it still doesnt work
It's the CSteamID that you plug into the GetAvatar...() function.
Thatll return u an image ID which u use with steam utils I believe to get the data
Really itll just be easier if you find a guide which uses steamworks. Converting to int is just guessing
https://youtu.be/mEZMsRouIWo
Around 13 mins is where they start coding how to convert the image. Also im on mobile so I skimmed through with no noise
oh yeah thats the exact same code i have
shoutout to you bro
only problem i got is passing the image onto where the blue pen marks
btw that was the exact tutorial i was watching xd
i cant really pass it onto there
so what do i do?
hello, i change the rotation of my object from script but it seems to have one frame delay between the animation trigger and the rotation change, anyone have a solution for that?
animation changes first, transform rotation changes after, even tho they are called at the same time
Animation are played late in the frame. If you want to override the rotation of an animation you will need to use a callback that is after the animation. Something like LateUpdate (Not exactly sure if it will work with this particular callback).
You could also look at how the IK package work: https://learn.unity.com/tutorial/working-with-animation-rigging#6014ac53edbc2a0eea5c1d95.
If you are experiencing delay in your animation, you might want to study Animation Transition; Make sure that your transition has no exit time.
@dusty wigeon it doesnt, still doesnt matter it is an internal bug, i tried all possible combinations. Only fix was setting the sprites directly
best i could was 1 frame delay which caused a stutter
So, it is not about changing rotation isnt ?
nope. its another unity animator bug
...
Stop blaming Unity.
You do not even describe your issue and blamme it on the engine.
As far as I know, you might not even use it correctly.
the sprites do not get changed instantly when its set to, exittime 0 with any update conditions engine has
ive had worse when i set 15 animators trigger at the same time and they played out of sync by seconds.
not my first rodeo
If you are doing 2D sprite base animation, maybe the Animator is not suitable for your use case. I am pretty sure the Animation are threaded, thus it might be expected to have a frame delay between the trigger and the actual change. In most case, this should not be an issue or it could be mitigate by waiting for a frame before doing the actual behavior.
yeah. if i change it by scripts it works fine. but if i make the animator sprite renderer fully transparent and change it by script also, it still lags 1 frame
So, the issue is not the Animator ?
the animator somehow lags the script i have no idea why
Maybe the animator is running before the script.
Did you try to manipulate the Execution Order and use LateUpdate ?
if i make the animator fully transparent it lags one frame. if i remove it , it doesnt
So, the issue is on the SpriteRenderer not on the animator ?
It is kinda hard to follow what you are saying.
i do not understand how one makes an animator transparent
by making its sprite renderer transparent
adding a second sprite renderer
and changing the second sprite renderer by script
if animator is enable second sprite renderer still lags
to a different object
There is also the possibility to force the Animator to Update with Animator.Update.
animation updates normally happen between Update and LateUpdate.
letme try that
if i reference the spriterenderer connected to the animator at all. it will lag
weird af
i guess ill use two seperate scripts on two seperate objects
@dusty wigeon calling update helps a bit but doesnt fix it. thanks for your help tho
it lags less amount of frames
In unity, rotations work in a 360 full circle.. I am trying to determine when a rotation is greater than the last rotation, but this fails when the rotation resets. How can I solve this?
I'm not even sure this is the right place to ask, but I'm wondering if it is worth it to attempt to upload and market a Toolkit I'm working on. The goal is to provide allot of generic code that can be used to speed up development. The features I have mostly working so far are Generic Repositories for storing many of a single type. I've also started work on a SaveableObjects for things that need to be saved but only one or few in the game. Also code and logic for taking all those things and serializing them into Json string with optional encryption as well as deserializing them back into their types. I'm also thinking about taking a stab at creating a custom monobehaviour that will be able to handle registering/deregistering events automatically and a static ServiceLocator for registering and Locating Unity Singletons with Maybe another custom monobehavior class specifically for singletons that will include the unity singleton pattern in their base code. --Does this seem like something worth trying to sell or is the market oversaturated with this kind of asset?
Don't rely on the euler angles from the transform. Use your own float for the angle
Thank you.
If you are interesting in marketing tool, from a User stand point, I suggest that you
- Concentrate your effort in a single point. (Save or Event, but not both)
- Make things that are actually long to make or hard to make. (Save is pretty straight forward, Event are easily done)
- Consider extensively the interface of your tool. (The UI and the Code interface)
- Be sure to be able to add more value to your tool then what it already exists. (Performance, Flexibility, Usability, Price, etc.)
Also, consider that as an User, I am also a developer. I can easily do most of what you want to do. (And have done it several time) It is more a question of how much time it would take to make it. Thus, if you are not ready to invest a considerable amount of time in your tool, then you should not do this.
That being said, as an individual, it is really useful to have your own toolkit and you should definitely do it for your own benefit.
Anyone have experience setting button OnClick function arguments via script? I'm struggling a bit with it.
tried this in a function that passes the int:
dropItemButton.onClick.AddListener(delegate { dropInventoryItem(invSlotId);});
trying to select an inventory slot, and have the slot update the int illustrated above based on index/id
or open to suggestions if that is a bad way to do it
You cannot and should not update the int you are showing. The state of what is currently being selected should be handle else where such a class name InventoryUI.
Thank you, I currently have an inventoryManager.cs that is on the parent of all inventory slots. I also have inventorySlot.cs on each slot game object.
The InventoryManager could be consider the model of your UI. What you want is add an extra layer between it and your view. Your view being the button, the InventoryUI being the Controller and the InventoryManager being the model.
In other words, follow a sort of MVC flow between your different composant.
You inventory should be agnostic of your UI.
Hmm, wondering how much backtracking I should do.. My UI is currently just reading from the playerInventory and applying it to the slot
There is multiple of MVC approach, this is what I prefer from experience.
This is prefectly fine for a start, however you are now in need of a UI state which justify the added layer.
Code is evolutive. When you add extra feature, you sometimes have to refine the structure of things that are already in place.
I may be using this model, but I was double checking to confirm 😄
The inventory list of game objects is on the player, inventoryManager.CS (perhaps a bad name) reads the inventory list, and the empty slots get updated in realtimew based on the live inventory adjustments
not sure if that is traditional (or technically MVC)
The controller manipulate the data from a UI perspective in a VideoGame context (Which should be the same in Web Application).
What you have describe seem to qualify as a controller, however it is poorly named.
you are likely right on that... this is my first go at open world game with a lot of aspects a large team would be handling... but I'm solo
I do not think you should have a InventoryManager
Not sure what you mean. In a large team, you still have 1 person doing that.
Large team is all about work division.
It is hard to have several person work on the same feature at the same time.
yeah, so I'm learning a lot of different things on the fly.. execution probably not perfected on anything
but making an effort
What ever the scale of the team, this is always true.
Nobody is perfect, and the essence of programmation make it even harder as it is continously evolve while you work on it.
One good solution, can become a terrible solution after a few iteration.
the "Use" and "Drop" button get updated based on the selected inventory item, (whether they are disabled, canDrop, etc.)
This seem logical.
so, if the inventoryItem.cs has canDrop = true... the button enables, but I currently feed the button function an int argument... maybe just try to change the function to read a more global int?
from the inventoryManager.cs?
The decision should come from the poorly name InventoryManager.
I would expect to see something like UpdateView which would content a specific section attributed to the Drop and Use button.
You could also decide to dissociate the button and the InventoryManager, however I feel like it would add complexity for no particular reason.
If you do, you would need to define a class that manage the state of your button that can be extended to include the specific of the Drop and Use button.
One way could be to use something like a Condition which is evaluated at the Button level.
Inside the condition you would define a contract between the condition and the Inventory
I was going to make a script to handle button states, but didn't want to unless it was appropriate
Something like CanUseCondition which content an indirect reference to the InventoryManager through and interface ICanUse which define a function IsUsable.
This, would be complex for no real immediate benefit.
The avantage of such a structure is that it can be reuse in mutliple place.
It would be easy to make the CanDropCondition after having done the CanUseCondition.
Also, given you used an interface, you would even be able to reuse the condition on other context than an inventory. However, I feel this is making the things more complex than it needs to be.
It is an appropriate name.
thank you by the way
#1127676238253805669 Could someone take a look at this?
that's really hard to diagnose without actually running the code. The behavior seen from the images and code make me think the bug is in the mod division operations, so i'd take a second close look at that
what's with the red markers there? :p The player only ever interacts with the UI
Not sure what red marker you are referencing to. The "player", as you stated, only interacts with the view/UI. In fact, the player would not even be able to interact with the controller directly as it is not a UI element. How a user can interact with something that has no interface ?
mainly the ones changing 'request':
Yeah, it make no sense to interact directly with the controller.
but.. but.. 😛
It is not possible in fact.
How would you interact with something that has no interface.
aaahh got super confused because you labeled the controller as "Inventory UI"
The view are the specific element that compose the UI.
Toggle, Button, Panel, etc.
You can have higher level element
Such as scroll view
However, you always gonna have a coordinator between the view and the model.
The model being the game (Player, Inventory, Environment, etc.).
View element are agnostic to the model
yeah technically in Unity the View is always the prefab (or multiple parts of it), but usually gets grouped together with the underlying code (which would be the Controller)
While the controller is the bridge between the view and the model.
god objects ftw
Not really. Prefab can be either, a view, a controller or a model depending on the role they have and the context they are.
well, had UI in mind, where a bunch of Buttons consist a prefab and that technically makes prefab 'be' the controller
Buttons are view by definition.
but yeah nothing stops views or controllers or even models from being prefabs anyway
Anyway, my point is that in Unity it's a bit complicated, because of industry standards and the game engine's design itself.
What's to take from MVC/MVVM is that it's important to always separate UI from data.
hi guys, can you ask multiplayer questions in here?
wondering why my toggle is acting so strange
UI
readyToggle.onValueChanged.AddListener((value) =>
{
NetworkLobbyManager.Instance.SetPlayerReadyServerRpc( value);
});
Lobby manager
[ServerRpc(RequireOwnership = false)]
public void SetPlayerReadyServerRpc(bool value, ServerRpcParams serverRpcParams = default)
{
int playerDataIndex = GetPlayerDataIndexFromClientId(serverRpcParams.Receive.SenderClientId);
PlayerData playerData = _playerDataList[playerDataIndex];
playerData.isLobbyReady = value;
_playerDataList[playerDataIndex] = playerData;
}
UI
public void UpdatePlayer(Player player)
{
this._player = player;
if (player.Data.ContainsKey(NetworkLobbyManager.KEY_PLAYER_NAME))
{
playerNameText.text = _player.Data[NetworkLobbyManager.KEY_PLAYER_NAME].Value;
}
else
{
playerNameText.text = "Unknown";
}
// debug.log player data name and ready
Debug.Log("player data name: " + NetworkLobbyManager.Instance.GetPlayerData().playerName + " ready status " + NetworkLobbyManager.Instance.GetPlayerData().isLobbyReady);
readyToggle.isOn = NetworkLobbyManager.Instance.GetPlayerData().isLobbyReady;
}
"acting strange" is extremely vague - but maybe because when you do readyToggle.isOn = something; that's going to trigger the on change callback
yeah sorry, definitely should have been more detailed
interesting didn't know there was a call back
basically the toggle is false by default, the log prints false, which is fine as i poll the lobby for updates
then when i press the toggle it goes true for one update then back to false
server side though its recorded as the play being ready
so when you set isOn it calls another method?
reading the docs now, thanks
im using this now
/// <summary>
/// Set isOn without invoking onValueChanged callback.
/// </summary>
/// <param name="value">New Value for isOn.</param>
public void SetIsOnWithoutNotify(bool value)
{
Set(value, false);
}
but it still flicks to off the next poll but the code says its true, only only passing true
This is not an advanced topic. You can use the Instantiate method to clone an object. Back to #💻┃code-beginner if you need further help
you can get the ui source and run debugger in it
yeah, its a networking code issue 😦 , trying to debug it
Is it possible to set the build subtarget platform in 2021.3? Basically I would like to use this : https://docs.unity3d.com/Manual/dedicated-server-assetbundles.html but in 2021.3
Doubt it
It's probably you overwriting it somewhere
Hello im trying to make a scoreboard where whenever a player joins the server a ui prefab instantiates so that everyone can see on the scoreboard. Right now i have a script where username and profile picture from steam goes into the scoreboard but you can only see your own username and pfp.
This is my script which i handle everything: https://pastebin.com/exaqv1Az
If you need more info please let me know
yes what is the actual problem?
Problem is people cant see eachother on the scoreboard
You don't seem to be having any code that handles a player joining, or a list of players that are currently in the game
Probably look at the documenation for the networking solution you are using to figure that one out
well i do but in another script where i have to reference it i just wanted to know how i could display so that everyone can see their username and others on the scoreboard
basically see the player joining and list of players done (just ignore it)
If you have trouble with referencing scripts, suggest you try #💻┃code-beginner
?
read my text pls
Next time that is, for now just create a property and drag it in the inspector
then what is?
I know what your goal is, but what exact problem are you running into?
The problem is when 2 players are in an server and they check the leaderboard/scoreboard it will only display the localplayer
basically 20 people can be in a game but in the scoreboard it only shows the local player
okay but you dont know how to display multiple entries on the scoreboard or is it something else?
nope thats the only problem
i have an event where a player joins and leaves
Alright so your scoreboard implementation does not support multiple entries?
it does
that code only shows the part where you get the local players data
then what is the problem
or actually nvm it doesnt
i just need a normal multiplayer scoreboard
yes okay the problem is it doesnt support multiple entries
@plain temple where's the actual networking code?
in a diff script
i only have an event where a player joins and leaves
not sure why your showing that script then if the problem is in the networking
Its not in the networking either, he's just discovered that his scoreboard doesnt support multiple entries
:)
well i want to make that script a network script
yes
First setup your scoreboard so it stacks elements under some game object. Then when a player joins, get their steam ID, add a text/image component for them on the scoreboard and set the values with your existing functionality
Well depends on what networking solution you use, but generally HandleSteamID should be an RPC call that you call from start and send to all other players too
its an own made
that is exactly what i have except its only when the localplayer joins
need to set it up so when anyone joins it will instantiate that with their values
It's exactly what you have except u dont have everything after the first sentence..?
All I did was breakdown the problem into steps for you, because you really arent specifying what was actually done. This code only shows u grab the local player, so it's clear only the local player will be shown
ill explain to you. when the localplayer joins it gets their steamid, username, pfp and instantiates a gameobject to the scoreboard ui which shows all their values
Reread what I wrote. I've already understood what u have, I've seen the code. You just have to extend the functionality now to use your friends CSteamID
oo yes i see that it only takes the localplayers csteamid
thank you ill fix it
Thoughts on this pattern? Hooking up regular C# classes to Update() using an UpdateHook():
public class UpdateHook : Singleton<UpdateHook> {
List<Action> callbacks = new List<Action>();
public static void Add(Action callback) {
instance.callbacks.Add(callback);
}
public static void Remove(Action callback) {
instance.callbacks.Remove(callback);
}
void Update() {
foreach (var item in callbacks) {
item?.Invoke();
}
}
}
Any reason you are not using directly a MonoBehavior ?
Although this sounds like a great idea, managing object lifecycle like this can become a nightmare
It's for when it doesn't make sense for the code to be a monobehaviour, but u still want the update loop
This is what I'm afraid of. Can you name some examples off the top of your head?
How would you instantiate a new gameobject?
What situation makes you need this ?
And maybe it's short lived, so you destroy it aswell
E.g. a bullet (if not using object pooling)
you don't have to, becasue its not a monobehaviour, it would be a C# class. I don't get your question
Any code that doesn't need to be in scene. Like a statemachine, or some manager class like a roadBuildingManager that takes care of building and previewing roads over multiple frames
been there done that, more of a hinderance
you lose inspector especially felt if you have oding with [ShowInInspector, ReadOnly]
In case of a StateMachine, you want the user of the StateMachine to be the responsable of the update of it.
In case of a RoadBuildingManager, you want the RoadBuildingManager to be the responsable of the update of the roads.
its better in almost every way to derive from mono
You'll notice you'll end up impleneting a simplified version of monobehaviour
From my experience, there is no situation where you want code to be updated without being indirectly connected to a MonoBehavior.
you can have IUpdatable, ILateUpdatable and relay unity events down the chain, to some internal objects
If you are looking for a different paradigm altogether, take a look at unity DOTS
Yes but really you are just implementing a monobehaviour then, x)
well no
there is a reason to do that, you dont need to maintain a components lifecycle, no need to have or construct a go
but again you are dodging the unity pipe, you are losing a bunch of very useful perks
especially for debugging
MonoBehaviour can sometimes be overkill. By example, you would not necessary create a MonoBehaviour per state in a state machine. However, the statemachine or the owner of the statemachine should be a monobehaviour and relay any events that are necessary.
@tired wyvern imo a middle ground is best, if you have a root gameobject that carries those, you can have an api that automates their construction sort of var myobj = Create<T>()
and it constructs a go, attaches it, adds mono, you get the benefits of it having its own inspector, its transform which can carry utility objects itself
Thats a neat pattern, I'll try it out.
It was useful reading your convos.
- It's clear to me that there are cases where some code has no reason to be a monobehaviour still wants access to Update(),
- that being said, there are weird bugs that have come up because of using the UpdateHook() so maybe its not worth the hassle.
- I don't use the inspector as much because serialization gets really annoying to deal with sometimes, so that's not an issue for me.
do you have Odin?
Yes I used it alot and eventually dropped it.
i advice to use it at least for [ShowInInspector, ReadOnly]
on pretty much everything everywhere that doesnt need unity serialization, but helps you debug
I just use the Debug toggle in the inspector
😄
I do this too, have a statecontroller as a monobehaviour and the states are then regular c# classes - they all implement a process method - the controlelr decides when they are updated
An example of a weird bug from UpdateHook:
The following scene GameObjects were found:
SingletonUpdateHook```
that is easily supressed
hardly a bug
Probably missing some clean up code somewhere
just deinitialization order issue, which is only affecting editor
public static bool IsNullOrDestroyedSilent(this object uobject)
{
try
{
return !(uobject as UnityEngine.Object);
}
catch
{
// swallow the exception
}
return true;
}
wait im messing it up again
(he could also actually be spawning stuff from OnDestroy)
yes i misinterpreted
that is probably something in the base singleton trying to init a null reference again when entering edit mode
which can be remedied with hooking into
EditorApplication.playModeStateChanged
catching ExitingPlayMode
My guess is that I'm calling the static field here when I shouldn't:
public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour {
static T _instance;
protected static T instance {
get {
if (_instance != null) return _instance;
_instance = FindObjectOfType<T>();
if (_instance != null) return _instance;
GameObject obj = new GameObject();
_instance = obj.AddComponent<T>();
obj.name = "Singleton" + typeof(T).ToString();
return _instance;
}
}
protected virtual void Awake() {
if (_instance == null) {
_instance = this as T;
}
else if (_instance != this) {
Destroy(this);
}
}
}
something like this
that code also probably assumes that you have domain reload disabled on play
since i dont have it enabled for years i dont really know how the InitializeOnLoad and statics should be properly working there
hello guys, i wanted to ask. What would be the most effecient way in making a touch input for a button?
nah i mean making an input system using touch for a button
some people said using this asset
i found a tutorial too in youtube. Is it more easy using this?
I don't really understand what your question is
are you asking how to use UI buttons when you are using the new input system?
Sorry for the confusion. Im making a button that would execute something when its tapped (touch) for a mobile game. Is there an easier way or the quickest way in making that other than the new input system?
This is not an input system question
that's a #📲┃ui-ux question
you just want a UI button
the fact that it's a mobile game isn't really relevant
Oops, okay then ill moved into the ui ux section
Is there anyway to change animation execution order?
reason being i am doing animation stuffs on FixedUpdate(need to predict for collision stuffs)
now can i change bone rotation or something if set AnimatePhysics?
You can manually update an Animator with its Update method.
It's also possible to change the internal player loop with the PlayerLoop API.
https://docs.unity3d.com/ScriptReference/LowLevel.PlayerLoop.html
its kind of bad tbh. Slow
not seeing example how its done there?
No, there aren't examples in the documentation. You can find some examples online.
if only i knew this a lot earlier....
Isn't Resources.Load() misleading in its name? The asset in the resources folder is loaded at the start of the game. It's actually just returning a reference given a string path
So for the past 16 hours I'd been struggling with this issue. Where I'm casting a sphere from the cameras position inside the players controller.
The way Unitys raycast/spherecast works, generally speaking it's not supposed to return a collider if the origin of the cast intersects it.
My issue was that when I fired and jumped at the same time, the raycasthit would usually return my players collider. Not what I wanted.
Spent HOURS debugging and trying to zero in on the issue. Then I put my Character Controller's Move() function inside Fixed Update.
And now the bug is gone.
So I guess my question is: does the game only update the games colliders on Fixed update? Even if the object itself is moving in update?
collider positions don't update until the physics simulation
which is synced with FixedUpdate
Ah
a call to Physics.SyncTransforms() would do it too
I guess it makes sense.
Would that be in Update?
if you change a collider position in Update and need it to be visible to physics queries at that time, sure
Thanks!
Yo Ive been struggling with the Tilemap.BoxFill. I've checked just about every forum post about it but I still cant seem to get it to work
background.origin = Vector3Int.zero;
background.size = new Vector3Int(width, height);
Debug.Log($"Tilemap Size: {background.size}");
background.ResizeBounds();
Debug.Log($"Tilemap Bounds: {background.cellBounds}");
background.BoxFill(background.origin, backgroundTile, background.origin.x, background.origin.y, background.size.x, background.size.y);
My debugs return that the size is what Id expect (9, 9, 1) and the debug for the bounds gives the position as (0, 0, 0) and size as (9, 9, 1) as well, but for whatever reason the tilemap refuses to fill no matter how I go about it
At one point I even tried doing my own for loops using the SetTile but that didnt do anything other than give me this single tile as well
Anyone able to point out where Ive gone wrong?
Edit: Ive also tried changing the arguements being passed into boxfill to just about every combo I can think of and it seems to do very little
BoxFill is pretty buggy last time I checked. I would try setting a single backgroundTile at the min/max positions (origin and origin + (width, height)) with background.SetTile and then BoxFill as usual.
I have this basic InputBufferAction struct which utilizes FrameSliceCounter which is also a struct. They work perfectly when I make them serializable or when I make them class (non-serializable) but break when they are struct and non-serializable.
For eg. in image the frameSliceCounter should count 15->14 then in next frame 14-13 and so on, with class and serializedStruct the state(frame Idx) is preserved while with non-serialized struct they dont. Any insights ?
it's unclear how and where this code is running
but basically - it sounds like you are probably getting tripped up somewhere by the pass-by-value and copy-on-assign semantics of structs
Automatic File Reading
Sorry I forgot to mention, But consider the HasFrameSliceExpired()' in BufferdInputAction as an Update() loop as it is invoked in one.
Thats all, there are no extra calls to method,
I understand pass by value and ref and ik structs are blittable types, but Im unable to grasp where the link breaks. There are no assignments no variable resets nothing, just making it serializable works and removing it breaks it.
If you use class instead of struct does it works ?
As mentioned, yes.
Which ik is the main characteristic of a value loss due to being value type. But then why making struct serializable works ?
Probably due to Unity Serialization process ? It is kinda hard to know because it requires knowing how your struct is being use and where.
Thank goodness its not just me. I tried that last night but I mightve passed in the arguements wrong so Ill retry again when I get home, thanks
Collider[] colliders = Physics.OverlapSphere(transform.position , radius); is there any way to change the source code for Physics.OverlapSphere or any overlap?
when taking the colliders into the array to be exact
Why would you want to change the source code... ?
because why was so hard for this command to let me choose which colliders enter the array
saves a lot of time
because i would not have to iterate trough all the array
Which colliders enter the array ?
what question is that
whatever i want
with the ID i want
or whatever
because why was so hard for this command to let me choose** which colliders enter the array**
What collider ?
It is the result of the function.
What you want ?
i just want to have an overload for this function where it creates the array and takes in just the colliders with the tag i want
i would want to acces the source code for Physics and find the function
is it possible
OverlapSphere peeks into the C++ side, the physics engine. You can't
if yes where to look
inpossible to change the physics engine in any way?
impossible*
c++ is no concern to me
you planning to re-write PhysX?
You can use layers ?
I don't understand why you would need to take an array in that. It's a physics call, it queries the physics engine and returns the collider around some point. If you need to do some filtering on the results, it's either afterwards on the array that it returns, or beforehand with a Layer Mask
i said, just for time save
"just" an overload. but it's all done on the c++ side so unless you plan to somehow modify physx and/or the unity engine itself you cannot do what you've decided to do.
literally the entire implementation is on the c++ side
https://github.com/Unity-Technologies/UnityCsReference/blob/master/Modules/Physics/ScriptBindings/Dynamics.bindings.cs#L871
take the advice others have given you and use layers/layermask
iteration with an O(n) algo is just pain
use a layermask
How many result do you have ? Because 10 iterations is nothing.
Profile, only optimize if it needs to be optimized
Big O is only useful with high numbers.
Hello I'm having an issue with DoTween that warns reaching maximum tweens. It comes from an object that is spawned quite a lot so I'm suspecting that I'm not properly killing my sequence but can't figure it out exactly.
private Sequence sequence;
private void Start()
{
sequence = DOTween.Sequence();
sequence.Append(transform.DOMove(transform.position + (Vector3)Random.insideUnitCircle.normalized, 1).SetEase(Ease.OutCirc)).SetTarget(transform);
sequence.AppendCallback(() => Destroy());
}
private void Destroy()
{
Destroy(this.gameObject);
}
private void OnDestroy()
{
sequence.Kill();
}
small radius around 5, max radius when the player is maxed like 30 and something
So, max 10 colliders...
So, you went down to 50
yes
How many colliders do you have ?
total?
normal items and entities - 20
world structers and others - 30
40? lmao
dotween has a default limit of 50 sequences
Are you running the request on every object ?
The shotgun I made shoots more than that
use the nonalloc version
this creates garbage
I'm having like 8 sequences at a time tops
agreed
could you explain more?
It smells like some kind of leak, because the warning appears after 2 or 3 minutes
yes
Maybe you should consider using Triggers instead ?
what's to explain - use a preallocated array and the nonalloc version to avoid creating new arrays every frame
Yeah I was wondering if using OnTrigger* methods would lighten that up
Aaaaa ok
agreed
idk - the dotween documentation doesn't mention anything about cleaning up
wait that's a genious idea
so I assume they go away when they're done
how could
And layers to reduce the number of potential collision with object that cannot and should not collide.
You should do sequence = null; in Destroy() probably
or in OnDestroy
after sequence.Kill
you are the best , thanks 💓
i am so dumbfounded that i did not think about that
Found the issue for reference, I was using the Tween.Rewind() somewhere else that was causing the issue
Is it possible to not draw a specific set of meshes in the editor so that I can have a custom OnSceneGui to draw meshes?
I do not understand what you are asking for.
out of curiosity, how do those Vector3 shorthands work, like Vector3.left? From what I can see in the code all it says is {get;}, but that doesn't explain how there's a difference between Vector3.left and Vector3.right
It returns new Vector(1,0,0) and new Vector(-1,0,0).
well yeah I know that, but how does the code specify that
What do you mean ?
What exactly you want to know ?
Because it seem pretty straigh forward.
on the class of Vector3, this is what it says for Vector3.left and Vector3.right
all it says is {get;}
and they read the exact same
how does it know what to return
You are looking a decompiled code.
Take a look at the source code https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Math/Vector3.cs
Here you go.
yeah that makes a lot more sense, thanks lmao
I want to create a component that allows designers to specify different armors for submeshes. For example, the head could be a critical zone which would have a debug color of red, and the hands and feet could be trivial zones which would have a debug color of blue.
I don't want to change the material on the game objects. But I don't want to create z fighting between the debug mesh and the game mesh.
You can easily change the material for the duration of tool, or even better, disable the renderer.
However, normally, you do not use mesh collision but primitive for collision such as hit zone.
(Hit zone are sometimes bigger then the actual target)
I believe I've asked this before, but don't recall if I got a concrete answer or not. If I have a ScriptableObject asset, and that ScriptableObject class has methods in it... If there are two separate GameObjects in a scene that have a script on them that references the ScriptableObject asset, and I call one of the methods on GameObject(A)...will it automatically excute on GameObject(B) too? ...just double checking my understanding of ScriptableObjects usage and how they work.
It's just a method call. The code will execute once.
hey so i am working on a game involving vr controllers and I would like to know what do i have to do in unity if I want to link a UI menu i created in unity to connect to the controller
ive been told it is code related i just dont know what lines of code they would be
Probably due to Unity Serialization
more like libs of code
what you mean libs of code im still new to coding so yea
libraries of code 😛 check for ready asset if you're new to coding, as this is no simple task, and anything you hear in #archived-code-advanced is probably gonna be way too complex
dang I thought you were calling them a liberal
yea dw the stuff im doing is waayy more advance but im still learning like ik a bit but yea where do u think i should look for ready assets because i tried to search online about what is the code required if you want to use a controller (any type of controller) as a system to move the "player"
the asset store would be the go-to
I assume you want to render a dot wherever the VR controller is pointing to, detect clicks on buttons, support dragging around, etc
this looks like an all-in-one bootstrap: https://assetstore.unity.com/packages/tools/gui/vr-uikit-bootstrap-your-vr-app-with-ease-128236
sorry for the ping again
im not seeing animator stuffs from this playerloop?
is legacy animation same as animator's update?
How do I get the list of bones from a loaded Mesh asset? Not sure if there's a way. But I've also tried creating a GameObject in a custom editor tool, adding a SkinnedMeshRenderer to it, and then setting the sharedMesh field, and then trying to access the bones array but it is empty.
Mesh has no bones 😛
the .fbx I'm loading has bones, is there another type I can use to access them?
when you export a rigged character as FBX from blender, it exports the whole hierarchy, which includes
A) the mesh
B) the bones
and when you import it in Unity (or any other game engine), you get a GameObject that contains
A) The root GameObject
B) A GameObject with the renderer (referencing the mesh)
C) The hierarchy of bones
so, that said, there's no way to get a list of bones from just a Mesh asset
what about the bones array on the SkinnedMeshRenderer? otherwise I can get the bone names from the heirarchy
you would need to access the prefab
I'll try that, thank you
The Director stuff is what you're looking for
that's working, thanks. would you know how to get the material slot names?
np! names? what do you mean? can you show in the inspector which part in specific?
the names here on the left
ah I doubt you can get those, unless editor scripting (?)
yes I'm creating an editor tool to import and setup ~3000 assets, so can't do anything manually 😢
is there a way to rip these names from the inspector panel? haha
those are built in materials, im not aware how to get them after the fact but they must be present during import, if there is no way otherwise you can try caching them in your custom asset post processor
built in the fbx, generated by unity
you should be able to get those via Importer yeah. pretty sure I had.. I can check for an old importer in like 10 minutes
hmm iirc I wrote another script to edit those to hardcoded values
or.. nvm
thank you! I'll give this a try
doesn't work.. 😛 sec
I remember I had to do some hack for this, just not 100% certain which hack 😄
@quick ibex can you post the .meta file of the model whose inspector you linked?
I'll DM you
I wonder if the names are there :p
hmmm doesn't look like the names are there
RIGHT! so.. once you export, the fields for 'remapped materials' should match the name of the material
my importer is on an HDD I don't wanna bother attaching now, but the hack I remember I did was something like this:
var originalAssetPath = AssetDatabase.GetAssetPath(myObject);
MoveAllMaterialsToFolder($"{originalAssetPath.TrimEnd(".fbx")}/Materials");
var importer = (ModelImporter) AssetImporter.GetAtPath(originalAssetPath);
importer.materialLocation = ModelImporterMaterialLocation.External;
importer.SearchAndRemapMaterials(ModelImporterMaterialName.BasedOnMaterialName, ModelImporterMaterialSearch.Local);
importer.SaveAndReImport();
this made all materials get automatically mapped from the Materials folder.. but I never managed to get the name of the fields (neither did I need them, tho)
I really just need the names, because I have a bunch of textures that have the material slot names in their file names. I guess my last resort is to use a fbx file importer library 🤣
I also had another script that exported all textures and stuff to match the material name (on 3D software)
so, Ball.mat would have Ball_Diffuse.png, Ball_Height.png, Ball_Normal.png, Ball_[...].png
but yeah.. those names are probably not obtainable easily.. there should be a way if you dive deep in Unity's inspector internals, but Unity doesn't like that ;p
that's alright, I'll just do the ineficient thing and load the file again using a fbx importer library haha
thanks for your help
np please throw a ping if you manage to do it 😄
You want to get the name of the mesh? if so, get it via mesh filter
var mf = instance.GetComponent.<MeshFilter>();
var mesh = mf.sharedMesh;
Debug.Log(mesh.name);
if they're not merged into a single mesh you can just do var meshes = myGo.GetComponentsInChildren<MeshFilter>(); and do the same as above to get the name
I'm trying to transition an animated model to a ragdoll in unity and it looks "explosive". I already set each rigidbody's velocity and angular velocity t; zero. what else can I try?
guys hello how can i fix this error
False positive. Restart the Unity Editor or simply clear the logs / ignore it.
when i press the play button it comes
im restarting now
yes it worked i think
thanks 🙂
what is the algorithm of linecast (or raycast) on a quadtree
four children check if line intersect (or is contained) in the AABB, if yes then recursively call on those children intersected? it sounds slow but i only comes up with this algorithm, probably can be slghtly speeded up by cohen-sutherland algorithm
probably what this code is doing but I find cpp extremely hard to read. Is there something about cpp that makes programmers use inscrutable identifiers?
https://github.com/NVIDIAGameWorks/PhysX/blob/a2c0428acab643e60618c681b501e86f7fd558cc/physx/source/geomutils/src/GuAABBTreeQuery.h#L165C17-L165C17
I have a 6 vertex, 5 polygon extruded triangle that is built in code. I would like each face to have a unique material with its own UV coordinates. How could I do this?
In Unity every renderer has an array of materials
each material corresponds to a submesh
split your mesh into submeshes and you'll be able to apply a separate material to each
I've been doing that! And I managed to get every submesh its own material.
My issue came with the UV
For some reason, no matter what I did - each one of my submeshes used the first one's UV
sounds like you need to actually do the UV mapping process in Blender
That's the thing, I can't!
It's a dynamic shape
It will always be an extruded triangle
if you are making the mesh programmatically you will need to assign the UVs programmatically
But the size and angles will change
Yeah!
And I would Love to do that
But it's not doing it the way I would expect it, and unfortunately - I can't quite figure out anything else to try..!
I'll send some code in just a bit!
Create an array of UVs and assign with this property:
https://docs.unity3d.com/ScriptReference/Mesh-uv.html
I presume you simply have a bug in your code if it's not turning out properly
Yes I think so too!
Already utilising this, mhmm!
public Mesh createMesh(List<Vector3> vertices, float thiccness, float offset)
{
Mesh mesh = new Mesh();
float topHeight = thiccness * (offset+1);
float botHeight = thiccness * offset;
//Set the vertices
Vector3[] meshVertices = new Vector3[6];
meshVertices[0] = vertices[idA] * topHeight; //A Top
meshVertices[1] = vertices[idB] * topHeight; //B Top
meshVertices[2] = vertices[idC] * topHeight; //C Top
meshVertices[3] = vertices[idA] * botHeight; //A Bot
meshVertices[4] = vertices[idB] * botHeight; //B Bot
meshVertices[5] = vertices[idC] * botHeight; //C Bot
mesh.vertices = meshVertices;
int topMeshIndex = 0;
int acSideMeshIndex = 1;
int botMeshIndex = 2;
//Triangles
int[] topTriangle = new int[3]
{
0, 1, 2, //Top
};
int[] acSideTriangles = new int[3*2]
{
0, 2, 3, //AC Top
5, 3, 2, //AC Bot
};
mesh.subMeshCount = 2;
mesh.SetTriangles(topTriangle, topMeshIndex);
mesh.SetTriangles(acSideTriangles, acSideMeshIndex);
// mesh.SetTriangles(botTriangle, botMeshIndex);
//UV
Vector2[] topUV = new Vector2[3]
{
new Vector2(0 , 0),
new Vector2(0.5f, 1),
new Vector2(1 , 1)
};
Vector2[] acSideUV = new Vector2[4]
{
new Vector2(0 , 0),
new Vector2(1 , 0),
new Vector2(1 , 1),
new Vector2(0 , 1)
};
mesh.SetUVs(topMeshIndex, topUV);
mesh.SetUVs(acSideMeshIndex, acSideUV);
//Calculate normals (optional)
// mesh.RecalculateNormals();
// Return the created mesh
return mesh;
}
I removed some parts for clarity - I have all the sides setup, and mapped out correctly
My problem comes with the fact that all of my sides use the topMeshIndex UV
If I uncomment mesh.SetUVs(topMeshIndex, topUV);, then the acSide no longer has any UV either.
Also this doesn't work in the first place
I was padding the UV arrays to have 6 elements before
no it was the mesh material slot names, they're on the left side in that picture. managed to get them via a fbx importer library instead.
hmm... so, I'm confused about one property of asset bundles - when I load asset bundle filled with sprites in one scene (loads ok) and then switch scenes, texture associated with that asset bundle gets destroyed while sprites are still there, using destroyed texture
texture seems to be auto-generated atlas by Unity containing all sprites of asset bundle I'm loading
so basically:
Before scene change:
asset bundle > sprites loaded from bundle > auto-generated texture backing the sprites
After scene change:
asset bundle > sprites loaded from bundle > null
any idea why this happens? I'm sure I'm not deleting the texture manually
If you delete asset. (Destroy(...)) They will be destroyed from the asset bundle if I remember correctly.
hmm... Instead of Sprites I add Texture2D's to bundle now and make Sprites out of them, aaand it works
so I'm assuming it's something related to how Unity handles dynamic sprite atlasing
I'm using Atlas in an AssetBundle without any issue.
is gpu skinning good on a GPU bottlenecked game?
never used but i know the theory, and what it achieves is removes all the cpu objects, transforms, vertex buffers and offloads to gpu shader
so maybe it can help by removing the cpu/ram/gpu roundtrip, reduce bandwith usage, but the shaders become more complex
Yo sorry to bug you but this doesnt seem to like me either and I wasnt sure if you knew of anything I might be missing to make it hate me
background.origin = Vector3Int.zero;
background.size = new Vector3Int(width, height);
background.ResizeBounds();
Debug.Log($"Tilemap Size: {background.size}");
Debug.Log($"Tilemap Bounds: {background.cellBounds}");
background.SetTile(background.origin, backgroundTile);
background.SetTile(background.origin + background.size, backgroundTile);
background.BoxFill(background.origin, backgroundTile, background.origin.x, background.origin.y, background.size.x, background.size.y);
I tried playing with the arguements being passed in and doing things like not resizing the bounds and whatever else but it still just gives me a single tile shown like before. Is there anything in the inspector I should be double checking or are tilemaps just a bit funky sometimes?
Greetings, I'm running into a dillama where I need to use .net framework in my unity project over .net standard.
I am wondering if that is a dangerous choice long term, and if it is advisable to avoid it.
I ideally want to run my game on multiple platforms in the future.
Lemme test it out on my end and see if I get the same issue.
If you intend to do multiplatform you might have issue down the line.
Thank you.
I see the issue now, the problem is the position argument is not for the origin, or rather, it doesn't work for the origin, do this instead:
background.ClearAllTiles(); //Optional
background.origin = Vector3Int.zero;
background.size = new Vector3Int(width, height);
var endPosition = background.origin + background.size;//In case origin isn't 0
background.BoxFill(endPosition, backgroundTile, background.origin.x, background.origin.y, endPosition.x, endPosition.y);
background.ResizeBounds();
And needless to say make sure backgroundTile isn't null. This is why we need Option<T> in C#.
I thought it was Nullable<T>
Does anyone have any idea on how to reduce the time a SphereCast creates? Im doing a spherecast to detect objects to damage and the profiler is reading that this spherecast is taking 20ms to run. Is this normal? What can i do to reduce it
{
foreach (Collider col in Physics.OverlapSphere(transform.position, radius))
{
if (col.attachedRigidbody == null || col.gameObject.Equals(gameObject)) continue;
foreach (IDamageReceiver damageReceiver in col.GetComponents<IDamageReceiver>())
{
if (impactEvent.Receivers != null)
{
if (impactEvent.Receivers.Contains(damageReceiver)) continue;
}
float distance = Vector3.Distance(damageReceiver.Position, transform.position);
float damageFalloff = Mathf.Clamp(RawDamage / Mathf.Pow(distance, 2 / radius), 0, RawDamage);
damageReceiver.Damage(new HealthEvent(damageFalloff,
damageReceiver.Position,
(damageReceiver.Position - transform.position).normalized,
source));
}
}
base.Activate(source, impactEvent);
}```
OverlapSphere you mean?
Yes, a good start would be to use the non-allocating version of it, SphereCastNonAlloc. Instead of creating an array each time it's called, you pass your own and it fills it by reference.
Another way that would be more performant if you have a lot of objects with that script on, would be to not use SphereCast at all, and track what enters and exits your vicinity using OnTrigger* methods
Nullable<T> is only for value types, and doesn't prevent you from accessing its value when null like Option does.
ill give that a go, but how would i go about NonAlloc when this overlap gets such varity between sizes?
Allocate an array that's estimately big enough to store the maximum colliders you might have in one query. It returns an int that tells you how much of them it detected, you can for-loop with that
Alright, ill give that a go
That worked! thank you
Ran into another problem, Unsure if this is the right channel; Would anyone have any ideas as to why [ParticleSystem].Stop() is causing a performance spike of over 350ms?
YOOO, thanks
Ill try this as soon as Im home again
Hello working on a multiplayer game i got this error just now havent been able to figure it out, using Photon 2 free
It's a warning, not an error. It's telling you that PrefabInstanceStatus.Disconnected is obsolete for the reason stated in the message: prefabs can never be in a "disconnected" state. You can remove the second part of that condition entirely.
(you can keep it, it won't do anything, but it might transform into an error if you upgrade the version of Photon later on)
thanks and yes it could end up being an error later on thanks for your help
this am i correct
No, what's after the || and the || itself
yes ofcourse thanks
I'm trying to use a compute shader in a command buffer, but setting data in a compute buffer with cmd.SetComputeBufferData() is for some reason, depreciated? Why? What's the alternative?
Ohh wait cmd.SetBufferData() exists now, nevermind.
Hi,
https://docs.unity3d.com/ScriptReference/Physics.OverlapSphereNonAlloc.html
Does OverlapSphereNonAlloc fill the array from the center point or from the extents or totally random?
hello! I created this mesh, and now I want to change the color of the selected face (like in the image). How can I change the vertex color? Do I have to user shaders?
are u asking about the order of colliders given? you cant really rely on the order unless you know exactly how the physics engine calculates it. If you're trying to calculate the closest or anything, you'll have to do that yourself
I want to keep a lower size of the collider array, but i want to ignore the far collider first
You decide the size of the array already, but i really have no clue what you mean by "ignore the far collider". You havent really specified what you're doing
I'm doing an OverlapSphereNonAlloc in a specified point, but i don't know if there are 10 or 1000 colliders near the point. I'm good taking the closest 10. dunno if i can keep the array size = 10 or have to take in consideration all the colliders and than filter for distance
getting the closest X from 1000 colliders really wont be an issue unless you are running this very often. You may also want to reconsider how you're doing this if your overlap sphere is covering a massive radius often
Is it a good idea to add more load to a truck thats already loaded beyond capacity ?. Answer is same for both.
I'm monkeying around with writing my own collision system using Burst but I've hit a bit of a wall design-wise. Here's my current process:
- For each object, I get all the nearby object (optimized with quadtree partitioning)
- I pass the object along with its found neighbors each into their own job to check and resolve movement and collisions for that object (in -> a collider info NativeArray, out -> a 1-index-long Vector2 position NativeArray)
- I apply the output position to the transform of the main object
- I adjust the quadtree partition based on all the objects' new positions
I'm having terrible overhead in allocating NativeArrays with miniscule time spent in jobs.
Do I expand the neighbor searching and batch groups of collisions together instead of giving each one their own job? Do I consolodate all of them into a single job- if so, how can I do that while still using a quadtree to avoid n^2 performance?
TL-DR; Too many NativeArray allocations are killing my performance. What's a better approach that keeps the quadtree performance gains in lieu of giving each thing in my scene their own job to resolve nearby collisions?
NativeArray allocation performance
Id assume pseudo random, it likely collides in order of some kind of ID that entities have, Id bet you notice it ends up being Oldest->Newest entities in order, so yeah you'll want to sort by distance.
Luckily sorting runs in nlogn time so shouldnt be a notable impact on performance
no you dont even need to sort, you only need a max heap of size 10
so for finding 10 smallest item in n items only require O(n log(10)) = linear run time
Is there a library that handles HLSL or Shaderlab AST?
To be precise, I would like to generate shaderlab or hlsl shaders from code and be able to transform them easily
The only thing I found for now is a reference on Vulkan's site to something called DXC (DirectXShaderCompiler) which under the hood generates an AST after parsing HLSL
can it help me and is it possible to use it in unity somehow?
What's the proper way to slow down animator update? What I mean by this is, I want to lower animation update at far distance, somewhat similar to what RDR2 and Elden Ring does. What's the way to approach that?
I know about animator.update but that's not a solution since its single threaded only
Shaderlab, no. DirectXShaderCompiler has some options for navigating the AST of a hlsl file, but it doesn't let you modify it or turn it back into source code.
You do not want to hear it, but the solution is Animator.Update.
That screws up the performance
Depends.
Just be more aggressive with it.
You might consider switching to DOTS...
I killed animation at far distance
Not all of DOTS is there
I hope.
Also not much Hybrid solution out there
I still need a layer to make the scene less odd
I mean, if you have 2000 Dynamics Object you have solution where DOTS make sense.
Still, the answer is using Update.
It works well when you have a relatively small amount of object.
You spread the update on multiple frame.
Can I spread it using Job? Does Update support parallel calculation even?
Oh got what you meant
Pretty sure it does not.
I think you might be interested in using the Playable API.
There is finer control there.
Maybe you can solve your batching issue.
If your game run at 60 FPS, you can Update Animation at 30 FPS. Half a frame, half an other frame.
It works correctly when you have a relatively small amount of object.
I have done it*
Do not remember the exact performance gain though.
I have 2 layer and using prediction to replay from previously left state using Time.time
1st layer is normal
2nd layer is the one where animator just disabled
No idea what you are doing.
also following strict pattern of blend tree to make prediction work
Firstly you calculate Time.time when you disable
Later on lets say you are close by, then when turning it back on you substract current time with previously left time
Oh, you mean to start animation where it should be starting again.
Yeah
Pretty much over-engineering in my opinion.
For blend tree we are using 60 frames for idle, 30+30 for walking and 20+20+20 for running. To have accurate prediction
Not much choice other way for 2000+ objects
It should matter even less.
Because there is more object, the player will not be bother by the small detail.
You can also keep the animator state when you disable it.
If you did not know.
I mean we have problems where player is not getting its shield up behind back thanks to culling
To address that we introduced temporary always animate behind our back using spatial partioning
Can predict attacks now
Could it be because it is not being animated out of frame ?
I had this issue like yesterday.
Yeah culling to save performance but comes with its own problem
Unity doesnt give much access
Just set the object that was causing an issue to always animated.
I think the issue was because the animation was driving the position of the object.
The way i see it, you have to tweak around between culling and always animate
I believe you should spatial partioning to make characters split into grids
Lets say i attacked or npc behind me attacking one another
You are over-engineering yet again.
By default thanks to idle they wont do anything
Will never hit each other unless you just go radius or sphere collision
Design wise its not that good atleast in my case
Had to temporarily enable animation based on timer of the attacker's clip time
Why do shaders on tilemap not work on Hex pointed top?
It seems whenever I apply a material to a hex pointed top map. the hexes convert to a flat top
We achieved what we need but still worried how unity handles Animator.Update()
X is an indivual pointed top hex being rendered with a sprite rendered
meanwhile Y is thesame pointed top hex being rendered using tile maps
They both use thesame material
but in tilemap, the hex shape is changed
Good afternoon,
Can anyone help me with this? I'm trying to send an API request but it gives me this error: Curl error 60: Cert verify failed: UNITYTLS_X509VERIFY_FLAG_USER_ERROR1
I have looked for a solution in several places but have not found an answer
Hmm, just a guess but are you allowed to use said API?
according to the api code manager, yes
I am in contact with him trying to resolve
the url works directly through the browser, only this problem occurs inside unity
Did you try to use something like Postman ?
// string url = "https://avatarmuskverse.com/login-game?username="+ userName +"&password="+ password + "&version=" + versao;
string url = "https://avatarmuskverse.com/login-game?username=lmjDixon&password=******&version=1";
UnityWebRequest www = UnityWebRequest.Get(url);
Debug.Log("URL LOGIN: " + url);
// www.SetRequestHeader("Content-Type", "application/json");
// www.SetRequestHeader("X-Requested-With", "XMLHttpRequest");
yield return www.SendWebRequest();
if(www.isNetworkError || www.isHttpError){
Debug.Log("Erro ao logar: " + www.error);
}else{
string json = www.downloadHandler.text;
retornoInfoUsuario = JsonUtility.FromJson<RetornoInfoUsuario>(json);
Debug.Log("Conexão efetuada com sucesso");
}
}```
yes
Looks like an invalid/expired TLS certificate or it's signed by a certificate authority which your device doesn't trust
Can you try outside of Unity with wget or curl, wahtever you have?
Also change that password if it's the real password. It's both now leaked, and insecure
No one knows what could be causing my problem with the hexes?
ok
thanks, i will change
but now is just one test
I will pass on to my colleague responsible for the api to see what he replies
Also, what platform are you using ?
I particularly cannot help
just unity to call the url
sorry my english
So, Windows ?
no
If it was on other platform like Android or Hololens it could have been explained online.
try posting in the 2d topic, I think you will get more answers about
understand
I will keep looking
thanks for help
by 2d topic u mean #🖼️┃2d-tools ?
yes, i guess
I'm following a yt tutorial on how to transition from a ragdoll back to animation, and I'm trying to lerp my bones towards the first frame of my animation. But using animationclip.SampleAnimation() I'm getting bone positions in a t pose? Why would sample animation give me a t pose?
update: works if I reduce the weight on an animation layer... but sampleanimation cares about layers?
private int FacingSign
{
get
{
Vector3 perp = Vector3.Cross(transform.forward, Vector3.forward);
float dir = Vector3.Dot(perp, transform.up);
return dir > 0f ? -1 : dir < 0f ? 1 : 0;
}
}
the property returns a value based on the dot product result. If the dot product is greater than 0, it means the character is facing left, so it returns -1. If the dot product is less than 0, it means the character is facing right, so it returns 1. If the dot product is exactly 0, it means the character is facing neither left nor right, so it returns 0.
Is this an accurate diagram to represent this code?