#archived-code-general
1 messages ยท Page 60 of 1
yeh but you can write your own equals implmentation with the interface
ok yeh their equals method worked - thanks
hi so im trying to make a simple dash that lerps your velocity back to where it was before dashing
Vector3 previousVel;
private void StartDash() {
if (isDashing) return;
isDashing = true;
previousVel = rb.velocity;
rb.AddForce(dashForce * orientation.forward, ForceMode.Impulse);
StartCoroutine(InterpolateVel());
Invoke(nameof(StopDash), dashCooldown);
}
private IEnumerator InterpolateVel() {
Debug.Log(rb.velocity);
Debug.Log(previousVel);
while(rb.velocity != previousVel) {
rb.velocity = Vector3.Lerp(rb.velocity, previousVel, 0.2f);
yield return null;
}
}
private void StopDash() {
isDashing = false;
StopCoroutine(InterpolateVel());
}
and in interpolateVel, rb.velocity and previousVel are always equal (that's the problem)
That is not how you stop a coroutine https://unity.huh.how/programming/coroutines/stopcoroutine
Also not how you use Lerp
and you should probably also improve that lerp so it's not so jank https://unity.huh.how/programming/specifics/lerp/overview -> https://unity.huh.how/programming/specifics/lerp/coroutines
k
Hello, I have a question: How do I reference different data types that are all enums; case: I want to use a serialize field that's an enum but that data type can change:
public enum Month
{
Jan,
Feb,
}
public enum Day
{
Saturday,
Sunday
}
I want to be able to reference wither of those types in the same place... how do I do that please
(I know about templates but I didn't find the way I need to be able to do this)
enums are numbers by default.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum
Dictionary?
you can cast them to integers and to whatever enum type you want
yes... but I dont want the numbers I want the values that I put (the name of each value)
I want to reference the data type itself
I don't understand the question, are they meant to be serialized together? If so, just make a struct
no no @quartz folio
Yeah, im not understanding the ask
Days meetingDays = Days.Monday | Days.Wednesday | Days.Friday;
ok I will try to put it this way
thats a flagged enumeration
It's cs or csharp for the colours btw.
oh thank you..sorry
Are you referring to generics?
GetEnumValue<TEnumType>?
trying to explain what I am trying to do... I want to use a Data type.... like I have several game objects, I want them to have a variable that's either of weekdays or month ...
when structuring data, you use strongly typed objects
under the hood, enumerations are just whole numbers, binary representations if you use flags
the values for one enum dont directly map to another
so in order for you to prevent trying to deserialize to a specific enum that might not exist, you have to know the type
yes I want tio pick up the type in the beginning
so what I was thinking is referencing a datatype <T> that's an enum
you'd have to have your parent class handle generics as well to know which enum type its using
how are you expecting to actually use this thing
yes I dont mind that but I dont know what's the right way to do that
why do you need to goggle between two enum types?
thats not really an intended usage
you'd have a lookup table or something
your record would have a masked value to map out to those enums
tell us what you're doing with these enums
I want to write one class to do this... i dont want to do masking or anything like that
but thank you
it seems like i will have to do it that way
is there a reason why you arent telling us the usage?
there is more than one usage
enlighten us ๐
What will the code that uses this look like
that will help us steer you in the right direction
the first is the simplest, I have a several dropdowns that I want to change their values depending on what they represent (the idea is easy here... just pick before the game launches in the inspector the data type )
public class ChosenDate
{
public Month SelectedMonth {get;set;}
public Day SelectedDay {get;set;}
}```
the ToString for enums by default will use the name value instead of the number
yes yes
eg Month.Jan.ToString() == "Jan"
but I dont want to referene both
how do you know which one to use?
Can you answer my question then
You're going to probably need some type checking for what you're thinking of
public class ChosenDate<TEnum>
{
TEnum SelectedValue {get;set;}
}```
I want to pick that in the inspector... I want to pick EITHER day or month for each dropdown*
If you want to do it in the inspector, that seems a little more complicated.
still no idea how this code is meant to be used when you actually have the type
which I have asked 3 times now
public class DateSelector
{
Type ChosenEnumType {get;set;}
int RawValue {get;set;}
}```
but you'd have to cast from the int to the type with reflection or something
and you'd have to tell the inspector what the list of viable types are
Lets rewind and pause... Tell us what you're doing. Explain your project
[Serializable]
public struct DayOrMonth
{
[SerializeField] private bool _isDay;
[SerializeField] private Day _day;
[SerializeField] private Month _month;
public bool TryGetDay(out Day day)
{
day = _day;
return _isDay;
}
public bool TryGetMonth(out Month month)
{
month = _month;
return !_isDay;
}
}```
and then make a property drawer for it
my project is boring, just writing details and such but I am trying to make it look pretty
...
thank you but you're really not getting what I mean... I can do that and I have done it before but i am trying to push myself to the limit...
I am trying to put only one data type that can be either of them.. just like when you do inheritence you know
๐ sorry
well, you've been provided many different answers and little information so until there's actually an answer to our questions nobody can help you
use an integer and cast when necessary
No idea why you want inheritance when this takes up the space of what, two bytes and a bit?
ehh, you have to explicitly specify that the enum is a byte
its an int by default or a short?
why not do that then?
with what they showed for values, no reason not to
i have answered and given you the usage
No you havent
At no point have you provided any code example of how you would expect to access either a Day or a Month
You told us what you want to do... not why
ask
I haven't because it is not working with me, i am asking what way (if it exists) would I be able to put a generic datatype where I can put either day or month enums
I answered... I am writing a project where I am only inputting data
You can use generics with enums just fine, there is nothing stopping you
You do realize thats not saying anything, right?
just constrain it to Enum if you care to do that
ok how do I reference a generic data type as a serializedfield
because it is not related in anyway to the problem...
what does that mean?
[Serializable]
public struct Something<T> where T : enum // or whatever needed
{
[SerializeField] private bool _isDay;
[SerializeField] private T _value;
public bool TryGetDay(out Day day)
{
day = _value;
return _isDay;
}
public bool TryGetMonth(out Month month)
{
month = _value;
return !_isDay;
}
}```
that would need some rework... those trys would fail in various conditions lol
if you're referencing a day as a serialized field.. the inspector will give you a dropdown that shows the choices ...
I want to make the inspector show a dropdown that has 2 data types either a month or a day
Type[] types = new(){typeof(Day),typeof(Month)};
all he needs is a custom editor, really
What was wrong with what I previously provided? You can easily make a property drawer that displays that struct that way
it is different than what I wanted
I will try to look into this
thank you all and sorry for confusing you
There's this too, but it doesnt support generics, you'd have to box your enum in custom classes
This won't work because enum is not a valid constraint. You can check if T is a struct implementing IConvertible, and then validate if the type's isEnum field is true.
// or whatever needed
thank you
I know, doesn't hurt to give the solution, does it?
Enum is a valid constraint
again everyone sorry for confusing you
is it worth you causing abrasion by calling me out for it when we're beyond that?
In Unity too?
yes
since c# 7 we can do that yeah
this is valid public static Dictionary<int, string> EnumNamedValues<T>() where T : System.Enum
in the old days we'd do it like this where T : struct, IConvertible
i have this in my github for old stuff from like 2016 and older
dbase/foxpro loved their enums
I also have a SerializeReference dropdown that supports property drawers and UIToolkit https://github.com/vertxxyz/Vertx.SerializeReferenceDropdown
But if this is the answer to the question it's the most poorly phrased question of all time. It would have been so quick if we got like any code explaining the use case that wasn't relating to the original enum question
I think you should stop feeling personally attacked. You're one of many people I respond to and you're not being targeted by anything.
I highly suggest we stick to the topic.
struct, IComparable, IConvertible, IFormattable
You weren't even right...
Oh, sweet. I'll definitely look into that one when I get home
The implementation is complex for both IMGUI and UIToolkit to support property drawers, and due to SerializeReference being jank (I have reported so many bugs) it may appear wrong at times, but I feel like I can't really use things without property drawers!
When I create GameObjects with GameObject.CreatePrimitive in play mode they persist after exiting play mode, why?
I would presume you're accidentally creating things in edit mode, or from a function that you shouldn't be creating things from, as I can't think of another reason that would happen
It's in Awake...
are you inheriting from any class?
Well there you go.
๐
How can see more variables if I activate a boolean in the inspector? i see this practice in another script. You put the boolean true and new variables see in inspector
I've only used OdinInspector for this, just a matter of adding [ShowIf(variable)]. It probably wouldn't be too hard to make a custom inspector with that functionality
OdinInspector it's a asset?
Yes
Free and has a showif attirbute
thank you
As you see in the video if i move the mouse fast its aiming correctly but if i move mouse slowly its not aiming.
How can i fix that?
https://www.youtube.com/watch?v=IlulWcTnn9Y&embeds_euri=https%3A%2F%2Fforum.unity.com%2F&source_ve_path=MjM4NTE&feature=emb_title
`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using StarterAssets;
public class Aim : MonoBehaviour
{
StarterAssetsInputs starterAssetsInputs;
[SerializeField] private LayerMask layerMask;
[SerializeField] private GameObject debugObject;
private void Start()
{
starterAssetsInputs = GetComponent<StarterAssetsInputs>();
}
private void Update()
{
Vector3 mouseWorldPosition = Vector3.zero;
Vector2 screenCenterPoint = new Vector2(Screen.width / 2, Screen.height / 2);
Ray ray = Camera.main.ScreenPointToRay(screenCenterPoint);
if (Physics.Raycast(ray, out RaycastHit raycastHit, 999f, layerMask))
{
debugObject.transform.position = raycastHit.point;
mouseWorldPosition = raycastHit.point;
}
Vector3 worldAimTarget = mouseWorldPosition;
worldAimTarget.y = transform.position.y;
Vector3 aimDirection = (worldAimTarget - transform.position).normalized;
transform.forward = Vector3.Lerp(transform.forward, aimDirection, Time.deltaTime * 40);
}
}
`
transform.forward = Vector3.Lerp(transform.forward, aimDirection, Time.deltaTime * 40);
Its probably this part, this isn't how you Lerp. Use vector3.rotatetowards instead. https://docs.unity3d.com/ScriptReference/Vector3.RotateTowards.html
No the GIF explains how you actually post code here in a code box with colours.
oh okey i didnt know that thanks
let me try rotatetowards 1 second
You can also read !code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
@main shuttle sadly still same problem
private void Update()
{
Vector3 mouseWorldPosition = Vector3.zero;
Vector2 screenCenterPoint = new Vector2(Screen.width / 2, Screen.height / 2);
ray = cam.ScreenPointToRay(screenCenterPoint);
if (Physics.Raycast(ray, out RaycastHit raycastHit, Mathf.Infinity, layerMask))
{
debugObject.transform.position = raycastHit.point;
mouseWorldPosition = raycastHit.point;
}
Vector3 worldAimTarget = mouseWorldPosition;
worldAimTarget.y = transform.position.y;
Vector3 aimDirection = (worldAimTarget - transform.position).normalized;
Vector3 newDirection = Vector3.RotateTowards(transform.forward, aimDirection, 40*Time.deltaTime, 0.0f);
transform.rotation = Quaternion.LookRotation(newDirection);
}
}
how do i access the effects with a script
Instead of doing stuff with aimDirection, set the rotation to aimDirection directly, do you get the correct rotation in your opinion then?
If that's the case, it's not the smoothing that's the problem, it's the aimDirection that's the problem.
Changing Volume Profile properties
Or the URP one, you can look that up yourself.
What networking framework is more reliable in terms of count of job offerings? Photon or mirror?
hey so i'm using addressables, and im releasing the loaded assets by Addressables.ReleaseInstance(), they are deleted from the hierarchy, tho the ref count in the profiler is stll 1 and the memory isn't released, why is that?
Hey guys, does anyone know if it's possible to query your project settings in scripts?
For example could I check the company name in the player settings?
Maybe ask in #archived-networking ? Also, why not just Netcode?
Iam using UniTask and with it iam trying to delay action, however if object is destroyed, how would i kill that task?
I tried creating function asnyc UniTask DespawnTimer but how do i kill that returned task?
If I store an IEnumerator, does it becomes null when the coroutine finishes?
I still have this issue guys, my triangle isn't being drawn
Here is the full script:
using UnityEngine;
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class ProcGrid : MonoBehaviour
{
public int xSize, ySize;
Vector3[] vertices;
private Mesh mesh;
private void Awake()
{
StartCoroutine(Generate());
}
private IEnumerator Generate()
{
WaitForSeconds wait = new WaitForSeconds(0.01f);
GetComponent<MeshFilter>().mesh = mesh = new Mesh();
mesh.name = "Procedural Mesh";
vertices = new Vector3[(xSize + 1) * (ySize + 1)];
for (int i = 0, y = 0; y <= ySize; y++)
{
for (int x = 0; x <= xSize; x++, i++)
{
vertices[i] = new Vector3(x, y);
yield return wait;
}
}
mesh.vertices = vertices;
int[] triangles = new int[3];
triangles[0] = 0;
triangles[1] = xSize + 1;
triangles[2] = 1;
mesh.triangles = triangles;
}
private void OnDrawGizmos()
{
if(vertices == null)
{
return;
}
Gizmos.color = Color.black;
for (int i = 0; i < vertices.Length; i++)
{
Gizmos.DrawSphere(vertices[i], 0.1f);
}
}
}
And screenshots:
Please someone help
Works fine for me, do you have correct material assigned?
You can also go into wireframe rendering mode and see if you see the edges
Aha ok there was no material assigned that's why
thank you, finally
Hi guys I have a problem , I download I asset bundle that it's a scriptable object with photos , text audio, all this works fine except the instiatiate for Android , in pc it works correctly if I make it instiatiate from start for testing in the correct place , why I doesn't work for the phone ?!
how would OnCollisionStay method work if there are collisions with multiple objects at once? if i want to know if there is a collision with certain gameobject, do i have to make a list and update it on collision enter and exit?
Test it (tm)
My guess is that it is invoked multiple times per frame for each object
weight painting is the way to fix this issue, but since im a programmer, not a 3d artist, i have never touched blender in my life, can someone pls help
if needed, i can send you the model if you need information
Vector Math question, need a bit of help on how to actually reason this out:
I have two objects on a board (made of grids), there is one instance that if one pieces moves into another that's staying still, a **shove ** would happen to the stationary piece.
So say the piece getting shoved is at (1,0,2) and the shover is at (1,0,1) - aka just below him, he would shove the piece to (1,0,3). The issue is that all pieces have a Rotation Quaternion to them. Suppose the shoved piece is looking to the right, it would therefore be shoved to its left. I'm not sure how to translate this in practice.
So in summary I end up with:
- Global direction of a shove for a given piece - e.g.
(0, 0, 1)from example above - A Quaternion Rotation (such as
Quaternion.Euler(0, 90, 0))
And I'm trying to convert the global direction above to the local movement for the piece, which in this case would be (-1, 0, 0). What operations would I need to accomplish this?
To add to the above, I tried using the omnicalculator, and when plugging in vector to be rotated as (0,0,1), around Y axis of rotation for a 90 degree turn, I ended up with the opposite result (1,0,0) instead of (-1,0,0). I'm also not sure what operation it did to acquire that result, however. Image below.
I'm assuming that what I'm doing is a local to global translation in this case, so maybe negating the answer would get the global to local instead?
hey there! does anyone know how AssetBundle.LoadFromMemoryAsync works? The description in the documentation is quite complicated
weight painting is the way to fix this issue, but since im a programmer, not a 3d artist, i have never touched blender in my life, can someone pls help
if needed, i can send you the model if you need information
this isn't really a programming question. you can use maya's character binding tools to generate better weights
what is your objective?
my friend gave me his game bcoz he stopped working on it
so im trying to understand how it works
private void RunDumbTests()
{
Debug.Log("RUN DUMB TESTS IS ENABLED! Disable it unless you're feeling DUMB!");
List<Tuple<Vector3, Vector3>> list = new List<Tuple<Vector3, Vector3>>()
{
new Tuple<Vector3, Vector3>(new Vector3(1,0,1), new Vector3(1,0,2)),
new Tuple<Vector3, Vector3>(new Vector3(1,0,1), new Vector3(1,0,2)),
new Tuple<Vector3, Vector3>(new Vector3(1,0,1), new Vector3(1,0,2)),
};
foreach (var tuple in list)
{
var bumper = tuple.Item1;
var victim = tuple.Item2;
var globalDir = victim - bumper;
var victimRot = Quaternion.Euler(0, 90, 0); // right
var localResult = victimRot * globalDir ;
var invertedLocal = -localResult;
Debug.Log($"Tried bumping from {bumper} to victim at {victim} with global dir {globalDir}" +
$". For a right turn we got {localResult}. Inverted it: {invertedLocal}");
}
}
When in doubt try it out, just need to plug in some example coordinates maybe I can learn from trial and error. Appreciate anyone with Quaternion knowledge to weigh in however ๐
you can use InverseTransformDirection to convert a world space direction to a local space one. but you are going to be moving in world space anyway, so it's a moot point. use DOTween for tweens (moving the pieces).
before you say anything more
look at the documentation for InverseTransformDirection
Might be worth checking out their implementation, thanks pangloss. I don't have access to transform, so will have to see if it's simple enough to do it myself (not using game objects for any of these due to network traffic)
Although I'm hoping I'm on the right track already with this and it's a trivial mathematical calculation.
do you have a screenshot of your game
It's not much to look at, I kept telling the artists to not get involved for now ๐
This is what I'm working with for the time being. Getting them to move and collide (shoved etc) correctly
This is a renderer element that takes a resulting board and generates game objects for it
try profiling a standalone player to make sure. otherwise, you should really not use addressables as a memory management solution, even though it is advertised as one
all computations happen server side, the hope would be they don't get coupled up with Unity, and so far has been relatively simple to find unity alternatives
what should i use then for memory management?
to load/unload things dynamically?
any recommendations?
what are you trying to do
what is the game
okay, right away
i can stop you there
you do not have to memory manage this manually at all
after the sequence ends, i want to load the next one and unload the previous one
you don't need to worry about the resource usage of this
i do need to wory about that
why
switch has limits of 3gb of ram
and right now it doesn't open on switch cuz of ram exceed
have you run a memory profiler on a standalone build
yes i did
and what did it say?
like i stated, it's not releasing the memory after doign Addressables.ReleaseInstance()
the enemies textures and animations
also frmo previous (unloaded) sequences
what size are they?
the issue is your texture settings
it always is in similar situations*
okay
you omitted the most important part
take a screenshot of the whole inspector, so that it shows (near the bottom) the actual selection of compression settings
here you go
you have to pull open the bottom drawer
where it says the name of the image
also, the Switch module is not installed
im not on switch branch right now
okay
which one exactly?
the compression method is set to Normal quality
Ive got an object with a cloth simulation (think a sheet of paper) when i shoot it holes are instantiated onto the surface. The issue is when i then move the cloth the holes remain where they were instantiated. How can i like attatch them to the cloth?
should i override the compression method for switch?
i agree it's confusing - it's where it says zamykanie oczu... at the bottom, at the bars
pull that up
on switch branch i have a switch icon down there
should i override the compresion ?
to none or something?
Have you tried using late update?
is it a visual novel?
we're develpoing a game for switch exclusively
it it a shooter 2D
uhhhh
cool
i dont understand what they mean by this, can anyone help lol
when i did the profiling, the memory used was like 3.4GB which almost 50% of it was the textures
even tho i unloaded the sequence (with the textures)
okay well fortunately a bunch of problems are easy to solve right away. i am a little confused why this is a giant black rectangle though
so they should release the memory
shouldn't there be like, the content of a terrain background or something in there?
late update happends late in the frame cycle so you can use that for stuff that needs to happen after other Update methods or physic actions
okay
i just wanted to show you the texture settings, dont mind that
and is this a pixel art game?
no
but how will this help with my like original issue with the cloth (if u go up like 2 replies)
i'd love to show you more unforunately i cannot due to NDA
I don't understand why he suggests it. It makes no difference here since it has nothing to do with what method you use.
oh, how would you go about doing this then?
it's okay - and also, art isn't really sensitive
because you're going to release the game and everyone's going to see the art anyway
I guess you need to figure out the position of your cloth at that frame, and move your hole to it
what are the things i can solve "right away" as you stated?
all you gotta do is google texture compression unity! a lot of these problems are easy to solve @deft timber
you will just learn what those import settings mean
alright i'll start from there
that will be the first step on the expanding brain meme
yea but different bits of it are in different places cos its a cloth sim
the second is realizing that the file format has nothing to do with the size in memory
That's the challenge ๐
You got the initial position, though
Can't you find the relative position and update it?
unity doesn't deliver a PNG in the player build
the fact that it's a PNG is meaningless
yea sadly our graphics 3d asset provider isn't the best one
i think it's going to be fine
a stone, which the enemies throw at you = 3milion tris
it sounds like right now you are doing tech art
but ofc we reduced it to 1k
Cloth sim positioning goes over my head so I can't really answer it
this is a 3d game?
it is a 3d game with 2D view
but the assets and models are 3d indeed
you should really aggressively search "Tech art for unity" and different tutorials for importing assets
Wasn't able to find their implementation, but by their own explanation it appears to be a simple inversion (negate everything) on the resulting Vector3. Having tested a few different inputs it looks like that's all I need - negate the result I got since I'm going from global to local, not the other way around! Cheers ๐
and see all the little details involved
it sounds like you already know a lot so don't sweat it
so it could solve the exceesing RAM usage problem?
where the textures takes roughly up to 50% of the used memory?
okay
because they are uncompressed and full resolution
an eye closing animation, for example, probably only needs to be 128x128 max size, and you can compress it
it might even look better slightly blurred
well ig i can just leave them full res on pc (maybe future steam development?)
and override it on switch
the switch has whatever, a 720p display
you shouldn't have a single switch texture above 1024x1024
but you also need to atlas, you need to set compression settings
got ya
the thing like the eye animation, it's 2 colors
so it can be stored differently
also in texture import settings
but now that you see that drawer, you know how large this stuff is
yea it's our first product on switch, we're still learning
you can also use the build report tools to see how things are shipped
yes don't sweat it
it's a hard one ngl, xbox is much easier ๐
but at least you're out of the hellhole of Addressables
yea they doesn't work like we expected it
there's just a lot of stuff you are describing that doesn't make sense, in the broad sense of your approach, and it's hard for me to help to do stuff that makes no sense
thank you for your time, wish you all the best
What doesn't make sense specifically?
you can build a Matrix4x4 instance and it has many of the same methods
it seems like moving the piece is a rendering concern
It isn't
like the specific thing you are trying to do
Movement / collisions will happen on the server, no rendering takes place
it's hard to succinctly say how wrong this all sounds
that is really hard to do
the moment you said collisions
It's not physics based, it's discrete collisions
There are predefined rules to how things can play out
Yes of course, I don't blame you for that. I think it would have been much to pitch a whole game to solve a minor issue ๐
is this a minor issue? the whole architecture sounds wrong
Does it? I never even mentioned the architecture though?
it sounds like it's a game where pieces move around a board, like a tactical combat game or similar
if i were building this networked, i would communicate the state of the game for the sake of simplicity, or differences in the state in the game, and a difference in the position of a piece would not be the relative change since the last state, but a "overwrite"
Server has a board and pieces it updates, it calculates and sends results to all clients which render them via animations or teleports (to catch up on background progress) where they are / end-up
Yeah it is a full overwrite
then it would always be a world space position
and the concern of animating between two world space positions would be rendering, and that would permit you to use a transform
Sure but I was asking about an implementation for server side collision resolution
you are saying server side collision resolution, which makes no sense to me
Sure it does. clients don't decide how they collide. Server does
you are using a physics word, collision, then you say it's not physics
They can insist all they want ๐
As in not physics simulation. It's not a unity collision trigger
just a collision of pieces moving to the same square
like i said, rendering the results of that is a rendering concern, you'd have transform
it doesn't really matter where the rules are resolved
you can communicate the world (or local) space positions of the rules, it doesn' tmatter
visualizing it you're doing on the client
it sounds like you are struggling with maybe resolving that rule?
and you're storing the orientation of a piece as a quaternion
which seems bad
you can store its transform.forward instead. then this will be very easy for you to achieve
quaternions are rendering tools...
transform is unity specific
well if you're trying to resolve the rules of how the piece is bumped
i think you store the rotation as a vector3 direction where it is looking
and your problem is solved
it can even be a vector2int.
Pieces can rise and fall on the board
i can tell you think saving space on these types over the network is going to matter - it won't
okay well
i don't know, what's your goal? use Matrix4x4
it has all the methods for this
go for it
For what advantage specifically?
I don't understand why the rotation of a piece determines where it gets shoved. Isn't it just based on the relative position of the shover?
Could be worth pursuing if there's a useful benefit
it sounds like the user wants to send realtime position and rotation updates from a server, and reimplement some part of the rules of scene hierarchy
it is, but all pieces move based on primitive behaviors (can be a rotation, a cardinal movement and other special behaviors they can carry out on the board)
so when a piece gets shoved, it will own that behavior as part of its primitive set. Which it will then execute in sync with all other pieces
and the wisdom of recreating unity in a headless backend... is limited
it sounds like you are a lot more interested in the networking science of all of this
Well, I think this has gone a bit beyond being critically helpful. Thanks for the inverse transform. I'm not exactly planning a redesign of architecture on a prototype
i'm not sure if there's any value in trying to recreate a scene graph in pure c# on a headless backend server
if it were a prototype, you'd be making this a local multiplayer game
and use the unity rules as is
it is currently lol
then why are you networking anything
it's not yet
i see
i think there are a lot of surprises and confusions here. it's hard to give good advice without seeing more of the code. you can look at Matrix4x4
Help im a newbie and dumb
Sure, sounds like a fair suggestion. Will take a look, thanks.
before you say anything more, look at it.
lol
Halp
Do what it says ๐
you should be looking at your console window in Unity
good
now fix those compile errors
and make sure your class names match your filenames
because EventManager and NewBehaviourScript do not match.
those errors in particular seem to be that you have two scripts with class NewBehaviourScript
damn
but It says I have 8 errors in visual studios but nothing is highlighted in red
Hey everyone, I need some thinking help about trigonometry and scrollview scripts... I am using this extension script here https://gist.github.com/yasirkula/75ca350fb83ddcc1558d33a8ecf1483f to center the scrollview to a specific child. This is working perfectly. But as my map will also rotate, I get some weird offsetting from this script. I was trying to add the rotation with a vector but I cant really see a pattern and not even sure, I am using the correct setup of scripts and recttransforms right now. This code is just prototype code, so do not worry about structure ๐ This is what I am using right now scriptwise: https://hatebin.com/epellljqgw
you should at first not work with the default script name of NewBehavourScript
this one isn't but a different script is
lol
but what does that have to do with my script having an error
Unity cannot compile anything as long as ANY script has an error
oh wow
The compiled results of all the scripts go into one file called an "assembly"
if there are broken scripts the assembly cannot be built
#๐ปโcode-beginner i like the unity tutorials on kodeco
formerly ray wenderlich
they are written you will thrive
btw has anyone here done world streaming?
Does anyone know why the Instantiate Map Objects is not appearing?
like in the tutorial
Are you getting any errors in the console?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
just warning
but in visual studio it shows 8 errors but its weird because it says 0 issues found
Yeah, those errors will be why it's not working.
Are those errors in the file that you have currently open?
I'm not sure if this causes errors or not, but you've put the script in a folder called Editor, yes?
This is MapDataInspector.cs?
yep
Custom inspector scripts need to be in a folder called Editor.
why
I think the script has to be in the root Editor folder, you can't have subfolders in it.
I may be wrong on that.
Hello, i have a procedural generated map using corridors & rooms linked together, what would be the best way to optimize the performances plz ? i currently have a big box collider trigger in each rooms / corridors prefabs and when i enter inside the trigger, the room/corridor loads, and unload when i exit the trigger. But i don't know if that's the best way to do
using UnityEditor; do you have that?
AssetDatabase is part of the UnityEditor namespace. Did you add that?
I should note that this code will not run in a build application. Are you aware of that?
Good point.
Look into Resources.Load
hey,
are all classes convertible to UnityEngine.Object ?
is it possible to convert a customClass to UnityEngine.Object ?
No, only those which derive from UnityEngine.Object
Custom MonoBehaviours and ScriptableObjects are UnityEngine.Object
Thanks โค๏ธ
Hello there, this is kinda a beginer question I guess, how can I retrieve the vertices of a mesh only if they dont have the same position as another vertex?
What are you retrieving them into?
you'd have to check them against the other vertices you've already looked at. Perhaps using a HashSet
Lets take for example the default cube, it prints 24 verts (I have already read the theory behind it) but I only want to print the 8 verts it should have visible
Into a native array
what's the ultimate goal with this code?
Like Praetor said then. Check them against the vertices already stored, and if the position matches any of them continue.
I basically want to spawn "Nodes" over the vertices of a model. My issue is that the code generates more nodes than necesary into the vertex positions as using mesh.vertices returns vertices per face
Let me try
Wouldn't it make more sense then to check the nodes you've already spawned rather than the vertices?
for what purpose though? Do they have to match the actual vertices in the model, or are you trying to calculate a Hull?
Like "if there isn't already a node here, make one".
@everyone Is anyone are able help me with this: #archived-code-general message
Dont think so, I want to spawn just the right nodes quantity, I dont want to spawn all the nodes and then check if they have repeated positions, it wont be efficient
Just a hull
I don't think I articulated that properly. I meant loop through the vertices but check the nodes you've already created to see if you should create one, rather than looping through all the vertices you've looked at.
So maybe think about using a convex hull algorithm
With a HashSet you wouldnt have to loop anyway
I can not use shaders. I am able use GetPixel and SetPixel methods but image has still colors.
HashSet would be easy but it will also only work for identical vertices and not close vertices
the thing here is that im using ECS, so I cant retrieve data from a node I create, I can't do for example if(newNode.position = x)
Ah, fair enough then.
Hold on I will send a picture to better understand
Not sure if there's a way where you get around the read/write enabled restriction.
One possible way I can think of, is duplicating the texture asset via code, maybe that would let you set isReadable to true, then you could edit it?
I suggest you ask this in #โ๏ธโeditor-extensions
So, my code currently does this
it spawns nodes over the vertices of a mesh, since this is a cube, it should have 8 nodes, right?
4 on top 4 on bottom or from which side you want to look it from
One at each corner, basically.
Yeah, exactly
I have some code that continuously writes to a texture, but has no need to read from it. I use a coroutine that updates a fixed % of pixels, then updates the texture and waits for the next frame. Itโs still quite slow and was hoping to get general ideas on how I can more efficiently approach this problem
but my code instead of spawning 8, it spawns 24 because of 6 faces having 4 vertices (as I understand, unity mesh.vertices algorithim reads faces too, so since there are 6 faces and each face has 4 vertices, it reads 24 vertices in total)
stupid question - is the mesh always going to be a cube?
No, its not
its a complex shape
so what are these nodes for
Sadly modifying textures on the CPU is going to be slow. Maybe a compute shader or some normal shader with Graphics.Blit would work better.
You could toss your code here though so I can see if theres anything to optimize
Let me upload it one sec, thank you ๐
Hmm, but isn't there a method in arrays for checking duplicate positions or how can I do this with a for loop?
Sorry, Im really bad at loop math, so I cant quite figure out how to do it myself ๐
IEnumerator UpdateCloudMap()
{
yield return new WaitForSeconds(0.1f);
const int _cloudRes = 344;
Texture2D _clouds = new(_cloudRes, _cloudRes);
DigitalRuby.WeatherMaker.WeatherMakerFullScreenCloudsScript.Instance.WeatherMapOverride = _clouds;
while (true)
{
for (int j = 0; j < _cloudRes * _cloudRes; j++)
{
float maxIntensity = 0f;
int x = LehmerRandom.Next((_cloudRes * _cloudRes) - 1);
int y = x % _cloudRes;
x = ((x - y) / _cloudRes);
for (int i = 0; i < _cells.Count; i++)
{
// Get tornado position and intensity
Vector2 tornadoPos = _tornado.GetPosition(i);
float tornadoInt = Mathf.Clamp01(_tornado.GetCellFraction(i)); // KEY:OFFSET
// Get (potential) cell texture coordinates
int cellX = WorldPosToCellPos(CloudPosToWorldPos(x, _cloudRes), tornadoPos.x, _hookPositions[i].x);
int cellY = WorldPosToCellPos(CloudPosToWorldPos(y, _cloudRes), tornadoPos.y, _hookPositions[i].y);
if (cellX < 0 || cellY < 0 || cellX > _cellSize || cellY > _cellSize)
{
continue;
}
float cellVal = Math.Max(0, _cells[i][cellX, cellY] - (1f - tornadoInt));
if (cellVal > maxIntensity)
maxIntensity = cellVal;
}
float cloudInt = Mathf.Clamp01((maxIntensity * 1f) + 0.6f);
Color color = new(cloudInt, cloudInt, cloudInt, 1);
_clouds.SetPixel(x, y, color);
if (((j + 1) % 1376) == 0)
{
_clouds.Apply();
yield return new WaitForEndOfFrame();
}
}
}
}
yup
I already suggested using a HashSet above
the very first response to your question
The Lehmer RNG just allows me to update the pixels in a random order, otherwise there's an obvious "scan line"
But without repeats/missing pixels
why
Unity does not include UnityEditor methods in a build
wow
So you need to make sure scripts that include it are excluded, or you make sure any editor methods are not compiled, which is also possible but your behaviour must still work, obviously.
so im doing this all for nothing basically
I'm sure there is another way
Already suggested the right way to do it like an hour ago
not exactly a coding question but need confirmation. There are 24 unique rotations when rotating on an axis by 90 degrees at a time right?
4 rotations when pointing in a direction times 6 axes is 24 rotations, even though theres 64 combinations of eulerAngles where x y and z are 0, 90, 180 or 270.
sounds about right. 4 orientations per cube face
6 cube faces
24 orientations total
One thing you could probably improve is using SetPixels right before you Apply, instead of repeatedly using SetPixel in the loop
Using SetPixels can be much faster than calling SetPixel repeatedly, especially for large textures
https://docs.unity3d.com/ScriptReference/Texture2D.SetPixels.html
Still though I suggest looking into shaders
nice thanks
euler angles cannot be trusted as every orientation can be represented by an infinite number of euler angle sets
Welp, this solved my problem!
makes sense. Ill stick to quaternions.
is that like Addressables?
cause I can't find anything on YouTube about it
You should check the Unity manual before YouTube
hey,
reorderableList has a call back for Onchange ChangedCallbackDelegate(ReorderableList list); ... I'm not sure how is to use this ? I wanna know how to get which item has been modified and react based on that piece of info
damn
this is hurting my brain lol
im more of a video tutorial guy
Programming in general is a very text based practice
you should get used to reading and understanding documentation
Would addressables be an alternative to world streaming?
Completely orthogonal topics
fk
hey,
i have some custom properties that was created by custom editor using EditorGUI.PropertyField() it look nice , but I cant edit them in the inspector , is there is a reason for that ?
So what's actually the best way
that would work in a build
very east method instead of creating 10 scripts
The best way for what
So, I know how to raycast through the camera and find out what your mouse cursor is over, but how would I go about finding out where the mouse would cross a plane at y=0? I want to have a fallback in case there is nothing under the mouse without having an infinite collider across the world at y=0
Check out Ray Plane intersection, where your plane is with normal (0, 1, 0) and pick a point any point where y = 0
https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-plane-and-ray-disk-intersection.html
Ah, perfect. And it reuses the same ray, so I can just pop it in the else of the initial raycast. Thanks!
Resources.Load was suggested to replace your use of AssetDatabase, not the entire world streaming setup you copied from a tutorial
It's the simpler version of Addressables
and basically does what your AssetDatabase code did
but at runtime
and is actually simpler than the AssetDatabase code
I've successfully tested embedding content within assemblies as well as an additional avenue to use if Resources.Load is not preferred
Oh, shoot, for some reason I thought that was a static method. I don't actually have a plane, I meant like the mathematical concept of an infinite plane at a specific height. I guess I'll have to use the math @safe knoll provided or just make a plane
just create a plane in the code
Unity Addressables is a powerful asset system available as a package in Unity and today I provide you with a new video where I show you how to install the Unity Addressable plugin, how to configure addressable groups, how to add assets to your Unity Addressable settings, and lastly how to load and instantiate objects via script.
Project shown i...
Found this
Ah, it's a different plane than the plane primitive, okay that makes it viable again
you can just make a Plane struct to use that it's just a little struct so doesnt need to hang about. the math is pretty simple too from that website if you're curious.
For some reason, my code doesn't run as intended. I wanted to make a point that appears where the raycast hits. It instanciates correctly and updates, but it doesn't get destroyed later. What did I do wrong?
RaycastHit2D hit = Physics2D.Raycast(transform.GetChild(0).transform.position, transform.right, LaserRange);
if (hit.collider != null)
{
// If the circle instance doesn't exist yet, create it
if (circleInstance == null)
{
circleInstance = Instantiate(circlePrefab);
}
// Update the position of the circle instance to match the point of contact
circleInstance.transform.position = hit.point;
}
else
{
// If the raycast doesn't hit anything, destroy the circle instance
if (circleInstance != null)
{
Debug.Log("It should be gone now!");
Destroy(circleInstance);
circleInstance = null;
}
}
I don't even see the log message
If you don't get the log then the condition is never true. That means either your ray is hitting something or circleInstance is null
Have you checked to make sure your raycast isn't hitting anything?
Hmm, I added Debug.Log(hit.collider.gameObject.name); after raycast and it sends me the message that it is null.
In Debug tab I can see, that circleInstance is not empty and has a gameObject
After the else, try logging circleInstance before checking it
If you get a log, then the else is running. If you get a log, but it's blank, then circleInstance is null
Weird, because it works perfectly now. I moved the first log I mentioned to execute after if and added the second log in else as you said.
Anyway, thanks for the help. It's working now
Yeah it works because if the log was this here: Debug.Log(hit.collider.gameObject.name);, and the raycast didn't hit, it would throw an exception, ending the script execution right there
So, not running anything past that line
Would this work for world streaming alternative?
fk
Do you just keep forgetting conversations you recently had
ya
Is there a way for Raycast to ignore colliders with certain tag?
only layers
how?
no - use a layer mask to filter by layer
Thanks, I used the "Ignore Raycast" layer and it works
damn im fked
@copper shoal but in theory u can make function with Physics.RaycastAll and u can use tags
my b
Hey guys does anyone know why the skinned mesh renderer randomly unassigns bones after a frame
Im breakpointing my code and i can see clearly the bone has been set
But then when i continue it randomly says missing transform on the root bone on the skinned mesh render
even though the bone is already there
//Get meshes and bones then copy them to the new mesh
foreach (var kitsuDnaData in groupedKitsus)
{
var p1 = kitsuDnaData.Key;
var clonedGenZero = p1Instances[p1];
var config = resourceMap[p1].Config;
var partsInThisKitsu = kitsuDnaData.Value;
var meshes = partsInThisKitsu.Select(t => config.Elements.FirstOrDefault(v => v.Key.ToLower() == Part.GetName(t.PartIndex).ToLower()))
.Where(t => t != null)
.SelectMany(t => clonedGenZero.transform.FindGrandChild(t.TransformName)?.GetComponentsInChildren<SkinnedMeshRenderer>())
.Where(t => t != null)
.ToList();
var bones = meshes.Select(t => new
{
Transform = t,
RootBoneName = t.rootBone.name,
BonesName = t.bones.Select(t => t.name).ToArray()
}).ToList();
foreach (var mesh in meshes)
{
var newMesh = Instantiate(mesh.gameObject, go1.transform);
newMesh.transform.SetParent(go1.transform);
newMesh.name = mesh.name;
var newMeshRootBone = rootBone.FindGrandChild(mesh.rootBone.name);
var newMeshBones = new Transform[mesh.bones.Length];
for(int i = 0; i < mesh.bones.Length; i++)
{
newMeshBones[i] = rootBone.FindGrandChild(mesh.bones[i].name);
//newMeshBones[i].position = mesh.bones[i].position;
//newMeshBones[i].rotation = mesh.bones[i].rotation;
newMeshBones[i].localPosition = mesh.bones[i].localPosition;
newMeshBones[i].localRotation = mesh.bones[i].localRotation;
}
newMeshRootBone.localPosition = mesh.rootBone.localPosition;
newMeshRootBone.localRotation = mesh.rootBone.localRotation;
var skm = newMesh.GetComponentInChildren<SkinnedMeshRenderer>();
skm.localBounds = mesh.localBounds;
skm.bones = newMeshBones;
skm.rootBone = newMeshRootBone;
}
}
For a single frame the model is OK hence why i can get a screenshot
But no clue why its randomly unassigning the bones
"missing" generally means the object was Destroyed
are you changing scenes or anything like that
im not
all im doing is instanting a new model. Taking the skinned mesh renderer and component from that model and adding it to a new one
Then im also taking the bones required for that skinned mesh adding them onto the new armature then setting the new skinned mesh renderer with the bones
its weird as hell
1st frame its fine 2nd frame its all deformed
var newMeshRootBone = rootBone.FindGrandChild(mesh.rootBone.name);
well first off what's FindGrandChild?
so yeah this "rootBone" is actually the new armature
/// <summary> Find the first transform grandchild with this name inside this transform</summary>
public static Transform FindGrandChild(this Transform aParent, string aName)
{
var result = aParent.ChildContainsName(aName);
if (result != null) return result;
foreach (Transform child in aParent)
{
result = child.FindGrandChild(aName);
if (result != null)
return result;
}
return null;
}
Iterates through children
why do they make this hard to do world stremaing damn
You are trying to do an advanced thing as a beginner.
It is going to be hard
nobody "made it hard". It just is hard.
the issue is that also there are not many tutorials on World streaming on YouTube
https://www.youtube.com/results?search_query=unity+world+streaming
I get hundreds of results with this search
Also again YouTube is not always the best resource.
they are either too old or use paid 3rd party ressources from the asset store
doubt most of them are too old
What exactly makes you think they are too old
they won't be using anything that has changed too much over the years.
the one I was watching that was somehow decent was great until the database error
so I had to stop
If you're doing an advanced topic like world streaming you should be able to work through errors
@swift falcon World streaming is more appropriate for open-world games. Its overkill for the office space scene you showed. Addressables is probably a better option for you
ya that's what im thinking too
Will that do something like World streaming but without making things disappear and reappear like loading?
@simple egret hey man i couldent figure the last part out r u busy? l ike followed your equation and it snaps perfectly buthow can i get it to go in between the points as well
It really depends on how you implement. Based on that screenshot and the details youve shared, Id bundle assets in based upon which room they go in. And depending on proximity load/unload the appropriate assets.
Is there an easy way to do something similar to Gizmos.DrawMeshCube that would not draw over everything else? I'm trying to work on my debug visualization for an octree and it tends to devolve into a sea of color since I can see the mesh cubes through objects. Do I need to handle this myself if I need them not drawn over objects they are behind or am I missing an easy way to do this?
;{
I have a script of a bullet that follows an enemy. If the enemy dies the bullet stops at it's corpse. How can I make the bullet keep it's direction and not stop?
unity is bugging out
even the parent is correct
can duplicate naming of components cause a issue?
cause i clone bones then rename them to the original clones name, but they are parented to a different parent
youd have to detect the death and then tell the bullet to just continue straight (stop giving it turn commands)
each bullet should have a target associated with it so you can check if that monobehavior property indicating death has been set
To follow the target I am using Vector2.MoveTowards. How can I tell him to just continue straight?
i dont recall exactly what you need (still learning) but instead of that MoveTowards, you basically need to tell it to just move in the direction the bullet is facing as soon as death is detected and then give it momentum
not exactly what you need but should help point you in the right direction
Managed to solve my own issue. It seems Destroy does not destroy the object so it was picking a old bone
When i used DestroyImmediate it worked
I tried this but it looks like Vector2.MoveTowards does not update the velocity in the rigidbody for me to get it from there.
What would make doing Task.Run(() => Function()) stall the main thread for a bit?
AddForce?
rb.addforce
yeah, thats my suggestion for him
what's more readable? or maybe a better question is how would you prefer a colleague write this if it was code you both had to work on? (generally speaking)
result = x > 0 ? "positive" : "non-positive";```
```cs
if (x > 0) {
result = "positive";
} else {
result = "non-positive";
}
im not used to this operator and if and else just seems like more plain english but one line is so much more concise
It's a preference question indeed. I find the first one more readable, as its a pretty short ternary
https://youtu.be/8YAfqUhW6cM
can anyone please help?
When i click inspect my item OR whenever i have something where pausing disables the players movement this spinning thing sometimes keeps happening. I've tried everything but nothing seems to work, even asked chatgpt for help. Here are my movement, look and disable scripts.
ty for the input @hexed pecan @lime grove
Can someone help me out with a problem please? I have a unit that can stand, move, attack and cast spells. This is implemented with a state machine. The problem is I want some of my spells and attacks not to interrupt the current state and order.
My current implementation:
Player Controller checks for player input and sends an event with the relevant data
UnitManager switches to the relevant order based on the input (move order, attack order, etc)
Order is calling the necessary state. For example, attack order will check if the unit is in range do the attack. If yes, the unit will attack (attack state called) , if not, it will move in range (move state called) . Order will function until new order is given.
The state is responsible for animation and calling the systems. I am using Animancer to use custom code to call animations. For example, the state will play animation attack and on certain animation time line call for a system that fires a projectile
Just a guess, on you rigidbody, have you locked your rotation?
if I cant do ParticleSystem.main.renderer is there another way to access it from the particle system or do I have to use ParticleSystemRenderer?
hey,
I'm trying to replace EditorBuildSettings.scenes with a new list of scenes.
so I made a new list List<EditorBuildSettingsScene> SS = new List<EditorBuildSettingsScene>();
then I added all scenes and i can see them via the following loop
for (int i = 0; i < ss.Count; i++)
{
Debug.Log($"I:({i}) _ path : {ss[i].path} _ Count:{ss.Count} _ enabled: {ss[i].enabled}");
}
everything is correct, the right count , the right enabled value with the right path.
then to store it on EditorBuildSettings.scenes and replace the older list i use the following command EditorBuildSettings.scenes = SS.ToArray();
It didnt work! , the list has been rest ( all changes i've made have been returned back )
so i stored it on an array instead and looped throught it EditorBuildSettingsScene[] newArray = SS.ToArray();
for (int i = 0; i < newArray.Count; i++)
{
Debug.Log($"I:({i}) _ path : {newArray[i].path} _ Count:{newArray.Count} _ enabled: {newArray[i].enabled}");
}
the order is not correct , the enabled value are all true , why ???
When I scale UI elements and set them to zero, it seems they are not rendered. So, I do not need to set active to false or disable image component?
The visibility is based on the distance to camera. I scale UI elements and finally I want to hide them
I feel like setting UI element scales to 0 to hide them would be unconventional. But if this accomplishes what you want, don't let anyone stop you lol. I would probably just use a CanvasGroup though.
Canvas group for each element?
For whatever elements you're trying to hide. If you have multiple sibling GameObjects in your UI that all need to be hidden, you can use a single CanvasGroup on a parent GameObject.
I keep all of them in one root
I can have two parents, one for active and the other for inactive elements, perfect.
ActiveParent
InactiveParent --> canvas group:0 or disabled game object
Oh, yeah. If enabling/disabling your UI GameObjects won't have any side-effects on your project, that'd probably be simplest way. Just re-parent them from an active to an in-active parent, and then back.
no, you put the group on stuff you want to hide, then use it to hide via its alpha, if you disable a component its quite expensive to turn it back on, you'd use a sub-canvas and toggle the canvas component to disable the renderer without triggering a refresh of all children
I like using the CanvasGroup alpha because it's quite clean and won't cause any side-effects like running my OnEnable methods.
in any case, scaling of UI elements is generally a very bad idea as the whole system is unaware of scale
Yes, I mean create two sub canvases for each (active, inactive elements) but I think canvas group and set alpha to zero is OK as well
you can use it as a temporary effect but should always return to a 1.0 scale as soon as you can
you should not move around ui objects (reparent them) a lot
Also keep in mind that if your UI elements block raycasts, they will still block those raycasts with their CanvasGroup alphas set to zero. So you may or may not want to also toggle the blocksRaycasts property on CanvasGroup as well, depending on your context.
So, you say reparenting is expensive as well like set active
So, add canvas group for each UI element and just set it to zero or 1
yes, its best to just use a canvas group or a nested canvas to control visibility and break the refresh-cascade in well defined places
Another way is to set the position to another place but I do not prefer it
if you need your layoutgroups to respond to the visibility you need to disable to game objects ofc, there is no cheating that
Set scale to zero is OK because I adjust their scales based on the distance to camera, to hide it set them to zero. I did not get why you say it is a bad idea
They are a bunch of world space Icons
like gizmo
because the ui system does not observe scale as trigger to refresh itself
like it does with size
and the whole point of a rect transform is to be able to define an arbitrary rect without abusing scale
OK, multiply width and height and finally set them to zero
however if you do scale your rect transform, and then trigger a layoutgroup, everything goes wonky
๐
Layout group?!
Why do you assume I use layout?
if you mean unity UI layout group component
Unity/Physx use AABB for collision resolution right? Can someone explain how this works if the box itself never actually rotates?
Like if I have a box collider on a cube and I toss it around, obviously it's rotating
like how does corner detection work then?
layout groups are a core part of a usable ui, most people use them in some way, so its a reasonable assumption you would too
The box itself rotates. The AABB does not
By "box" you mean the render right?
It checks AABB first
it uses the AABB to figure out collision candiates quickly
There's the collider itself, and the AABB completely contains it
oh alright
the AABB is like a bigger box that holds the small box of the box collider
when the box collider is rotated, the AABB is larger than it - since it can't rotate and has to encompass the whole thing
So after the quick AABB is done, is separating axis theorem then used to complete the query?
So like when the box collider is rotated the AABB will be the larger outer rectangle in the image on the right^
depends on what the collision behaviour is expected to do, the AABB lookup is used as a fundamental part of all physics queries
every collider type implements the narrow phase differently.
Ok cool
I think there's actually a different implementation for every collider type pair
Yes but as I mentioned they are world space icons in the world.
lik gizmos/icons in unity editor
so like:
Sphere - Sphere
Sphere - Box
Sphere - Capsule
Box - Box
etc...
so you are actually just scaling the whole canvas of each of these icons? not a child of a canvas?
In non convex models, in final check, it tests all faces, right?
Scale each icon, yes based on the distance
Now, I have just one canvas
icon != canvas
Canvas
parent
icon1
icon2
...
is this a 2D or 3D world?
in most cases each individual thing (like your icons) in a world UI should be its own canvas
World space 2D icons in 3d world
those should all be individual canvases
What?!
Canvas1
Canvas2
...
?
well, if you need them to be canvases for convenience, then yes, if you care about performance, make them simple sprite renderers
One canvas is more performant than several canvases
just one drawcall
OK, thanks
No, sprite renders do not work. They are icons and should be rendered on top like UIs
you may want to read https://unity.com/how-to/unity-ui-optimization-tips
draw-calls aren't the bottleneck with UI
What is a good way for enemy objects to find the player object? Finding the object from the hierachy seems inefficent and unnecessary, because every enemy instance would have to search for the player themselves, when all they need is a reference. This reference could be provided somehow from somewhere, but how? A static player reference on a static class? That seems dirty.
Use tags.
you'd typically have enemies do a physics overlap-check or raycast of their vicinity to find any potential targets, if you want to give them a static reference to the player, assign it in the editor or inject it through the same script that spawns the enemies
GameObject.FindWithTag("Player")
You mean give the player a "player" tag, then call "FindGameObjectsWithTag" on each enemy instance to find the player? My problem with that is that every individual enemy would call "FindGameObjectsWithTag", even though that shouldn't be necessary.
I'm not trying to create complex AI system where some enemies know where the player is and some don't. I would just like to place enemy prefabs into my scence and when I start the scene, they should just know where the player is.
is this a prototype?
OK I should add that my player object doesn't exist right away. I place an object which designates a spawn location for the player, the player is then spawned there when the game runs.
Uhm, no I wouldn't say so ๐ Just a simple game
An arena shooter where you spawn and a lot of enemies attack you all at once, nothing special (learning)
You could still add an assignable player object field to your enemy script and set it to the player prefab, then have the enemy check whether that object exists in the scene.
if you care about architecture at all, you'd not use tags, you'd have the enemies register on start with an enemy manager and that enemy manager would inject them with any references they need, same with the player when it spawns, then you'd have a third system that would handle communication between enemy and player manager, i.e. telling the enemy manager that a player spawned which would then tell the enemies
yes I do very much care about architecture, which is exactly why I ask this question ๐
Enemy manager is a great suggestion then.
How would the enemies register themselves on an enemy manager?
Provide a public registration function on the manager script that the enemies can call when created.
which means the enemies need a reference to the enemy manager, so every time I create a scene, I have to put in an enemy manager, and for every enemy I place, I have to drag and drop the enemy manager onto the enemy?
that enemy manager would have to be injected into the enemy by the enemy spawner or you need to find it via some form of FindObject<EnemyManager>() or use some singleton service locator (many consider this an antipattern)
if the enemy spawner injects it, then the spawner needs a reference, that just moves the problem to a different location, I want to avoid "Find" methods (except they are the standard way of doing things?), I don't want to use singleton pattern for the reason you mentioned
essentially having enemy instances saved in the scene breaks clean architecture in some way, you just need to ignore it and use the crummy options you have to resolve that
You're basically not going to be able to do this without some form of reference in one direction or other, so pick which one you dislike least. ๐
you can't avoid find methods if you save instances in the scene unless you want to manually assign references to them in the editor
I mean, if I use one of the Find methods, then all of my problems are pretty much solved, I just read and heard here and there that finding objects is expensive and in this case it's kind of unnecessary, but maybe it's the way to go?
note that you should only avoid find methods at runtime after scene load. they are fine during init. you'd also never use them as a hack where better patterns exist, for some things however they are the only option
Couldn't you have your enemy spawner find the player object on Awake/Start and then pass that reference to enemies when it spawns them?
hey,
how to add item to the bottom of a list ?
the problem with find methods, architecturally, is that they couple your enemy implementation to the context they live in, and you want to avoid that as much as you can
.Add()
I don't really want to have an enemy spawner, or rather, I don't want to make an enemy spawner mandatory, I also want to be able to just place enemies as is.
it doesnt work with me , it keeps getting messed up
Didn't you say enemies would be spawning during runtime though?
some will spawn during runtime, some will be there right away
your options are "find", "singleton manager", "manual editor assigned reference" and "singleton service locator"
maybe I should spawn all of them during runtime, maybe thats better, I dont know
It depends on which solution you decide to go with I guess.
i have a list that i want to convert into array , as soon as i loop through it , the order of the items changes
How are you currently trying to do that?
being able to save them in a scene is very useful for iteration and testing, you should keep that as an option
int[] foo = myListOfInt.ToArray();
List<Custom> newList = new List<Custom>();
for (int i = 0; i < script.oldList.Count; i++)
{
FnTypePi p = script.oldList[i];
p.enabled = script.oldList[i].enabled;
newList.Add(p.Settings);
newList[i] = p.Settings ; // in attempt to keep item with index 0 to be in the newList[0] ... it keeps changing
}
after that I'll convert newList to array but this loop is running on the editor and everything is missed up there
u are talking about Arrays
lists has defined order, correct?
They both do.
both list and array have a defined order
Can someone explain ECS / Cache friendly designs?
I understand that we're supposed to have a main "entity" and a bunch of components in a data container attached to it, but I'm still having trouble wrapping my head around what this does for the cache.
Is the idea just to have a small base entity, so that it easily fits in the cache? And then always access all entities frequently so they stay in the cache?
Aren't lists not indexed? I must be misremembering, sorry.
Keep it in a mono then send it to every enemy
I honestly just think its the editor, its not as good as the rest of the engine
what do you mean with "send"?
what I wrote up there should have been enough to reorder the list correctly
Custom[] newList = oldList.Select(it => it.MemberWithReturnTypeCustom).ToArray();
When enemy instantiation
I''ll try that , thanks ๐
You can keep the player ref on that spawner class, then instantiate enemies and call init method of Enemy mono class and finally pass the player ref to them
yeah but in that case every enemy needs to be spawned from that spawner, I loose the ability to just place enemies as is
It is better than find game object with tag in my view.
If the player is single, probably find gameobject with tag will be OK too
player is single yeah
A simple static reference could work
it does! but everyone tells me static classes are bad!
Ask them why
You can keep spawn point in your scene
Then instantiate your enemies in runtime
Also do you mean static variables, or are you using an actual static class?
Yes, baddd
entities arent things, they are just identifiers (a simple int), stuff isnt attached to entities in an OOP/compsition sense, data is attached to entities by making a list of all data objects of a given type and associating that list's entries with entity ids (for example by using a sparse set), the cache friendlyness comes from this: when using that data to process a system, you can iterate through a tightly packed region of memory that ONLY contains the data you need for processing, no extra, superflous data, in consequence, more useful data fits into each cache line which means you need to request fewer pages of memory from RAM.
I'm not using anything, but if there was a static property somewhere, every enemy could reference that static reference. Which is what you mean right? It could be a static class on a script that does not live in the scene, or it it could be a game object which has a static property
Yeah just making sure we are on the same page.
Probably no need for a static class, just a static variable on the player class for example
Then every script could have a reference to that player script? That is good?
If that's your intended purpose of it (it is) then yes
Maybe make it {private set; get;} so that other classes can't modify it
The scope is global and it is generally bad
Why
For simple indie games it is completely perfect
it solves all of my problems, but you are right, the scope is global and people want to avoid that
imagine it's not a simple indie game
The rationale I usually see behind it is that if you end up accidentally modifying the global state from somewhere you didn't mean to, it's a lot harder to troubleshoot when things start going wrong and you forgot where you changed it.
Hence this
How can anything modify it if its setter is private
if you understand the singleton pattern this is a fine approach, its not bad when used to implement a service locator or hook up the initialization routine of your project. Singletons are bad when used as shortcuts form inter-object communication.
Yeah, I agree with you. I'm just saying what I've seen people say about it. ๐
isn't singleton an anti-pattern? ๐
its an antipattern to use it for the wrong reason, its a perfectly valid patter for its intended purpose.
it didnt work :S .. i looped after the code to see the order of each item in the array compared to that of the list and yea they dont match :S
the intended purpose is to capture the notion of "only one thing of X can exists", the anti-pattern is "give access to everyone, anytime, anywhere"
editor is full of bugs
that is not possible
its
Because every time you have a global scope class, you finally face big giant God class specially for junior developers.
I have faced in my team, my colleagues
It is one of drawbacks
With god class you mean some super game manager that has every reference possible?
I'll give u a console print out and i've only used ur code, but allow me to hide some personal info
If you have a singleton class, you can put everything there, yes if you are lazy
Then dont be lazy?
I dont see the logic here
they mean everything will have a dependency on that one god-object and thus refactoring and changes get harder to make, introduce more bugs and make communication about changes way more tedious
Say I change it in the future but wont
Yes I see why that would be a problem, but that's way out of proportion here
I have my own way
We are talking about one static reference to the main player
@whole gull Go make your game
๐
Is there a way to do a "ConeCast"?
So would these lists be stored in like a static class somewhere?
i think in a prototype one should do whatever gets it done quickest, but the mindset that results in bad architecture starts with this
I wanted to do something that'd detect certain enemies within a cone from my player controller.
However, there seems to be no native "ConeCast" function, and I don't think it's possible to have the sphere projected by a SphereCast increase in radius as it's projected further from its origin.
it makes sense to gently train oneself to use better patterns so the prototype-think doesn't become too hard to break come production time
Sphere overlap + filter by angle/dot product.
Could you elaborate, please?
Oh wait... ๐ค
That would be ConeOverlap though
If you read I said generally it is a bad idea and continued it is completely OK in that situation if it is single
What is a cone basically?
... you mean use the SphereCast at maximum size, and then exclude any that don't fall within the correct pitch/yaw from the player?
@cold parrot and here is the code I used CustomClass[] newList2 = oldList.Select(it => it.CustomClass).ToArray();
Is there any difference between it and cylinder?
Yeah, except I think a sphere overlap would be enough.
SphereCast returns the first collider that the sphere hits. Do you want to do that with a cone or do you want all colliders inside a cone?
All colliders.
๐ค
@cold parrot logic wise, there is no reason for editor to mess up my list, but it did , I run this code via editor's button
Physics.OverlapSphere, right?
Yes
Then that would be a ConeOverlap. I got confused because you said ConeCast.
Ok, well I'm not too familiar with the library still.
My apologies.
We can agree on that ๐
I just have my own experiences of getting told "dont do this/that" without them knowing my usecase and workflow preferences, and it just ends up limiting my productivity. But yes you should use static sparingly and only if you know its implications
Yes cone cast is meaningless
@cold parrot maybe its because ReordableList ?
I'm not seeing anything on a ConeOverlap in the scripting manual though...
In any case, I'll see what I can do with a series of OverlapSphere calls. ๐ค
I have more questions ๐
I'm creating an enemy object, which contains a 3D model of the enemy as a child. This child has an animation controller, which acts as a state machine. I can't figure out the proper object structure for clean code.
- My enemy has some stats, like movement speed etc., on which object should these stats live? The root of the enemy?
- The states of the animation controller have behaviours, which need to reference the stats. Should these behaviour scripts have a reference to the parent game object (the root)? That seems kind of dirty.
- Is a state machine with an animation controller even the way to go when creating an enemy with different states or attack types etc.? (I looked up many tutorials, but it's hard to tell what's outdated and what's still relevant)
What would be your preferred way of getting a reference to the main player for example?
DI when spawning the enemies?
What I mean is that at first you said you were looking for a "ConeCast" function. "Cast" physics queries only ever return one result, unless they're the "all" variant, like "SphereCastAll".
I see.
So I could use a SphereCastAll to do the same thing too... ๐ค
(If not better.)
Reach animator then get component of movement component and get movement speed
gross
movement component is on the parent game object, not on the same object as the animator. I could do animator.parent.getComponent, but then I have a very strict object hiearchy
If you only need to know what colliders are within the cone, it's unnecessary to use a cast function, because that will tell you information about the collision point, its normal, texture coordinates, like a raycast.
Ok... so what should I use instead?
I like you. You are smart
how often are you gonna do that...
Absolutely, I agree, don't depend on hierarchy
I don't understand this question. The behaviour requires different stats, which are constantly referenced at different times.
how often are you going to do that get component call on the animator parent
onStateEnter I guess
It's not the way I want to go anyway
I dont like it
Again, do you understand what a cone is? How is it related to a sphere?
so if you have 10 enemies they all get comp every time they change state?
There's something with an internal package:
Library\PackageCache\com.unity.services.core@1.4.0\Editor\Core\Configuration\ProjectConfigurationBuilder.cs(93,13): error CS0103: The name 'IoUtils' does not exist in the current context
How do I fix this?
if I would implement it that way, then yes
public Vector3 position
public Quaternion rotation
}
public class EntityNetworkData {
public Address networkAddress;
public int networkIdentifier;
public int rudpRecvAck;
public int rudpSendAck;
}
public static class EntitySystem {
public static List<EntityTransform> entityTransform = new List<EntityTransform>();
public static List<EntityNetworkData> entityNetworkData = new List<EntityNetworkData>();
public static EntityTransform GetEntityTransform(int entityID) {
return clientTransform[entityID];
}
public static EntityNetworkData GetEntityNetworkData(int entityID) {
return clientTransform[entityID];
}
}``` So is this basically how ECS works?
I figured I could hack together a cone by using a sphere that grew, even though that's not possible.
@whole gull Just so I catch up, are you using the animator's states for logic?
Why?? Why does it need to grow?
yes,
that is terribly slow and getcomponent is not generally used this way. It is better practice to use it on start, awake or enable. you will have exponential cost with this method as you have any more enemies
So that I can have my cone.
ok, but animation state behaviour doesn't have "Start" or "Awake" function, does it?
Looks like it does
https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.html
That's not how you get a cone. A cone is a spherical sector - a part of a sphere limited by an angle.
https://en.m.wikipedia.org/wiki/Spherical_sector
Unless you're saying I ought to just do some simple yaw/pitch/distance check to get stuff, I don't see why I shouldn't use a SphereCastAll to fetch the necessary stuff.
@whole gull Oh it inherits Awake from ScriptableObject
Not sure if that works how you want
im not sure. I would never use the animation state to control anything other than animation but I know its not unheard of like dark souls does store more than animation in the animation data.
I don't have to do it that way, I just found tutorials that told me to use the animation state machine to control enemy behaviour
instead of having 10 if statements in my update loop
So if you know what objects are within a sphere, you can check their angle relative to the "cone axis" to determine if they are within a cone.
this is backwards to how I would personally do it
Get rid of unity state bahaviours
You could just do the logic in normal code, and maybe use StateMachineBehaviours as additional juice if you need.
And to hook your AI states to your animator states
Oh I see what you're saying now... I think... ๐ค
... you're saying have one sphere emanate from the origin (which would be the origin of my player controller in this case), and then check yaw/pitch from there, right?
I could use normal code, but then have a lot of if statements
Whatever else falls outside of that check gets ignored.
I wouldn't say "emanate". I'd say Overlap or check.
But yes.
As in the sphere is at the player's position.
And radiates outward from there.
So sure, I guess.
Awesome. ๐
You could just make your own Finite state machine. No need for if-else checks. Or just use a switch (which usually compiles into if-else anyway)
yeah I'm kinda gravitating towards that now
You should separate logic from animations.
For logic, implement your own state machine or use well known packages
Like you would have an abstract State base class for example and then you would have subclasses of that. Each state's logic would be contained within itself
can you link me a well known package?
you should write your own state logic if you intend to build on it you will want to understand it
I am in bed!
I don't understand your obsession with "radiating"/"moving"/"expanding" the sphere. If it's a of a fixed radius, you don't need to do anything like that.
You can find it
ok! ๐ thanks for your help tho! I will look
yeah I guess I could!
You just need to check if objects are withing the sphere/radius. Which would be called an overlap.
I don't mean it grows, I mean to illustrate that the sphere merely is centered around the player controller.
Thus the radius stems from that position.
Go for it. Or if you use something existing, look for a framework that you can expand upon
