#archived-code-general
1 messages · Page 450 of 1
I'm trying to instantiate an arrow by code in the bow of my character, when I press the shoot button and I'm using addforce but I don't know why sometimes when I shoot the arrow it goes out of the map downwards and other times it falls to the ground without any problem, I don't know what would be the best way to shoot the arrow, the arrow is a prefab and has a rigidbody and a box collider, the arrow prefab shouldn't be the problem
Later I can send a screenshot of my code
maybe it's colliding with the player or the bow
Use Debug.Log in OnCollisionEnter to find out
also don't share code as screenshots
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hey guysss my sprite (the highlighted spaceship) won't load.... why?
it's nowhere near the camera
See this cute little horizontal white line above the hand icon
that's the top of your actual game camera viewport
your spaceship, since it's a SpriteRenderer, needs to be inside that rectangle to be visible in game view
(it's also HUGE right now)
You're getting confused by how Unity displays the overlay UI in scene view, that's all
ohhh okay thankss i get it
your other option is to use a UI Image instead of a SpriteRenderer
and make this thing part of the UI
trying to instantiate a pause meny ui object and keep it throughout each scene but im running into some issues, anyone know why this doesnt work?
https://paste.mod.gg/nljtehxlzegl/0
A tool for sharing your source code with the world!
Can you explain what you mean by "it doesn't work"? What are you expecting to happen and what's happening instead?
the pauseMenu script cant locate the instantiated menu
I'm not sure I even understand why you have two separate scripts here
Also why is it looking for some other object
when it is ITSELF the pause menu object?
I would recommend reading this, you seem to be confused about how singletons should work and your implementation is weird/overcomplicated and not really correct: https://unity.huh.how/references/singletons
Okey thanks
i think i get it now, thanks
so i got the menu to instantiate properly, but its outside of the canvas parent, so how can i add it in upon instantiation?
instantiate it as a child of the canvas
Instantiate has a parameter for a parent object
ah thanks
Hey, i'm trying to detect my mouse over UI elements, i have one on each side of the screen, and it seems like it detects the one on the left side but not the one on the right side? They're completely identical and this is really throwing me off
I'm using IPointerEnter and Exit handlers
Nevermind, I switched to graphic raycasting and it works now
switched to it - from what?
//script arrow
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArqueroAttack : MonoBehaviour
{
public int daño = 10;
public float tiempoVida = 10f;
// Start is called before the first frame update
void Start()
{
Destroy(gameObject, tiempoVida);
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("enemy"))
{
other.GetComponent<EnemigoMelee>().TakeDamage(daño);
Debug.Log("¡Flecha impactó al enemigo!");
Destroy(gameObject);
}
else if (other.CompareTag("Suelo"))
{
/*Rigidbody rb = GetComponent<Rigidbody>();
//rb.velocity = Vector3.zero;
//rb.angularVelocity = Vector3.zero;
rb.isKinematic = true;
transform.SetParent(other.transform);*/
}
/*else
{
Destroy(gameObject);
}*/
}
}
//script player:
public void DispararFlecha(){
GameObject nuevaFlecha = Instantiate(flechaPrefab, puntoDisparo.position, puntoDisparo.rotation);
Rigidbody rb = nuevaFlecha.GetComponent<Rigidbody>();
if (rb != null){
rb.AddForce(puntoDisparo.forward * velocidadFlecha, ForceMode.Impulse);
}
}
I don't know why when I shoot it does strange things, the arrow goes down through the ground of the map and it doesn't shoot well, I have an arrow with a rigidbody with gravity activated and a collider with the trigger activated, and I also use an empty game object located in the bow to be able to specify the shooting point (puntpDisparo)
Since your collider is a trigger it's going to pass right through all solid objects
And your code in OnTriggerEnter ignores everything that doesn't have the enemy tag
Hey, I'm making a VR game with a wall run mechanic where after a player starts wall running they get a full 360 degree control over where they go along the wall. So they can go up, down, left, right and anything in between. With the forward direction always being where they are looking.
Where I'm running into problems is with getting the movement direction while the player is on the wall.
Because it's a VR game I can't rotate the camera or the player object around to get the player's forward direction, at least not without unparenting the controllers. Instead I have an empty gameObject called directionIndex that I rotate to match the camera's Y rotation and use that to base the movement direction off while the player is on the ground.
directionIndex.eulerAngles = new Vector3(0f, head.eulerAngles.y, 0f);
Vector3 targetVelocity = new Vector3(moveInputValue.x, 0, moveInputValue.y) * (moveSpeed * moveSpeedMultiplier);
targetVelocity = directionIndex.TransformDirection(targetVelocity);
So what I would ideally need is to replace the first line of the code above with one that applies the player's head rotation along the walls normal to the directionIndex object (in world space). Does anyone have examples of that type of code?
(I've tried asking this a couple of times but my extremely limited knowledge of rotations and quaternions has always hindered my explanation of the issue and has stopped me from understanding and implementing the answers I got. This time around I took extra time to make sure I write everything down as best as I could. Thank you for reading this.)
i remember this yes. i presume you dont mean 360 control
seeing as a wall is a 2d plane so i presume 360 degrees on 1 axis is what is desired
yes it is
I tried to help before by explaining how you rotate the XZ plane movement rotation. doing Quaternion * Quaternion will rotate the first by the second.
Try:
directionIndex.rotation = Quaternion.Euler(0f, head.eulerAngles.y, 0f) * Quaternion.LookRotation(Vector3.forward, wallNormal.normalized);
That sadly doesn't work, while on the wall I don't really need the y rotation of the head I don't think. That's the part of the original code that needs to be replaced.
you can try just rotating the movement vector instead with Quaternion.LookRotation(Vector3.forward, wallNormal) * moveInputValue
you can do Quaternion * Vector3 to rotate a vector (around 0,0,0)
The point is to change their input from XZ to the wall "plane" right?
the input is fine, its the direction that needs to change. wait let me try to get a visual representation of what I mean cause I think we are not on the same page.
Aha this may be the rotation you need actually Quaternion.FromToRotation(Vector3.up, wallNormal)
Alright so when the player is on the ground, the directionIndex rotation gets clamped to this plane
https://gyazo.com/f1f413cfb1916004249a91e7772b5160
But when the player is on a wall, I need the directionIndex rotation to be clamped to the walls plane instead.
https://gyazo.com/8da76f4661160f6fd0f27cf2684f06f4
Try this:
Vector3 targetVelocity = new Vector3(moveInputValue.x, 0, moveInputValue.y) * (moveSpeed * moveSpeedMultiplier);
targetVelocity = Quaternion.FromToRotation(Vector3.up, wallNormal.normalized) * targetVelocity;
together with
directionIndex.rotation = Quaternion.Euler(0f, head.eulerAngles.y, 0f) * Quaternion.LookRotation(Vector3.forward, wallNormal.normalized);?
Ah I guess the input needs to be rotated by the player camera dir first?
@lucid brook If so here is a new version where we rotate input by the player cam Y rotation only first, THEN the wall normal rotation:
Vector3 targetVelocity = new Vector3(moveInputValue.x, 0, moveInputValue.y) * (moveSpeed * moveSpeedMultiplier);
targetVelocity = Quaternion.Euler(0f, head.eulerAngles.y, 0f) * targetVelocity;
targetVelocity = Quaternion.FromToRotation(Vector3.up, wallNormal.normalized) * targetVelocity;
instead of using a transform to rotate a vector we do it ourselves so directionIndex is not needed
I don't think that is going to work because it's still using the Quaternion.Euler(0f, head.eulerAngles.y, 0f). when I am on the wall I don't need the Y
I don't know what moveInputValue is from but if you want movement to be relative to the player look dir then it is needed.
There is also no changes needed to the input. If I do directionIndex.rotation = head.rotation; it almost works perfectly. The only thing I need to change is that when the player looks away from the wall, they walk off of it.
https://gyazo.com/9c32f6e964f8d4996188e25dd3bbcce5
and the reason I can't just have the players distance from the wall be a set value is because I have them riding on a sort of spring.
thats a different issue and is easier to solve
Im trying to implement knockback in my 2d platformer and im just trying to work it out on paper first.
Just a little confused on how exactly I need to calculate the knockback direction
maybe taking the bullet transform that is being fired, compare it to the enemy rigidbody, and apply the opposite of that bullet transform onto the enemy rigidbody?
Do you want the player to be knocked back in the direction of where the bullet came from? like the bullet comes directly from the right so the knockback sends to you the left?
it is?
Yes but more specific if possible, might add also a little upwards force too
a simple way would be to "release them" from the wall movement if their look dir angle (compared to the wall normal) goes above some value (actually probably below an angle)
like if I hit the enemy from the bottom it would just be sent upwards depending on angles and whatnot
but I don't want that to happen
then i dont know what you want anymore 😆

I almost got it working earleir but I had a thing where if I was on the right, I hit my enemy on the left with a bullet and my player was moving to the right, the knockback would just be the wrong direction
ive already given some info on how you should rotate a 2d movement vector for some surface normal. im not sure whatelse to say
Vector2 force = bullet.forward * knockbackForce + Vector2.up * knockbackUpForce;
rigidBody.linearVelocity = Vector2.zero;
rigidBody.AddForce(head.forward, ForceMode.Impulse);
Something like that should work I think
rigidBody.linearVelocity = Vector2.zero; sets your speed to 0 so your knockback will always be the same
Hey mate sorry to ping i know it's been a while but i can't for the life of me figure out how to make this work, i'm trying to do if my bool is true from my main class then it show an ui but i can't get the class since getcomponent can't be used and i can't us ()target; so i'm gonna stick to the hold editor way and just make an array for multiple variable instead of one big one ;w;
what does head.forward call? The vector of the bullet?
woops sorry, I wrote that in my current project. that should be your bullet
you could also do rigidBody.linearVelocity = rigidBody.linearVelocity / 2; if you don't want your played to lose all their speed
one more thing, lets say I had this on my enemy script, how would I call an instantiated bullet?
where would you put the knockback code? on the bullet or on the enemy?
well if I wanted it on my bullet wouldnt I need to get the rigidbody of the enemy I hit?
or if it was on my enemy I would need to grab the bullets my player is instantiating
Im gonna point out that your original idea of "bullet to enemy dir opposite force" is correct
its really not that complex
You do target.position - me.position to get a direction from me to target. It should be normalized before use with forces.
my brain isnt working my bad unity is still rather new to me, would I call the target using an OnTriggerEnter2D method?
well i presume you already use OnCollsisionEnter2D or trigger version for damage so you can do it there too
slightly different ofc depending on if its done on the bullet or enemy
yeah I just realized I already have like half of this
just try it and see, not hard. just use AddForce() with Impulse mode
aight bet thanks guys
Isn't this suppose to work? Why is my unity not referencing this dll?
[CustomPropertyDrawer(typeof(NormalizedAttribute))]
public class NormalizedAttributePropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
dynamic obj = property.boxedValue;
switch (obj)
{
case Vector2:
case Vector3:
case Vector4:
obj = obj.normalized; // error on this line
break;
default:
break;
}
}
}
error: One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?
im almost positive I've done something like this before
I effectively made my game crash from screwing up a single line of code but is this the right idea
ok nothing at all happened
oh wait Im not applying any froce
yooo I got it to work
that really was much easier than all the knockback videos made it
that was like 2 lines of code
Usually is a lot easier than videos make it seem
Do not use dynamic as not alll platforms will be able to support it. Use object and a type check to solve the issue:
object obj = property.boxedValue;
switch (obj)
{
// ...
case Vector2 vec:
obj = vec.normalized;
}
The downside being that you have to repeat the check for each vector type, so it can access the inline variable created within the type check
this is editor code. I know it's not in #↕️┃editor-extensions but it's a general question about if unity supports this or not, not for help with the editor code itself.
Error means it doesn't
has it never supported it? As I said I could have sworn I've done similar things before.
I think Unity supports dynamic at runtime but only if you're using the Mono scripting backend (not IL2CPP). But I also thought the editor always ran Mono so I'm surprised it's not working TBH
theoretically speaking, how bad is it to thread the same value via an overload across different functions?
Ok that's what I thought too. I was running IL2CPP but swithed to mono and restarted, and also tried .NET Standard instead of framework for editor assemblies, but nothing. I submitted a bug report.
{
int importantValue = 42;
StepA(importantValue);
}
void StepA(int value)
{
StepB(value);
}
void StepB(int value)
{
StepC(value);
}
void StepC(int value)
{
// final use or maybe even continue
}```
something like this
would this be considered bad practice or is it not that bad?
I've already solved it, I used an OnCollisionEnter instead of OntriggerEnter and I disabled the arrow trigger, thanks
If you're only calling other functions in the same class like that in each step, bad.
Otherwise, it's not necessarily 'bad' but it might be argued that something like this is more readable
void DoSomething()
{
int importantValue = 42;
var v = StepA(importantValue);
v = StepB(v);
v = StepC(v);
}
int StepA(int value)
{
//something
return processedValue;
}
int StepB(int value)
{
//something
return processedValue;
}
int StepC(int value)
{
// final use or maybe even continue
return processedValue;
}
@ocean hollow
doing it this way likely adheres more closely to the single responsibility principle as well
yeah im hopping between classes, thanks for the insight
is there a way to save a list of objects to json? i'm using JsonUtility.ToJson which seems to work pretty well for most things, but when it comes to this list it saves them as instances
doesn't work that way, you need to save data and restore it somehow (e.g. some id that you use to load a prefab later)
would it work with say an inner class? or a struct
This works, thank you so much 🙏
You cant just save a List<GameObject> but yea if you have your own script/class you can serialize data from that and restore it later.
Ideally you load a prefab and apply extra data after to fully restore state.
i should've specified rather than just "object" its a script :P
looks like this
the list is List<Catchable>
you will need a class to hold the list and then serialize that class instance.
Some things like Texture and AnimationCurve wont work ofc
this is why its better to do things a custom way with unique ids and prefabs you manage so you dont have to fuck with this
do you have a resource about this or a simple explanation so i can try to work a different system out?
i'm very new to the whole "save file" schtick
You can invent your own to suit your needs.
E.g. ScriptableObject with a unique string id + prefab. When saving you save this Id + extra data. Later you find the scriptable object with the id and instantiate the prefab, then load back the extra data (e.g. ammo, health).
You probably want to avoid trying to json serialize a mono as it will cause issues (and if you use another serializer like newtonsoft json it will require many extra things to work somewhat correctly).
ahhh gotcha
thanks
I think I have figured out an abstracter way of asking a question I have asked before.
So I am getting the blue walls normal, represented by the darker blue cylinder.
I want to get the rotation of the toaster along that axis.
So that when I take that rotation and apply to it a another toaster it will only rotate along the blue cylinder/that green plane
(Don't ask why I have 2 toaster, that's none of your business
)
I assume you could probably just set the transform.up of the 2nd toaster to be the normal of that blue wall
yeah but I need to rotation to be based off of the first toaster.
kinda like toaster2.eulerAngles = new Vector3(0f, toaster1.eulerAngles.y, 0f); but on any plane, not just on the Y
Then set the transform.up to be the same as the first toasters transform.up
Am I visualizing this wrong? Are you trying to have it copy only how much it is turned left or right, as if it was not turned on its side?
give me a sec, I think I know a way to visualize it better
So I want to take the rotation of toater1 only on the blue cylinders axis
https://gyazo.com/91ddd4c4789eb878a427de937509870e
So that if I take that rotation and apply it to toaster 2. it will only rotate like this
https://gyazo.com/0995f4240298d51fe14d3560d6fac6d7
It might be a bit more clear with just an example of toaster 1 in a rotation, then how you expect toaster 2 to look.
I do find it confusing what you want, maybe take a look at the quaternion docs and see if any methods stand out? Maybe something like to angle axis here
Quaternion.FromToRotation(Vector3.up, wallNormal.normalized)
the solution is still using this to make a global y euler rotation be on this "plane"
As explained earlier, you can multiply quaternions together to rotate one by the other.
does anyone know why profiler cpu usage does not display any highlighted blue for this collision manager ? from the ss i can tell the collision manager is taking 11ms and it falls under the script cpu usage for sure (since it is in update event)
maybe cus you de selected "Physics" ?
is there a reason why my IDE is suggesting this over my current solution? Is this better somehow?
What exactly is the cause of the 11ms. If it's something like GC, that might not be mapped properly.
I think that's pattern matching, and I'm not sure unity supports them yet.🤔
it does, it's pretty neat
a lot less typing
it doesn't fully support all the possible types of pattern matching, but in this case it's fully supported
To put it simply it's syntax sugar that the most cool guys in the neighborhood use.
im sure that syntax sugar would go very well on top of my spaghetti code
hello 👋 is there a way to disable OS trackpad gestures for games while you're playing?
I'm working on a game for kids (https://store.steampowered.com/app/3387970/Squash_and_Spell__Kids_Typing/) and some of the feedback is they accidentally swipe the trackpack and close/switch the app
Which OS? Although I think it's out of your control in all of them
or at the very least requires native plugins
Hello, I have some additive scenes. Is there a way for a camera to record only what's inside his own scene without using layers ?
without using layers
unlikely, the layers used for the camera's culling mask is what determines what it can and cannot see
Arf, ok thanks
so im using the mobile URP template, and each time i undo something i get this error
SerializedObject target has been destroyed.
UnityEditor.SerializedObject:UpdateIfRequiredOrScript ()
Unity.Notifications.NotificationSettingsProvider:<Initialize>b__19_0 () (at ./Library/PackageCache/com.unity.mobile.notifications@439e41e635a0/Editor/NotificationSettingsProvider.cs:79)
i didnt use the notification settings provider yet, so i wonder how a default unity template project errors like this
what isn't supported?
the list destructuring thing?
there were a bunch of additional improvements to pattern matching in the newest C# versions
I would expect Unity to only support stuff up until C# 9
not sure which exact features are supported
Unity lags behind, it isn't on the latest C#
(float,string) displayText = remainingTime switch
{
float i when i > 4f => (80, "First to 5 points wins"),
float i when i <= 4f && i > 3f => (300, "3"),
float i when i <= 3f && i > 2f => (300, "2"),
float i when i <= 2f && i > 1f => (300, "1"),
float i when i <= 1f && i > 0f => (300, "GO!"),
_ => (0f, string.Empty)
};
i was suprised when i found out you can do conditionals in the matching too 😄
this is pattern matching yes
but you could also just do > 4f instead of float i when i > 4f
also you don't really need the separate 3/2/1 cases
that isn't really pattern matching (except float i which isn't much of a pattern 😄 ), it's a switch expression with a condition on each branch! pattern matching would look like this (notice no variable names and and instead of &&):
(float, string) displayText = remainingTime switch
{
> 4f => (80, "First to 5 points wins"),
<= 4f and > 3f => (300, "3"),
<= 3f and > 2f => (300, "2"),
<= 2f and > 1f => (300, "1"),
<= 1f and > 0f => (300, "GO!"),
_ => (0f, string.Empty)
};
are ECS managed singleton supported ?
all functions i find to get my singleton requires T to be unmanaged
i am having a hard time understanding how components should be done when of managed types, a lot of functions (such as queries) dont accept them
sorry I missed that, I had it reported on mac OS but I'm guessing windows too. It can happen on Android but doesn't occur often due to the ergonomics of the hardware.
Thanks though, I thought the same thing 😦
Not sure if it belongs in this channel in particular, but I'll ask anyway.
I've been trying so hard to find a way to have it so that my player can slide against slopes without a slowdown, but I just can't seem to find a solution regarding that anywhere, at least in terms of a top-down RPG game.
I'm currently using Unity2D and the linear velocity of my RigidBody to move my character. My game is mainly top-down, and not a platformer.
Here's a visual representation of what I'm talking about:
A simple solution would be setting up physics materials to have 0 friction which may solve the problem?
otherwise perhaps you need to use ray casts/collision events to detect movement into a wall and instead change input to be parallel to avoid wall friction?
Yeah, I did the physics materials already, and it works when I simply want to slide against a wall, but I still slow down when sliding against slopes.
I wasn't sure how to go about using ray casts because I'm using a Box Collider 2D
It may be that its not loosing speed but due to the distance being further it appears to go slower visually?
It's kinda weird, because I even checked the velocity when this happens and the speed is reduced regardless
got a video showing the colliders?
Yeah, here, let me get it set up real quick
you'll probably get more helpful answers in #1062393052863414313 or #1064581837055348857
but yes, managed singletons are supported — after all they're no different than the other components
you most likely just need to use the Managed version of the API (SystemAPI.Managed)
Not sure if this is what you ask for, but here's what I have
Hi, i developed two package and one is depended to other. Both is on github. I followed the docs on below. How can i set my dependency url? when i put whole url i get this error : Expected a 'SemVer' compatible value.
https://docs.unity3d.com/6000.1/Documentation/Manual/upm-manifestPkg.html
that isnt possible, it has to be the package id + ver and it will try to install from the registries/scoped registries configured and thats it.
Do you have any example or any docs?
Where i work we have our own ones hosted on jetbrains and dependencies seem to work for ours
they are all com.company.unity.foobar
can i use a git url in scoped registry?
the point of this is to tell unity "hey, a package that starts with com.mycoolcompany probably exists on this host
git url just cannot do this so you cant make it work
open upm exists to help with this, most of them are sourced from github repositories
can someone help me, I'm making a battle system that has a shield that can face up down left or right and it's giving me weird angles except for up my code:else if (soulstate == 3)
{
myrb.gravityScale = 0;
transform.rotation = Quaternion.identity;
transform.localPosition = new Vector3(0, 0, 0);
shield.gameObject.SetActive(true);
if (Input.GetKeyDown(KeyCode.UpArrow))
{
shield.localRotation = quaternion.identity;
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
shield.localRotation = quaternion.Euler(0, 0, 90);
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
shield.localRotation = quaternion.Euler(0, 0, 180);
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
shield.localRotation = quaternion.Euler(0, 0, 270);
}
}
why are you using Unity.Mathematics.quaternion instead of UnityEngine.Quaternion? that is the issue, quaternion.Euler expects radians not degrees while Quaternion.Euler is what you want because it uses degrees
also !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
thx
weird thing, but can you configure visual studio to always prioritize one over the other?
It often automatically uses the System MathF which is always annoying when I dont spot it right away and realise seconds later when I dont have access to everything.
Same goes for Random
Make sure you normalise the input vector firstly as remember its magnitude will go up above 1 with diagonal movement. That may make it feel more consistent?
Hm... I prefer my movement unnormalized just for the sake of the game I'm making
you have to pay attention to what you are autocompleting instead of just doing it blindly
Thats true, definitely in the case of MathF vs Mathf. But Random could be System.Random or UnityEngine.Random theres no way to distinguish
only when you hover over it to see which one its using
You say that but linear movement with it's direction changed won't then match diagonal input. Just how it works.
Huh, alrighty then, I guess I'll see what I can do then
if you want to support analog input for movement then just clamp the magnitude to 1 so it cannot go beyond it but can still be lower than 1 to allow slower movement
if you don't need that slower movement or don't care about analog input then you can just normalize it because it makes no difference then
Are you talking to me?
Trying to use a small 64x64 pixel image as a "brush" for editing terrain at runtime, and I've got it making a blocky shape by just naievely sampling the closest pixel to the area of the terrain I'm editing (Picture below, it's a gradient circle image so it's scaled it up to 1000x1000)
If I want to smooth this, how might I go about sampling the image in a way that smooths it out? This seems like something most image programs do when blowing up a pixelated image but I need to do it mathematically when setting up the matrix.
The code that does that naive sampling:
int imageXCoord = Mathf.RoundToInt(Mathf.Lerp(0, brushSprite.width, Mathf.InverseLerp(0, width, x)));
int imageYCoord = Mathf.RoundToInt(Mathf.Lerp(0, brushSprite.height, Mathf.InverseLerp(0, height, y)));
BrushMatrix[x, y] = brushSprite.GetPixel(imageXCoord, imageYCoord).r;
this is the body of a loop over a portion of the terrain defined by width and height, in this image, they're both 1000. The image is a 64x64 grayscale mask.
sounds like maybe you want to use something like bilinear sampling? https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Texture2D.GetPixelBilinear.html
It does indeed! Thank god I thought I would have to use math
Flawless, no notes. Thanks!
Okay, more terrain math: Trying to go from a world space Vector3 to a terrain XY Index that I'd pass as the start location for terrainData.GetHeights.
I can't find any data about what those indices even are, other than 0,0 seems to be the bottom-right corner through basically just plugging and checking. How would I find out what the "Terrain space" coordinates of a world location would be, taking into account the terrain's transform position and size?
Since the 0,0 corner seems to be the transform.position of the terrain, I could do some InverseLerp/Lerp remapping, but what are the sizes of that heights array? Are they in world units, or something else? Is it just terrainData.size.x and terrainData.size.z? Those are floats, but the indices are ints so I don't know what to do to rectify that, they don't seem to be the same dimension
GetHeights asks for the pixel on the heightmap, so (point - terrainPosition)/terrainSize * heightmapResolution rounded to integer
There might be an off-by-1 somewhere
should be floored to int
This is a code channel
I love coding
using InControl;
using UnityEngine;
namespace J3G.Input
{
using Input = UnityEngine.Input;
public class PlayerInput
{
// Player Input
public static float MoveX() => GetInput(GamepadUtils.GetAxis(InputControlType.LeftStickX), UnityEngine.Input.GetAxis("Horizontal"));
public static float MoveY() => GetInput(GamepadUtils.GetAxis(InputControlType.LeftStickY), UnityEngine.Input.GetAxis("Vertical"));
public static float MoveXRaw() => GetInput(GamepadUtils.GetAxisRaw(InputControlType.LeftStickX), UnityEngine.Input.GetAxisRaw("Horizontal"));
public static float MoveYRaw() => GetInput(GamepadUtils.GetAxisRaw(InputControlType.LeftStickY), UnityEngine.Input.GetAxisRaw("Vertical"));
// UI
public static float StickYAxis() => GamepadUtils.GetAxis( InputControlType.LeftStickY );
public static float DPadYAxis() => GamepadUtils.GetAxis( InputControlType.DPadY );
public static bool Submit() => GetInput( GamepadUtils.GetButtonDown( InputControlType.Action3 ), UnityEngine.Input.GetKeyDown( KeyCode.Return ) );
public static bool Back() => GetInput( GamepadUtils.GetButtonDown( InputControlType.Action2 ), UnityEngine.Input.GetKeyDown( KeyCode.Escape ) );
private static T GetInput<T>(T inputGamepad, T inputKeyboard)
{
T obj = default(T);
if (!inputGamepad.Equals(default(T)))
obj = inputGamepad;
if (!inputKeyboard.Equals(default(T)))
obj = inputKeyboard;
return obj;
}
}
}
Hi guys, I'm having a bit of a weird issue when parenting my player controller
I've got a box collider 2d set up on my moving platform, so that upon entering, my player controller's parent is set to the moving platform
though the movement with the platform seems fine, every time I enter or exit the collider there is a small but very noticeable jitter
Is there any way to fix or avoid the jitter?
Maybe show how you're implementing this?
how does your player move?
How does the platform move?
Also !code please
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
yeah sorry its been a while since i've been in here
player is a Rigidbody2D controller, with the movement using rb.AddForce() applied in FixedUpdate
platform is stationary during this issue, as I can send a video of in a second, so I'm not sure that it is causing the issues
framerate is quite poor even though it was fine before i trimmed it
the box collider 2d surrounds the platform (space looking thing on the right)
Show how you're moving through code (checking for other complications)
yea sure thing
might be a little more complex to understand
public void Move(Vector2 moveDelta)
{
if (!movementEnabled) return;
isGrounded = Physics2D.OverlapCircle(groundCheckPoint.position, settings.GroundCheckRadius, settings.GroundMask);
rigidBody2D.drag = isGrounded ? settings.GroundDrag : settings.AirDrag;
Vector2 move = new(moveDelta.x * settings.WalkSpeed, 0f);
rigidBody2D.AddForce(move);
}
this is being run inside of fixedupdate by my player class
the movement function is contained within a subclass
no issues with the player controller or platform jittering whatsoever, its only the act of parenting one to the other (player to platform) that causes it
i'm going to try create an empty and parent to that instead just to make sure
closer look, hopefully the framerate shows it more obviously this time
I've tried both with a new empty gameobject with the parentable zone component
also with just a 'parentablezone' tag that can be checked against (this version is in the video, same behaviour either way)
Are you referring to camera jitter, player jitter or something other?
parenting dynamic RIgidbodies to other objects is not going to make them follow those objects properly
parenting a rigidbody isnt a good idea
ahh
had a feeling there might be some issues with physics
are there any alternatives?
thing is, in this case it doesn't matter because the lift will be going vertically, and the collider on it will just force the player up when it needs
but for horizontal movement, the platform will just slide out from underneath the player
You might want to look into Effectors - especially SurfaceEffector2D and PlatformEffector2D: https://docs.unity3d.com/2021.3/Documentation/Manual/Effectors2D.html
ah sweet, that looks promising, thank you!
My VSCode (or maybe Unity) keeps creating bin and obj folders in multiple places in my assets hierarchy. I can't find a way to prevent that on Google, so my Unity project doesn't compile until I delete them. It happens every minute. Does anybody know what's wrong?
Alright, I have a new way of solving a problem I am having, but I am going to need some help with the math cause I am not that smart 
I have a vector3 force and a collider's normal, and I need to not apply any force on said normal. So if the force is (1.3, 2.4, 0.9) and the normal is (0, 1, 0) I need the new force to become (1.3, 0, 0.9).
So it's like I need to invert the normal; 0 becomes 1, 0.2 becomes 0.8. Because then I could just multiply the force by that inverted normal. But like I said, I'm going to need some help with that.
I want to make a flying 2d enemy and im aware that using a Kinematic rigibody2d can let you keep an enemy in the air.
I also have knockback which works off of physics, so how can I keep the knockback on my enemy while its floating?
In that case you would need to turn off gravity. making a rigibody Kinematic means it won't respond to any forces
What if your wall is not perfectly facing an axis? this plan wont work 😆
oh wait theres literally a gravity scale mb
oh but now it just continously takes knockback
I guess ill make a coroutine for it getting hit to turn off gravity scale
at least i'm trying shit
ive been stuck on this for weeks.
- Project the force vector on the normal vector.
- Subtract the projection from the force vector
- you're done
oh that makes things much easier lol
Im gonna make a small example to illustrate something.
Thinking about how we can translate from one "space" to another is important (e.g. world to another transform local space)
also really quick, is Time.deltaTime the same as Time.time?
nope
have you read the descriptions?
quite possibly not
You should read them
okay so deltatime uses the last frame -> current frame while time uses the current one?
Time.time is how much time since the game started running
Time.deltaTime is how much time since the previous frame
oh okay
FOr future reference, this is all in the documentation: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Time.html
so time.time would be used for things based on how long the game has been running, while deltatime could be used for an action based timer?
sure - they both have a myriad of uses
idk what you're on about but it works fine...
thank you, thats exactly what I needed
@lucid brook I see you got a solution. I made a quick demo that demonstrates doing movement and rotation relative to a surface based on its normal. Would this be useful for you to look at?
I wanted to make sure my thinking was right too so i dont mind either way 🙂
can I see the code for that?
I did a script for movement and one for rotation. Both use a raycast and the resulting hit normal to "adjust" to the surface
both prefabs use the same scripts
I don't think that would have worked. cause I need the rotation to be based off of the camera. I need the directionIndex objects rotation to still be based off of the cameras.
The aim of this is to show you how you adjust things using rotations instead of relying on jank transform stuff
the move input is the same for both but they do different things and arent children of the planes:
We can still use a transform to do things such as rotate a vector. Hell you can even just take the forward vector of the camera and then rotate it as I did
*corrected, i meant vector
I know this stuff can be confusing, I just wanted to demo some way of doing something like this (changing a movement vector to move relative to a slanted surface instead of a flat surface)
idk that might have worked but I am not nearly smart enough when it comes to code to understand/implement that.
You will learn with time and trying things. I know that we can rotate a vector using a quaternion. I know the movement vector I have is intended for movement on XZ, where up is Y1. Therefore we can get a rotation to go from our normal up to the "surface up(the normal)" and rotate our input so its now relative to this surface up instead.
Transforms in unity and basically any engine all work with the power of matrices and are a good thing to kinda understand so you can apply them elsewhere or some of their concepts: https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Matrix4x4.html
that is not what I needed though. if I understand correctly. if I did it the way you just described and I was on the wall, facing this direction and held the the held the joystick to the right I would go up the wall, right?
yes you would. I wasn't concerned about this specifically so just take what I made and hopefully learn something useful from it.
I've accepted that I will never fully understand that stuff. I have been trying to get it on and off for 5 years or so. and I still got nothing.
my brain is just not build for it
I'll focus on game design and be happy
there's a bit more to it too, you need camera relativity on the direction if this is 3rd person
which I assume this is supposed to be spiderman according to the avatar haha
it's in vr so that's not an issue.
but the issue is solved. rob is just trying explain something
😆 hopefully something got through

oh yeah first person should be easy enough
well apparently not. it's fixed in a different way though.
Hey everyone! I've run into an issue i'm really struggling with fixing
I want to parse a Monobehaviour script as Parameter to another script, as can be seen in the picture. Ideally i would like to be able to just drag-n-drop my scripts here. However, this doesn't seem to be a possiblity, and it can only happen if set the parameter type to Monoscript, but then i cannot build my project. I know switching to Scriptable Object would be the optimal solution, but the attacks depend on Coroutines, so i'm worried i will have to start over if i do that.
Please help! Cheers! :)
For context: The reason i want to do this, is i want to add components for each script that would appear here.
Correct, you cannot drag scripts here
you would drag an object with that script attached.
also - regarding coroutines - you would probably want to just run the coroutine on some central coroutine runner anyway, not on the individual behaviors here
So i would have to create empty gameobjects, with 1 script attached, then use that as parameter?. AKA there is no easy way to simply input a script?
A script on its own is not a thing
it's just a text file
the class you define in that script is a blueprint for a component
Components in Unity do not and cannot exist except as things that are attached to GameObjects
You could do this in other ways
but not in the way you have designed here.
Wamp wamp, thanks for the answer though! :)
I didn't realize Monoscript was editor-exclusive, so i designed myself into a hole 😢
Idk where to ask about this, but I'm trying to change the "front" direction of a prefab. I'm using LookRotation() to have it point towards objects, but the "front" of the fork is not what I want it to be. How could I change the "front" of a prefab?
Either rotate it in your 3D Modeling program, or make it a child object of an empty GameObject and rotate it to the orientation you want so that the empty's forward is aligned with what you want the child object's forward to be
how do I know which direction of the empty is forward?
The blue axis
thx
it really does sound like you want ScriptableObjects here, if you don't want to create separate scene objects for each item this is what they're for! you said you'd have to redesign everything because of coroutines but there's easy ways around that
hey guys does anyone the best way to implment a highlight object script, heres my current hover code, it works but it makes the game very lagging if you keep hover and unhover the object. The highlight material is a thin white outline so I cant just override the origonal material
Well, few things but first are you applying these materials every frame or only on apply and deselect?
I suggest doing a toggle, but the overall problem here is you're creating a new material each time which is usually a big no-no for reusable stuff. Ideally make a material beforehand and cache it somewhere, then swap out the material when you need to use it.
once
can you toggle material or no
if thats what you mean
If you have say a bunch of units you can highlight, I also suggest using a single shared material
I just mean that having logic to do a one-time swap instead of continuously polling and adding that material to the renderer as long as your cursor is over it.
but that's less of a problem if you do a cache/shared material anyway
it is a one time swap
like it doesnt swap every frame
if thats what you mean
here let me record a vid
- you could keep reusing the same array instead of making a new one each time
- what's calling OnHoverXXX methods?
In that case yeah just make a one-time material. What's happening maybe is the materials arent being garbage collected perhaps cause you're newing them
let me send it 1s
Usually if you do want to create a bunch of new material instances you want to manually destroy them if possible
my gues is the lag is coming more from Unity drawing the inspector than anything else, TBH
A tool for sharing your source code with the world!
really
xdd
let me try this
The other thing is - you should be using this https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Renderer-sharedMaterials.html
not .materials
oh ok
let me see
wait i have a question
doesnt shared material like
changes material globally
It only matters if you're actually modifying the materials
for all the object using it
I'd make a single shared material for highlighting which can be applied to multiple units without having to modify it
the thing is this material is implemented as a second material
so you do need to modify the array
but it seems like the material itself isn't being modified
Ah, it's a submesh outline
oh yeah right
well if material count > submesh count it will just render the same submesh again, with the second material
what if I
add a boolean parameter
inside the
shader graph
and just toggle it on and off when im hovering over the object
Well it would be a float alpha param more like.
But this has a cost
it means you';re going to be double rendering all your objects all the time
it's better not to do this
you're right
but there isnt that many highlightable obj so it should be fine
probably a really stupid way to implement this effect lol
im hella stupid 😭
It's pretty common
Otherwise you have to integrate it into the shader, or do something like post-processing outlining
Really more of an issue on skinmesh renderers
oh ok
yeah but they look really nice
lol
Why is there a slight difference between how the above text (rendered to a Render Texture and displayed in a Raw image) and below text (in an overlay canvas) looks?
Does it have to do with the RT settings?
Or maybe the TMP shader?
Hello everyone, does anyone know how to achieve this behavior?
I want to have a black image overlay covering the screen, including UI buttons, and then use a second image to cut out a portion of that overlay—so the user can click the button underneath it. This is useful for creating tutorials.
Currently, I achieve this by duplicating multiple background images. I’ve also tried using shaders (one for the black overlay and another for the cutout), but I haven’t been able to get it working properly.
Does anyone know how to do this or if there’s a better approach for tutorial systems?
Can you do it with a Mask?
Tried it but can't seem to make it work.
This example looks like what you want:
https://docs.unity3d.com/Packages/com.unity.ugui@3.0/manual/script-Mask.html
unless I misunderstand
I don't think this is the correct approach, since the cutout image needs to both disable raycast targeting in that area and visually cut it out.
I think you could just handle the raycast targeting stuff separately
either with canvas groups or just looping through all your other ui elements to modify the raycast target thing as needed
Yeah, that could work, but I remember there's an approach that uses two shaders—one for the black image overlay and another for the cutout image. So it could also be done with shaders, though I can’t quite figure out how, even though I know it works.
Why is this not properly calculating the angle from origin to position on the x-axis?
Trying to rotate an inverse kinematics segment towards a target position.
The angle is correct, but it does not go negative when the position is infront of the segments origin.
public static float Follow(Vector3 origin, Vector3 position)
{
Vector3 direction = position - origin;
direction.Normalize();
float ikAngle = Vector3.Angle(Vector3.down, direction);
return ikAngle;
}
Mask is basically stencil shader anyway
It won't work with mask so far during my testing.
How do you all handle tutorials? For example, if you want the user to click only a specific button and prevent interaction with others, how do you manage that?
Disable the elements you don't want targeted, or manually raycast and go through the list of elements and only apply work on the one you want.
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Vector3.Angle.html
Note: The angle returned will always be between 0 and 180 degrees, because the method returns the smallest angle between the vectors. That is, it will never return a reflex angle.
Vector3.Angle explicitly gives you the shortest (positive) angle between the vectors
If you want a positive or negative angle, use SignedAngle
You mean to set all buttons raycast to false except the one I want the user to click?
Seems like a little complicated like I would have to do this for each tutorial step, what do you think?
Seems like a pretty simple function to do that in code
that would only have to be written once
the only thing you'd need to do for each step is pick the set of controls you want to remain active
but what about the overlay like to indicate this button to click?
use the mask technique
so mask to visually indicate this button to click and using code to disable interaction on other buttons?
you could build a Bounds/Rect from the rects of all the elements
and then dytnamically shape the mask
yes
How would I go about calculating the shortest angle with this specification?
Down is 0 and up is 180
negative if infront.
positive if behind.
the shortest aangle between what and what?
Vector3.Angle gives you the shortest angle
between the origin and position
Vector3.SignedAngle gives you a signed angle
origin and position of what? Angles are calculated between direction vectors, not positions
for an angle you need 3 points and/or two direction vectors
The angle should be on the x-axis or any axis for that matter never more than one
It's kinda hard for me to get what you're going for without seeing a diagram or something, but with Vector3.SignedAngle you specify an axis to check the angle around
help im been stuck at this for hours, dot know why the result vector isnt 90 degree to the incoming ray, the blue line is the surface hit.normal, trying with vector3.reflect
heres the code on the blue man if this help:
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(LineRenderer))]
public class Attack : MonoBehaviour
{
public int maxReflections = 5;
public float maxDistance = 100f;
public LayerMask hitLayerMask;
private LineRenderer lineRenderer;
void Start()
{
lineRenderer = GetComponent<LineRenderer>();
}
void Update()
{
CastLaser();
}
void CastLaser()
{
Vector3 origin = transform.position + new Vector3(0, 0.5f, 0); // avoid ground
Vector3 direction = transform.forward;
List<Vector3> points = new List<Vector3> { origin };
for (int i = 0; i < maxReflections; i++)
{
if (Physics.Raycast(origin, direction, out RaycastHit hit, maxDistance, hitLayerMask))
{
points.Add(hit.point);
if (hit.collider.CompareTag("Shield"))
{
Debug.DrawRay(hit.point, hit.normal, Color.blue, 1f);
direction = Vector3.Reflect(direction, hit.normal).normalized;
}
else
{
break;
}
}
else
{
points.Add(origin + direction.normalized * maxDistance);
break;
}
}
lineRenderer.positionCount = points.Count;
lineRenderer.SetPositions(points.ToArray());
}
}
it's because you are doing:
points.Add(origin + direction.normalized * maxDistance);```
you're using origin as the start for even the reflected parts of it
for the second part, the new origin should be the previous hit point
I want to get the angle from the red cube to the green cube on the x-axis
red cube is origin
green cube is position
thanks i will be need time to process this
it breaks after this, i dont think this is the issue. seems like it should only bounce based on the shield
you'll need to fix the raycast as well
wdym
from what im gathering here, it should reflect if it hits a shield. it makes sense that the end point would be the origin + direction.normalized * maxDistance and then they break; after
i feel like the blue line result makes sense, im not sure why a 90 degree angle would be expected there
What you Want is A -> B and B -> C
but you did A + the reflected arrow instead of B + the reflected arrow so you got D instead of C
So we got the green line instead of the purple
no
because origin is explicitly A in my diagram
it should be B + direction.normalized * maxDistance
And B will have been the hit.point from the first raycast
you cannot keep using origin
unless you update it for the reflected hits
Vector3 origin = transform.position + new Vector3(0, 0.5f, 0); // avoid ground```
This is the only time they're setting `origin` ^^^
it's the player's position, always
ah I see what you mean about the origin part
I think they basically just need to do origin = hit.point; if there's a hit
if (Physics.Raycast(origin, direction, out RaycastHit hit, maxDistance, hitLayerMask))
{
origin = hit.point;
points.Add(hit.point);
yes i update the origin and it works now
that might just fix it immediately
so dumb
yeah
the 90 degree part of the question confused me because im still not sure which part of this would be a 90 degree angle
but yea glad it works
it isn't 90 yeah - I think they meant that it wasn't reflecting properly over the normal
really it's angle of incidence == angle of reflection
im having trouble reading you guys with my english but thanks !
i will try to go back to understand what happend back there, math skill not good
public static float Follow(Vector3 up, Vector3 origin, Vector3 position)
{
Vector3 direction = position - origin;
direction.Normalize();
float ikAngle = Vector3.SignedAngle(direction, up, Vector3.down);
return ikAngle;
}
This is just calculating nonsense not even close to the specification
YOu said you wanted the angle around the x axis
Vector3.down is the y axis
Vector3.right / left would be the x axis
public static float Follow(Vector3 right, Vector3 origin, Vector3 position)
{
Vector3 direction = position - origin;
direction.Normalize();
float ikAngle = Vector3.SignedAngle(direction, right, Vector3.right);
Debug.Log(ikAngle);
return ikAngle;
}
This also wrong I don't know what axis to give as a parameter
Can you show a diagram of what you're trying to do?
Is this a 2D game?
3D game?
3D
some visuals would really help
The red cube is the origin position or rightFootController.transform.position
The green cube is the target position or worldSpaceTarget
ProceduralAnimator.UpdateTargetHeading
Vector3 worldSpaceTarget = offset + rightFootController.transform.position;
rightFootController.TargetHeading = IKController.Follow(
rightFootController.transform.right,
rightFootController.transform.position,
worldSpaceTarget
);
ProceduralAnimator.OnDrawGizmosSelected
private void OnDrawGizmosSelected()
{
Vector3 worldSpaceTarget = target + rightFootController.transform.position;
Gizmos.color = new Color(0f, 1f, 0f, .45f);
Gizmos.DrawCube(worldSpaceTarget, Vector3.one * 0.2f);
Gizmos.color = new Color(1f, 0f, 0f, .45f);
Gizmos.DrawCube(rightFootController.transform.position, Vector3.one * 0.2f);
}
IKController.Follow
public static float Follow(Vector3 right, Vector3 current, Vector3 position)
{
Vector3 direction = position - current;
direction.Normalize();
float ikAngle = Vector3.SignedAngle(direction, right, Vector3.right); // 90 when it should be 0, because "position" is directly below "current"
Debug.Log(ikAngle);
return ikAngle;
}
ikAngle is logged as 90
And target heading is used in this way to rotate the inverse kinematic segment in local space
Quaternion targetRotation = Quaternion.Euler(axis * _targetHeading);
// axis is (1, 0, 0)
transform.localRotation = Quaternion.RotateTowards(
transform.localRotation,
targetRotation,
RotationSpeed * Time.deltaTime
);
anyone have tmp input fields work fine in editor, but dont let u use them in a build?
This is one got really close but is ping ponging between -179, 179 after it reaches the angle. Also after rotating the armature it calculates it wrong again.
Vector3 worldSpaceTarget = target + rightFootController.transform.position;
rightFootController.TargetHeading = IKController.Follow(
rightFootController.transform.up,
rightFootController.transform.position,
worldSpaceTarget,
Vector3.right
);
so it's not Vector3.right you want as the axis
it's rightFootController.transform.right
correct?
Yes correct
also these seem wrong then:
rightFootController.TargetHeading = IKController.Follow(
rightFootController.transform.right,
rightFootController.transform.position,
worldSpaceTarget
);```
right wouldn't be one of the directions, and transform.position is definitely not a direction
it calculates the direction
public static float Follow(Vector3 currentAxis, Vector3 current, Vector3 position)
{
Vector3 direction = position - current;
direction.Normalize();
float ikAngle = Vector3.SignedAngle(currentAxis, direction, Vector3.right);
Debug.Log(ikAngle);
return ikAngle;
}
Alright but Vector3.SignedAngle(currentAxis, direction, Vector3.right); doesn't make sense if currentAxis and V3.right are the same direction vector
I think I'm still not clear exactly which angle you're trying to calculate
the x axis
"the x axis" doesn't tell me anything really
you have this object which is facing.. down
An angle needs 3 points
two directions
what are the points/directions here?
(in this diagram the "axis" is pointing out of the screen through that "fulcrum" point
The dots are points and the lines are directions
Yes now, what are the corresponding points and directions on your robot
The top is Vector3.up
The bottom is the current
The right is is position
well the top is really current + Vector3.up
but a sa direction yyeah it's Vector3.up
so the two directions are Vector3.up and position - current
and finally what's the axis
x axis
in the blue dots diagram it's pointing out of your screen
local x axis of the right foot
So then it should be this, right?
Vector3.SignedAngle(Vector3.up, direction, rightFootController.transform.right);```
After swapping out Vector3.up to Vector3.down it works
Hey, am I correct if I say that these are the steps to follow to make localization work in a game please :
-
- Install the Localization package
-
- Choose the languages I want to localize
-
- Create the Localization table
-
- Create entries and give them name for the key
-
- Fill those entries with appropriate translation for each language
In Code :
-
- Create a string variable that contains the name of the table ( i.e
tableName)
- Create a string variable that contains the name of the table ( i.e
-
- Create a string variable that contains the name of the entry (i.e
tableEntry)
- Create a string variable that contains the name of the entry (i.e
-
- Create a
LocalizedStringvariable and instantiate it to anew LocalizedString(tableName, tableEntry);
- Create a
-
- Subscribe to
StringChangedfor the localized string variable inOnEnable()
- Subscribe to
-
- In
OnStringChangedmethod, change the UI text there by assigning the parameterlocalizedTextto it
- In
this really looks like some AI list.
https://docs.unity3d.com/Packages/com.unity.localization@1.5/manual/index.html
follow the quick guide, or really any guide and just 
It's not an AI list, I made the list myself after struggling to implement it the first time here https://discord.com/channels/489222168727519232/1373660722197823560
And i already read the doc it didn't help me that much
i see, i dont see anything wrong with the steps at least so i believe its fine. It just seemed like AI because its very focused on stuff you probably dont need in a guide. Like the "in code" steps 1 and 2 surely can be excluded.
Also https://docs.unity3d.com/Packages/com.unity.localization@1.0/api/UnityEngine.Localization.LocalizedString.html localized string doesn't have to take string in the parameters according to the docs.
TableReference tableReference
Reference to the String Table Collection. This can either be the name of the collection as a string or the Collection Guid as a System.Guid.TableEntryReference entryReference
Reference to the String Table Collection entry. This can either be the name of the Key as a string or the long Key Id.
what's a Guid ?
And how to get it ?
the docs i linked has a link to the docs for Guid
https://learn.microsoft.com/en-us/dotnet/api/system.guid?view=net-9.0. its basically just a unique ID
you dont specifically need it here if what you have works
but how to get it ? Like how to get the one of my collection ?
Like I guess I need the name of collection and a special type to save that collection
ah i see what you're asking. truthfully not sure where that value comes from and I can't really check right now
its surely somewhere on the UI but yea I didn't see it from skimming through screenshots on the docs
is there any known fix for this issue https://discussions.unity.com/t/problems-with-color-scheme-in-rider/1635472 ?
any classes and functions inherited from monobehavior turns white in rider
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
for unity kinda, im used to use it for c++ and UE
yeah ive already done all of that
seems like a bug since i found the forum post mentionning it
or its this setting, which shouldnt be applied
yeah disabling "inherited values from" and "Foreground" fixs this
Is there a way to lock a Script from any changes?
but why?
version control + setting appropriate permissions
I assume you want your teammates not to touch certain scripts?
That's what version control is for, only accept commits that conform to the project standards
anyone here familiar with Sprite.OverrideGeometry?
At runtime I'm trying to create a sprite. Just as a test I'm trying to only generate the top left triangle for the geometry, but this just gives me a normal rectangular sprite the size of the texture.
def = Sprite.Create(texture,//texture
new Rect(0, 0, texture.width, texture.height),//rect
Vector2.zero,//pivot
32,//pixelsPerUnit
0,//extrude
SpriteMeshType.Tight,//meshType
Vector4.zero,//border
false);//genPhysicsFallback
def.OverrideGeometry(
[
new Vector2(0,0),
new Vector2(0, texture.height),
new Vector2(texture.width, texture.height),
],//vectors
[0, 1, 2]);//triangles
it looks the same as when I don't call OverrideGeometry
I'm preparing a practical examination and I want the students to only change code in a single file, everything else should be Read Only
Put the stuff you don't want the to be able to edit in a .dll
Yeah that was my idea as well
remember that c# is easily decompilable so it wont obscure code well but should suit your needs
If you want code that cannot be easily "read" it will need to be done in c/cpp/other c abi compatible lang and compiled into a shared lib.
Is there a way to integrate a chatgpt agent into our unity project, like we would a package?
You could put the code on Github as a package, then include it into the project using the git url.
Not a very tamper proof situation but unless they start copying things around it'll remain read-only, and as a benefit it'll be easy to read the code without decompilation.
I mean, if a student still attempts to modify code by compiling a whole DLL then that's their problem at that point
I doubt this is on a level where they can do that anyway
I'm surprised the most simple answer was not given, just make a folder explicitly named "read-only" and put scripts there. Clearly indicate the scripts are to not be modified and if the student does so anyway then that's their problem
@nova roost
Unless your student supplies the final game in which case you can't compile yourself with proper files, then it's different
you can get the satisfaction when a student complains their code doesnt work, and the cause was that they went and modified code in the "DO NOT EDIT THIS CODE" folder 😆
see it as an indication of which students can follow basic instructions
haha - yes I plan to basically put all the "editable" methods in a single file and that file is basically their hand-in. I just replace that file in my version and it needs to work. I just name all the other folders ands scripts "READONLY"
.dll wont work because they should be able to check some of the code, but dont change it. I thought it would be great to put like a lock on this file (like office allows you to do) with an additional security check "you're not supposed to edit this"
this seems fallible
- student passes an invalid argument to an internal "read-only" method
- error points to the readonly file
- student clicks on error and opens the file
- doesn't notice what folder is in and just shrugs and "fixes" it
so now the "readonly" folder has been modified without the student actually seeing what the folder said
You can also just reject the submission if it contains modification to files outside of the designated directory. Or make students only able to submit their files in said directory. Or treat all student submitted files as files in said directory.
how would the "readonly" files be supplied?
i feel like making them actually readonly would be pretty easy but maybe that doesn't work with how you're distributing them?
So my current plan is to give them a simple project where some functions are connected, but not implemented
so they have one file with a few empty functions inside that are being called from other scripts.
That way they only actually submit that file
That sounds like the easiest way.
I think you are overthinking this and should just do as FusedQyou suggested here #archived-code-general message
I've had this same situation given to me on tests and assignments, just not in a unity context. Just make it clear they are read only and to not modify anything. State that you have your own copy of the files and will overwrite that folder with the original, so any changes wont be used. You'd be doing this anyways if you gave them files with empty functions. It might be more clear to some people what the functions are actually doing if they can skim the code
if someone modifies it still and their actual code has a compile/logic error after, thats entirely on them
how do i change the aspect ratio of the screen thru code
thx
Can anyone help me with a delegate issue? I'm setting up some buttons in Start() and when I press the buttons later they don't work.
for (int i = 0; i < 13; i++) { ResultFrame.Find(i.ToString() + "/Bet/Button+").GetComponent<Button>() .onClick.AddListener(delegate { IncrementBet(10, i); }); ResultFrame.Find(i.ToString() + "/Bet/Button-").GetComponent<Button>() .onClick.AddListener(delegate { IncrementBet(-10, i); }); }
With debugging I see that all of the buttons when clicked later call IncrementBet(val, 13) with 13 being outside the range, this is because the delegate is pointing to the integer value i, which at the end of the loop is 13, right? How do I set that properly?
we gonna ignore that crazy find usage in the loop?
i've mostly given up on trying to correct things like that because people hardly ever listen 🤷♂️
how can I make it so the red bar is contained only in the card it's in
the red bar is spinning and it shouldn't show on the cards next to it
please help
the prefab looks like this
the 'ToHit' section is what conatins the bar and the black background
What's wrong with it?
Finding by name is just unreliable and slow. You should use a serialized array or list instead and have it be the type you need already:
[SerializeField]
List<Button> buttons;
Unreliable and slow for something that happens once during Start and is procedurally generated in the code?
If these are all UI Images, then sounds like you need a Mask within the card.
If they're sprites, then SpriteMask
they're sprites and Im already using a SpriteMask, the problem is the cards kinda overlap on each other
There's a way to handle that, where by you can localize a sprite to just the parent mask, even though other sprites are on the same layer and order. Gimme a moment to remember what it was
Jesus christ a Find and a GetComponent, multiple times, in a loop
Set those in the inspector
oh, thank you very much
Or, if they're spawned in at runtime, add them to the list as they're spawned
Again, something that happens ONCE during START for a grand total of 12 times. it takes a microsecond to complete and then never gets called again
SortingGroup, that's what it was. With that component you can force them to be local to the mask.
https://docs.unity3d.com/6000.1/Documentation/Manual/sprite/sorting-group/sorting-group-landing.html
okeeeee, thanks yet again
I think I see the problem, and its a nuance of delegates. Make a new integer in the loop to store i and assign that to the delegate, and not i itself.
Oh, boxfriend's tutorial covered that, nevermind!
You are right in general, but you might as well do this how people mention. You already should probably be removing the listeners later on to these same buttons, and most likely making them non-interactable at different points during the buttons' lifetimes. All of those will be useful to have access to the list of buttons.
But if it works for you this way, then ok.
Nope, it's an option menu that is populated once, the buttons are set, and sometimes the entire option menu game object is hidden, but it's never unloaded/reloaded or changed after that point
why my ai doesnt follow the ball, i use a prefab in the transform spot
{
GameObject ballObj = GameObject.FindWithTag("Ball");
if (ballObj != null)
ballTransform = ballObj.transform;
}```
only when i drag the ball from the hierachy
[SerializeField] private Transform ballTransform;
but what if my ball isn't spawned yet
how to fix that
prefabs do not exist in the scene, so naturally a prefab assigned to that variable won't be the one that is actually in the scene. you need to pass the reference when the object is spawned
with findwithtag?
ideally without using any of the Find methods. whatever spawns the ball can pass the reference to this object or can invoke an event
i got rigidbody and 2d sphere on my ball but it doesnt collide
how is it moving. also by "2d sphere" do you mean a "circle" collider?
yes
What's it supposed to collide with, and what's the Rigidbody's BodyType?
Aight im trying to make a simple flying enemy in a side scroller 2d game, and its currently able to be knocked back by bullets. Lets say I want it to drift back to its original position after being knocked back, how could that be done? Or even making it move back towards a programmed path it takes after being knocked back
could I just make waypoints along its path and have a coroutine check if its on them or not?
I was tihnking about using Vector2.MoveTowards but I think that ignores physics so maybe acceleration or forces?
you can use move towards and then set position on the rigidbody instead to move with physics
Screen.SetResolution isnt working for me
it wont change to landscape
nor will it change to portrait when in landscape first
public void MoveToScene(int sceneID)
{
if (sceneID > 1)
{
Screen.orientation = ScreenOrientation.LandscapeLeft;
Screen.SetResolution(2400, 1080, true);
}
if (sceneID < 2)
{
Screen.orientation = ScreenOrientation.Portrait;
Screen.SetResolution(1080, 2400, true);
}
SceneManager.LoadScene(sceneID);
}
is this full screen or windowed?
windowed
so i have it portrait right now
starting from the title page
but when i go into the game it still stays portrait
your if statements are confusing and I am guessing not really what you want
oh is that why
It could be 'right'. It is just written in a way that looks like that's not what you intended.
no it still stays portrait when i change to "else"
is it because my editor resolution is a specific size
how do i go full screen
omg i have to pay to go full screen????
er no? what unity version is this??
What?
i googled how to go full screen and ppl said unity removed that feature
so i downloaded a github project for it
ok so anyway
i changed my aspect ratio to 4k
it shows everything fine but it's not what i wanted
my game is for mobile so it needs a specific ratio
im out of ideas
This is just running it in editor and you're trying to change this? I've never done that in editor before, so not even sure what that means in that situation. The orientation property is only for mobile.
Mobile devices have many different aspect ratios, what should happen if your game is running on a device that doesn't match the one you want?
I set the resolution to full screen so it should be alright
The problem is it's not changing to landscape
Well it is in 4k
But how can I be sure
4k just has a large ass resolution that shows everything
Do I test on my phone?
You can change the resolution in editor game view.
If you don't want your game to run in portrait mode ever, you can uncheck them in project settings.
No my title page is portrait
And my game is landscape
Im just gonna test it on my phone
yea you should verify this stuff on a device or an emulator
Using different resolutions in editor will be necessary, especially for your UI layouts. You can just use this to check with your gameplay (landscape) scenes.
Guys, how hard will it be a for beginner++ to make a chess game (including the AI part) ?
Hard
8.86/10
But there are many guides out there for it
argh 😦
even the AI (that increase in difficulty or even learn to be better) ?
if you want something remotely decent for the AI, you'd want to use some preexisting chess engine like stockfish. Im not sure how youd integrate it with unity though. If this is just for learning, id really just focus on the actual gameplay elements and make a dumb AI.
It's for learning and also release it as a commercial game if I push it that far
I'd still classify this more as learning. Release it still if you want but I wouldnt expect an exact copy of chess with less features than existing free websites to get many downloads
I never said less features, but the opposite, meaning more feature, new mechanics, etc...
Chess 2: The Sequel is the next step in the evolution of chess tuned for more viable options, strategic interest, and years and years of expert play.
There are six armies to choose from, each with their own abilities and unique flavor:
- Classic: The original army from classic chess and the only army with a queen.
- Two Kings: Two warrior kings…
$5.99
62
Looks boring compared to what I want to make
Unnecessary to put another game down
Multi dimensional chess and shotgun chess are also really cool
tell me more 👀
What is it?5D Chess With Multiverse Time Travel the first ever chess variant with spatial, temporal, and parallel dimensions. It's the first ever chess variant with multiverse time travel!
Features
- Sharpen your tactics by solving a collection of multiverse chess puzzles.
- Practice against four different AI personalities, each with different stre…
$11.99
7372
#archived-code-general message
be realistic. if you're asking how hard it is to implement chess, how are you already planning to have more features than what chess offers?
spend 20 minutes on popular chess websites and you'll see just how many features there are
That's why I'm asking because I'm really bad at judging difficulty of things
Assume everything is about ten times harder than you expect, even when you take into account this advice
What the heck, it's impossible to play this kind of game without ending in an asylum 😄
How can I call my knockback code on my ai script? I want to be able to shoot my 2d enemy while its flying towards me but it currently does not take knockback since its locked out of it due to movement
I currently have both these scripts on the enemy
I cant call TakeDamage since it takes parameters and the update function is void
What does one thing have to do with the other?
My TakeDamage script does the knockback at the moment
ok, so call it
whenever the conditions happen in which you want it to take damage, call TakeDamage
but takedmg calls parameters and I thought update has to be void
first of all void is a return type
or have I been trolling myself
which has nothing to do with parameters
second of all i don't see why it matters what parameters or eturn type Update has
We're talking about calling a different function
where do you want to call TakeDamage from?
the if statement
I was thinking about doing if !TakeDamage()
so if I was not taking damage at the moment the AI could freely move
why would TakeDamage be an if condition?
🤔
I dont know
im just spitballing here
I dont have a script that specifically calls knockback since I use it in the takedmg
What are you trying to do, I don't really understand. I guess you're saying you don't want that code to run if TakeDamage... happened... recently? This frame?
SOmething like that?
something like that
you would communicate whatever information you need to communicate through variables
How does reflected/reserved functions in monibehaviors such as OnTriggerEnter are called/registered when the "event" (in this example a physics event) happens.
Is it a delegate registration on game init ? Or something more dynamic running on each event occurrence
could a bool like tookDamageThisFrame or something
then you would do if (!tookDamageThisFrame)
yes thats what I was thinking
and you would set it to the appropriate value at the appropriate time
I use that in my gun recoil script btu wasnt sure if it applied here
Im asking this because im wondering of the overhead of such functions
pkay hold on I think I can figure it out
The game engine does reflection at some point (possibly at compile time in the cqase of IL2CPP, but at runtime in Mono) and saves the MethodInfo for use when it needs it
I just wanst using my brain folds
So if i have 300 monos having a OnTrigger function, this would obviously take some memory space, but what about frame time, would this be impacted ?
Basically i have 300 Objects A and a few Objects B, im wondering if it changes something if the OnTrigger function is on the Object A or B mono
Probably micro optimization but id rather ask then discover it to late
It doesn't matter how many copies of the script there are in the scene
the method reflection info only takes memory once
If you are having a framerate issue, you should use the profiler to find the bottleneck.
How does it get all instances afterwards ?
Whaqt do you mean
the game engine certainly keeps a collection of all the objects in the scene
it simply iterates over that
I dont have much time to make my project so im asking in advance to gain some time, but yeah ideally i would try one way then profile it
you are wasting time thinking about this, i assure you
if you don't have much time, you should be focusing on the game design and implementation
If you don't have time to profile it you don't have time to care about performance
if and when you find a performance problem, then you use the profiler and see what the issue is
You said the reflection system gets only one "instance" of a mono.
So im wondering how the physics engine communicates on physics event
it gets one instance of the MethodInfo
not of the mono
Sadly i have to care about the latter
Ironically
Then you have time to profile it and figure it out
Wasted a day on ECS, but wasnt suited for a short notice
The physics engine doesn't know anything about monobehacviours etc. the game engine has a mapping beteween physics object IDs and UnityENgine INstance Ids. when it gets notifications about collisions etc from the physics engine it looks up the corresponding Unity objects via instance ID then uses its internal SendMessage system to call the function. The messaging system is the thing that cares about methods existing or not on MonoBehaviours
Yeah, but refactoring because of incorrect implementation is the biggest time eater
nah
this kind of refactor is really simple typically
like - moving something from an Update loop to another loop
Its a core process in my game, refactoring it will take some time
very simple, just make sure you're following good coding practices like putting stuff in modular methods etc
anyway I've said my piece - you are most likely prematurely optimizing.
Is this event rereroute process run per physics frame ?
there's also very little youi can do about physics callbacks
those have to run on individual objects if you're using Rigidbody/OnCollisionXXX etc
I'm not sure what you mean by "event reroute process"
You said something gets the physics engine notifications and gets the corresponding mapped unity object id from the physics id to call the event on the mono instance
yes
So, in a way its a rereoute
that happens whenever it has notifications to send
but it's not doing refflection there
it's basically a bunch of C++ std::map calls most likely?? It's a closed source part of the engine so we don't know.
it's fast
I forgot this sad part of unity
I guess ill put them on the Object B, and hope it fine enough
Thanks for the insights!
Basically i have 300 Objects A and a few Objects B, im wondering if it changes something if the OnTrigger function is on the Object A or B mono
For this question - no it doesn't matter which one it's on
not in terms of performance
What might matter is if you can make it so one of those objects actually doesn't ahve a script on it at all
that would save memory
but if they both have scripts on them and you're just deciding which one to put the message on, you should make that decision based on code design principles.
So have one trigger mono manager that gets the callbacks for all colliders ?
you can't
@round violet Events listed here https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Physics.html might be a slightly more efficient way to get contact information from the physics engine.
Collider is the problem not so much the OnTrigger ;p
Unity requires callbacks on the object itself
If you used, e..g. https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Physics.ContactEvent.html to process all your collisions, that might have performance benefits though. But it has a lot of restrictions.
Thats... odd
I guess its a limitation of this reflection system design
I also wonder how much it costs for the physics engine to add/destroy a collider component frequently (or move it between parent gameobjects if this is possible?)
And last question because im really tired, but thanks to you guys tomorrow will be less painful: would a raycast per frame be the same as the process of moving an object with a collider ?
Unity physics operates mostly in the fixed loop and interpolates a lot of that information, as doing it per frame would probably be very costly with that many units
Let me rephrase it: If we take 1 object doing 1 trace per frame
VS
1 object moving around with a collider
What takes the more frame time ? For the physics engine
but doing queries yourself doesnt have that continuous collisional detection that rigidbodies do come with, so you're usually having to implement some extra logic to prevent cliping through objects
In my case its a simple "on trigger enter run some code then destroy myself"
I would think doing queries would be quicker, but that's just because there's extra work to be done with what's offered with the physic (rigidbody) solutions
I also wonder if editing the transform component is the correct way of moving a GO with a collider if no CC or RB is used
well if you don't have any controlling component then you don't have any other means to control it yeah
this isn't the place for that. collab 👇
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
forget starving artists, now we have starving coders
There’s no equivalent to a destroycanceltoken for just a gameobject right?
No.
Having this property is not totally free unfortunately, so we decided to only have it on MonoBehaviour.
is there any recommended/consensus on a free hot reload plugin ? (that ideally doesnt take a lot of setup to make it run properly)
domain reload on each play is killing my time
many have expressed their opinion on them as: they are all hot garbage (including paid ones)
so everyone in the industry is waiting 10-20s before each play test ?
some people report deriving some productivity benefits from them in certain situations (i suspect these are small-ish projects that don't make use any unsupported changes regularly)
20s on a good day
i get the productivity thing for the initial code compilation, not for the play compilation
i would say iteration time is ~30-60 in an average mid-size project and much more in large ones.
ill be honest, seems completely dumb
you can disable domain reload
maybe no hot reload plugin are perfect but im sure some are good enough to gain time
i have statics, this would fuck up things ?
its a good practice to avoid statics in the first place but there is also this: https://docs.unity3d.com/6000.1/Documentation/ScriptReference/InitializeOnEnterPlayModeAttribute.html
for now i only use them for singletons
or global shared vars across pooled objects
you can use that initializer attribute to reset them
strategically you can develop your project in a way that you do most of the game-content-creation without code changes, this speeds things up when you also disable domain reload
thats perfect
the more statics and OnValidate stuff you have the slower the project will be.
its ironic that i thought unity would be better than UE because compilation is in editor, but it seems that it isnt the case (probably because of having the whole project code in a single assembly)
the compile times usually don't matter in editor, but you can also make sure that during dev, you use the mono compiler not the IL2CPP one to speed iteration up
You can split your project up into different assemblies if you want
how do i use the mono compiler ?
you can configure that in build settings
ive done that in the past, kinda the PITA to not have circular dependencies sometimes
Yee
its a complete non-issue in a properly modularized project
yeah, but you still have medium to big assembly at some point because you cannot split everything to tiny stuff
for example the player stuff
per header update in c++ is nicer imo
you need to have one core-assembly that references everything and manages communication, then everything else can be in layer-assemblies below that
im kinda lost here, any docs or param name so i ca find it ?
Hopefully there’s maybe some improvements to compilation once we finally get coreclr
its called "scripting backend" in ProjectSettings > Player
doesn't matter that much
fast SSD helps
but really the best you can do is develop some knowledge and intuition what slows down projects. stuffing everything in one place certainly does.
aside from static stuff, what can be an issue if i disable domain reload ?
is editing props and stuff like that an issue ?
its primarly about statics and other similar things that are already loaded in editor. You need to be careful with your pools.
most (tentatively all) stuff that is part of serialization gets reset by the serializer and doesn't need a domain reload
You're also more likely to have memory leaks.
from editor or my own code ?
im also wondering it this "reset statics on start" is something i should only have in editor, or also in packaged game
A better cpu does help too, I have a 7950x3d, my play domain reload takes about 5-10 s depending on the project.
It makes no difference in a packaged game
Gonna have to do this stuff in Unity 7 anyway since domains are going away
yeah, but im not waiting for unity 7 😅
Yeah just disable the domain reload and see what bugs crop up. It's managable
what anikki sent me and this https://docs.unity3d.com/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html is enough for me now
That's unnecessary. The domain isn't kept between runs of the built player anyway
There's something weird going on with my Unity + VS.. I'll double click a script in Unity to open it, and sometimes VS will close all the already open scripts so it's just this new one open
can someone explain to me why I'm having this issue image 1 but my code says this I assign the target pos to the agents destination
I have no idea what you mean 😆
targetPos is not shown in the watch/locals window
can i have .h/.cpp like file seperation with unity .cs files ?
i like navigating in a not crowded header when im looking at the structure of a type
Anyone knows why the character controller in unity 3d doesnt prevent the player from walking on a higher angle slope than the max slope angle? Im using unity 6.1.. something 2f and i dont know if its a bug because in unity 5, my code used to work flawlessly
Unity 5?
Yeah
Do you mean 2022?
Yeah 2022
Aight, just checking you didn't just put your project through a decade of editor updates
Its not the same project but the same movement code
not really, a forward declaration like that would be meaningless in C#, but your IDE should have a structure view or the ability to collapse method bodies
Is this Move or SimpleMove?
Move
I never use simple move
I dont know if its a bug with the new version cuz it used to work in my other project in unity 2022
Works fine for me in 6000.0.47, is all I can say.
Ok
Ill do some testing when im home
Cuz rn the player can climb anything not perfectly inclined 😭 🙏
There's been some physics changes in 6.1 so maybe it is bugged
how does c# memory works with scope ?
for example, if i make a struct instance in a function scope, then pass it by ref to another object that store it in a member variable, will it be still pointing to the correct address or will it be garbage memory ?
Assigning the member value would be a copy operation
Unless that is also a ref struct
it will be a ref struct
from what i understood the c# GC will only clean it if its not referenced, i assume storing it in a living class in a member var is enough
i dont know if unity does anything more special though
If you don't care about breaking common C# code conventions, you could use the partial keyword to achieve this.
Dog.h.cs
public partial class Dog
{
public partial void Bark();
}
Dog.cs
public partial class Dog
{
public partial void Bark()
{
Console.WriteLine("Woof!");
}
}
But no one does this. More commonly, interfaces and abstract classes serve this role.
thanks for the example !
Ref structs are still stack allocated so it doesn't matter
but you are right, its better if i get use to it
There's no garbage collection on structs
is GC only for classes ?
ref structs have special usage rules to avoid danging references, it's statically enforced
so i should get a warning on compile if my struct ref would be lost ?
No it wouldn't be allowed to leave the scope of the stack
it wouldn't compile if there was a chance to have a ref to something invalid
basically i want to do this:
// Object A
SomeFunc
{
var data = new Data(); // could be class or struct
SomeObjB.SecondFunc(ref data)
}
// Object B
protected Data dataM
SecondFunc(ref data)
{
dataM = data; // i guess here its a copy ?
}
yup, it's a copy
You could do protected ref Data dataM instead
i cant, says c# version is to old
Of course it is
Please use language version 11.0 or greater.
idk what version of c# unity 6 handles
Old
this will never change 
Version 9
c# 9, with an asterisk (some missing library support for stuff like init properties)
it's not THAT old!
If Data is a class, it allocates a new object on the heap when you do new Data(). Passing it to SecondFunc as ref is passing a reference to the local data variable, which now stores a reference to the newly created heap object.
The cold hands of death will soon claim it.
but if its a class and not a struct, ref shouldnt be needed ? is doing dataM = data still a copy with a class ?
classes are reference types so every reference to them is a reference (a pointer)
*a pointer, but safe
how are they cleaned ?
one day i will get my static defaults in interfaces
Garbage collection
so i should be fine if i store my new Data object in dataM
No, you don't need ref there if Data is a class. You're passing a reference to the data variable in that case, not a direct reference to the object you created.
Why is the ref there anyway? Is it a particularly big struct?
Use a class then
fwiw you can use in instead of ref for the equivalent of const &
It's not garbage collected if the reference stays alive
class Data { }
// Object A
SomeFunc
{
var data = new Data();
SomeObjB.SecondFunc(data)
}
// Object B
protected Data dataM
SecondFunc(data)
{
dataM = data; // not a copy, dataM refernces the Data object
}
?
the keywords are very random sometimes
😅
well there's out too, ref could be inout but i don't like that name either lol
Yeah you'll want a class here. Usually stack allocations are for things that don't live past their function
Even in C++ I'd heap allocate this to be safe. In C# it's just mandatory to make a reference in this case.
A more memory efficient approach is to expose the dataM field and allowing Object A to write directly to it. Then there's no need for a copy. But that can go against encapsulation.
where is there a copy ?
If the method is only the assignment, the asm is identical
Seems to get inlined
Also when Data is a big struct?
Presumably
If Data is a struct, you are first creating one copy of it in SomeFunc, then passing it to SecondFunc where it copies the values to the dataM field.
No.
if it was a big struct, that's when making the parameter to SecondFunc a reference (ref or in) would be useful, i'd rather do that than expose a public field
(Do be careful about defensive copies with in though, that would nullify the whole point)
yeah, that's a difference from C++, where you can't call anything except const methods on a const reference, in C# it just causes a copy so you'd either need to make the struct a readonly struct or be careful to only call readonly methods
I'm using WebCamTexture for QR code scanning, on mobile with modern cameras it's taking a lot of memory, how would I go about reducing the memory usage (since QR code scanning doesn't need that high resolution)?
I can see that it has requestedWidth/requestedHeight properties, but how do they behave? Do I need to set one of them, or both of them? What values should I set them to? If a device has multiple cameras (eg main and selfie camera), would it match the selfie camera which I do not want?
But if that parameter then gets assigned to a field in Object B, the copy still has to occur. So to avoid losing encapsulation, you'd have to reverse the direction of the call, have Object B call a method on Object A, providing its field as a ref or out parameter for Object A to write into.
Docs say this:
The requested width, height and framerate specified by the parameters may not be supported by the chosen camera. In such cases, the closest available values will be used.
As for how to choose the camera, I imagine you have to enumerate WebCamTexture.devices to find which ones are rear facing.
There you can also get the available resolutions and what kind they are (wide angle, telephoto, ultra wide).
Oh I don't mean that I want to pick a specific camera, it seems like the default already picks the rear camera which is what I want. It's just that I'm not sure if requesting a width/height would cause it to pick a different camera.
Each lens on the back of the phone will be represented as a separate webcam in this, so for most modern phones, you have 2-3 rear facing cameras to choose from.
If you're using the method overload that doesn't specify the device name, I would guess it would continue to pick the same camera. Unless the documentation specifies otherwise, I wouldn't assume that every phone will default to a reasonable rear camera. Unity just says it picks the first one.
If no device name is supplied to the constructor or is passed as a null string, the first device found will be used.
Yeah it just feels like there's a lot of guess work and hoping the API works the way we assume.
You can eliminate the guess work by enumerating the devices yourself and implement your own fallback logic. Maybe your first choice is a rear facing camera of the wide angle kind. If that doesn't exist, look for a rear facing ultra wide, etc.
Right that feels like what I have to do, by going through all the devices and their resolutions, pick the smallest resolution rear camera.
Well, you probably don't want to pick the ultra wide or telephoto lens over the wide angle, even if their smallest resolution is a bit smaller. A very low resolution ultra wide might not have enough resolution to scan the QR code and the telephoto lens might be too zoomed in for the user to scan at a comfortable distance.
Oh good call.
from a list of capsules (each representing a player), how would you try to get a free space next to one of them ?
my idea for now is:
- for each capsule
- get position, and do 8 CheckCapsule (add a angle delta between each check, imagine a circle cut in 8 parts) + some position delta
- if one check returns true stop here
Eh, even the WebCamKind is unreliable on Android.
On Android devices, the hardware does not report this value, so Unity determines the
WebCamDevice.kindby calculating the Equivalent Focal Length from a calculation based on the reported focal length and matrix size. Therefore, on some Android devices, the default camera may be detected asWebCamKind.UltraWideAngleorWebCamKind.Telephoto.
If it's at least based on the focal length of the camera, then you can still trust it to tell you how zoomed in the camera is. And whatever focal length Unity determines "WideAngle" to mean, probably similar to what it is on iOS, is still going to be your preferred focal length for scanning. So if some weird Android phone has very zoomed in lenses, such that it's ultra wide gets reported as wide angle and both the wide angle and telephoto are reported as telephoto, you'd prefer to use the zoomed in ultra wide.
And if some Android phone has no camera reported as wide angle, that's where your fallback would come in and you pick the second best option.
Yeah I'd have to actually grab a few phones and test them out to see what the best approach is.
It's very annoying for these kinds of stuffs, because what works for 99% might not work for the last 1%, and if you change something then a new kind of problem happens for new 1%.
Looking at https://stackoverflow.com/questions/28466221/how-to-modify-the-size-of-a-webcamtexture on the iOS code, it also seems to suggest that even for one camera you can capture in different resolutions, and I'm not sure if Unity reports them in a device's resolution.
Each device has availableResolutions, which is a combination of width, height and framerate.
https://docs.unity3d.com/ScriptReference/WebCamDevice-availableResolutions.html
Yes, but I'm not sure if Unity reports stuffs like AVCaptureSessionPreset640x480 as resolutions of the device or not.
That iOS native API presumably is using the same camera but capture with downscaling.
Actually, if Unity does report them as available resolutions, then 352x288 might be too low res for QR code scanning.
I guess I'll just have to grab some devices and check out how the API behaves.
I can't say from experience, but I feel confident that availableResolutions is pretty much going to be 1:1 with what the native APIs are returning. Unity won't be doing any of its own downscaling or anything, just for performance sake.
I wouldn't expect Unity to downscale either, but I'm thinking the issue is that the iOS native API provides resolutions down to 320x240, which is probably too low res for QR code scanning, so on top of the camera kind heuristics I have to also set a minimum size, and fallback if somehow a device only has camera that is really that low res.
when are input events (new input system) callback sent compared to Update/FixedUpdate/LateUpdate ?
Howdy there folks! I'm reworking my spell system in my game and I was wondering what is typically a good way to structure that sort of thing.
Currently I am using a scriptable object with a few enums to select between different "effects" - for example there's a SpellSpawningArea enum, and then in the SpellMovement script on the spell prefab it determines where to start based on that selection. However, I'm worried this is going to lead to bloat as I add more spell types including ones that operate in more unique ways (such as having many different types of movement for spells).
Alternatively, I could make the scriptable object contain a unique script for the spell that's attached onto the prefab when it's instantiated or even just have a unique prefab for each spell. But then I have to create a unique script or prefab for each spell which also seems like a bad idea.
Which way do you all think is better to structure this, or is there another way that you think would work better?
Prefab workflow works, but otherwise you can make a single Spell prefab and throw SOs at it
Stick to composition if possible and not split out your logic into multiple classes
Edge cases can be easily avoided with a simple comparison
What do you mean don't split my logic into multiple classes?
You can dig yourself a hole pretty easily with inheritance
But won't using just one class just lead to having one crazy long script with too much going on?
Well, all the code doesnt need to be in one script, but yes.
How do I split up a class into multiple scripts then?
Component workflow, have a list of behaviour that it executes
You take some of the stuff in this file, and put it in another
So for example you want some movement behaviour, well my idea would be create a subclass/SO called SpellMovement where you've different variations such as standard linear movement or different types of trig methods for wave movement. So in your Spell class you'll have a list of SpellMovement that it'll read from in your update loops.
Which you can blend together to make your own patterns from multiple of these modules
So I'd have a main Spell class, which then calls MoveSpell, and then MoveSpell determines how it moves based on something else? Or am I misunderstanding
If you want to shorten this script, that would be the idea yes. I usually like to throw in a bunch of animation curves and stuff to blend together for movement
Now, if you don't populate your SpellMovement list at all, then the Spell doesnt need to execute anything to move and you can consider it as some stationary spell
Ah, gotcha.
That makes sense for movement, and so I assume for a spell that is attached to a player I would have some sort of bool in the scriptableObject that determines whether or not it should be childed to a player object?
I have a dash spell for example, which moves the character and shows particles behind them
Personally I'd handle that as an independent type of feature not so much a spell, but say that the dash did do damage to enemies then yes I would make a isLocal to source bool
So you'll have to invoke your method with parameters such that CastSpell(SourceEntity entity, Vector3 location, Vector3 direction) at minimal even if you don't need to use all parameters
If you did have spells that directly targted enemies, then you'll need to make an override probably and make one with the target entity
or just make a bunch of default parameters that you check is null
Makes sense, I could always just have a parameters that are like "CastSpell(Vector2 startPosition, Transform targetEntity)"
SpellMovement can be SOs or some C# class, doesnt matter too much. You could nest it too inside of Spell but if you wanted a smaller script it's best to do that elsewhere. SOs are nice cause it prevents too large of an inspector to scroll through
So would I just have an Enum in SpellMovement that determines the movement type? Obviously some of them can be easily done with a formula, but some are pretty unique
Sure, that works, otherwise you could derive more and do like SpellMovementWaves, SpellMovementHoming
enum works too
What do you mean by "derive more"?