#archived-code-general
1 messages · Page 235 of 1
you cannot use Application.persistentDataPath from another thread. so your task is failing silently because you aren't handling your error there
Where do you assign these fields?
what do you mean?
well there's your problem
those are just fields and properties
you need to put something in them
ah, okay
that's where you'd be assigning the instace and inputManager fields
that seems reasonable enough
is inputManager assigned as well?
should I do so
which would be your problem
it doesn't matter that there's an InputManager component on the same object
I remember doing another project in which it wasn´t necessary
you must put something in the field yourself
If both managers are going to be on the same object, you could just do inputManager = GetComponent<InputManager>(); in that Awake code
thus: GameManager will, in its Awake method, grab the sibling InputManager component and store it into its inputManager field
Does anyone know how to change the FindObjectofType to pass a different value in the array depending on which cardslot this is placed into? currently it only updates the first element in the array
oh ok thanks let see
however I´m a little confused it worked on my other project and not on this one
if you want to get a reference to a specific CardAttack object, then do not use FindObjectOfType, that just returns the first CardAttack object it finds in the scene. here are other ways to get a reference: https://unity.huh.how/references
it works! thanks @heady iris
there is only one object with CardAttack
You could share the code from there
the problem is that it updates the wrong element in the playerCards class array
It's good to have a solid understanding of what is and isn't working
oh my mistake i misunderstood your question. the reason it only updates the first elemtent of the playerCards array is because you pass 0 as the index
you need to pass the index you would like to modify
not sure how I would do that based on the cardslot I am placing it into
I tried using tags but that didn't work
here's how I tried using tags
i don't really understand your problem
wdym you tried using tags? how is a tag relevant? you are currently passing 0 as the second parameter of the SetPlayerCard method. pass the index you want to modify instead
Do you have many CardSlot instances?
and the fifth card slot should cause you to set the fifth player card?
this is from my other project
here's what the problem looks like in the inspector
oof, that site doesn't use monospaced text :p
gdl.space is nice https://gdl.space/mobehewuco.cs
It's almost worse than just pasting it unformatted right here
hmm, this code wouldn't work. i do see you have a "todo" comment:
/// <summary>
/// START
/// Needs to assign _input
/// </summary>
private void Start()
{
}
make sure you didn't just give InputManager its own instance field and its own static Instance property
why does the object calling the SetPlayerCard method need to pass the index? just look for the next empty index inside that method if you are just assigning to the next available index
Anyone know a good starting point, to start learning 2D enemy behavior?
Such as a video series? It can be from places like Learn Unity or Youtube.
In this course, Dr Penny de Byl reveals the most popular AI techniques used for creating believable game characters using her internationally acclaimed teaching style and knowledge from over 25 years researching and working with games, computer graphics and artificial intelligence. Throughout, you will follow along with hands-on workshops design...
Thank you! Have a great day!
https://gdl.space/hawanafato.cs
Can someone take a peek at my save system and see what I'm doing wrong?
Hmm you mean my multi threading? This is my first save system I've built. I don't know much about it.
yes, you are using Application.persistentDataPath in your anonymous method that is being passed to Task.Run. don't do that
I also think I'm not calling Request save anywhere and I think maybe i should
I'm not sure what you mean by my anonymous method
task.run(()=>{});
ohh
That's how it writes the file
what should i use there? I used that because it's supposed to be crossplatform
you should not be calling Application.persistentDataPath inside of that. get the path before you call Task.Run
private void SaveDataAsync()
{
string filePath = Path.Combine(Application.persistentDataPath, "characterData.dat");
Task.Run(() =>
{
// Assuming curCharData is the current instance of CharacterData to be saved
DataSerializer.SerializeObject(filePath, curCharData);
Debug.Log(filePath);
// You can also handle exceptions here to deal with any serialization errors
});
}```
problaby shouldnt run the debug there either?
that is fine
for future reference, if you want to catch errors that happen due to accessing unity stuff off the main thread, you should wrap it in a try/catch and log the error in the catch
can binaryformatter work with monobehaviour?
binaryformatter shouldn't be used at all. but also they shouldn't be serializing an entire MB anyway
so the entire system they have going is kind of fucked
What should I use instead of bynary formatter? I heard it was safer and smaller then JSON
Also that debug log in my reqest save never gets called. I think becasue I'm never calling Request save. But I'm not sure wherer I would call it or when
binary formatter is certainly not safer than json. and if by "safer" you actually mean harder to modify, there's not really a whole lot you'll be able to do about preventing people from modifying the files stored on their devices
you call it when you want to save
Do you recommend JSON?
yes, you can start off just using unity's JsonUtility and if you end up needing anything more advanced you can swap to newtonsoft or you can use BinaryReader/Writer if you want to structure it manually or use some package like messagepack if you want a fairly easy to use solution
Hmm. I am calling characterData.AddItem in my playercontroller. I don't want to attach my save manager to my player controller. So i'm not sure where to call the saveManager.Request save, except for maybe in my game manager, in the update method. Do you think that's a good idea or a dumb one?
i think you need to rethink your entire save system before you worry too much about where you call it from tbh
you shouldn't be trying to serialize an entire monobehaviour. create a type that holds just the data from that MB that you want to store and serialize that instead
Regaurding this I am hoping to make this a mobile game, and it wont save entire game states, just inventory changes, and scores if the mission is won.
I dont think i'm even using Monobehaviours propeties on that script. In fact I just eraced it and i dont think it affected anything
huh?
[Serializable]
public class CharacterData
{
[SerializeField] List<WeaponStats> Items = new List<WeaponStats>();
private bool isDirty = false;
public void AddItem(WeaponStats item)
{
Items.Add(item);
isDirty = true;
}
public void RemoveItem(WeaponStats item)
{
Items.Remove(item);
isDirty = true;
}
public bool NeedSave()
{
return isDirty;
}
public void ResetSaveFlag()
{
isDirty = false;
}
}
this was the class that I am trying to Serialize, I just removed the : Monobehaviour from it
ah yeah, that will work provided you do not need to attach it as a component (so no GetComponent<CharacterData>)
I am attaching it to an empty game object
shoot.
damn.
hmm ok
well, if i do start over, or go watch some tutorials, does my debouncing, asynchronys, file pathing all work?
or look like their gonna work
public class SaveManager : MonoBehaviour
{
public static SaveManager Instance;
public CharacterData curCharData;
private float saveCooldown = 5f;
private float lastSaveTime = -Mathf.Infinity;
#region Singleton
private void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else if (Instance != this)
{
Destroy(gameObject);
}
}
#endregion
public void RequestSave()
{
if(curCharData.NeedSave())
{
if (Time.time - lastSaveTime > saveCooldown)
{
lastSaveTime = Time.time;
SaveDataAsync();
curCharData.ResetSaveFlag();
}
}
}
private void SaveDataAsync()
{
string filePath = Path.Combine(Application.persistentDataPath, "characterData.dat");
Task.Run(() =>
{
// Assuming curCharData is the current instance of CharacterData to be saved
DataSerializer.SerializeObject(filePath, curCharData);
Debug.Log(filePath);
// You can also handle exceptions here to deal with any serialization errors
});
}
public void LoadCharacterData()
{
string filePath = Path.Combine(Application.persistentDataPath, "characterData.dat");
curCharData = DataSerializer.DeserializeObject<CharacterData>(filePath);
}```
I dont know anything about this I just heard that debouncing was good for an auto save system that triggers whenever you pick up an item given sometimes you will be picking up a bunch of items at once, Asynchronyous saves is good for not bogging the thread running the graphics, and the way i am file pathing is crossplatform
@leaden ice Found a nice write up on a solution to my issue with using a timeline. I love that this guy wrote a blog on it, and made his project accessible on Git so you can see how it works.
https://blog.unity.com/technology/creative-scripting-for-timeline
@simple egret I'd still like to see what you were speaking of, if you ever find it! @hexed pecan I know you were interested too. Not sure if the link above will help you in your case, but if it does...nice!
hey gang im having a really weird issue with these lines that do a player respawn. the first image is how it was working before as placeholder, both lines worked. but then i changed some things around to work with my checkpoint and collision triggered deathpits and now only the rotation is being applied (see second image)
that was it! thank you 
Is there any way to code a custom cinemachine input axis controller that instead of moving a camera rotates a player?
(using CM3.0)
I'm trying to create a script to set a rect transforms size to the safe area, but cannot for the life of me get the scaling correct. This is what I have currently https://gdl.space/pojanuyida.cs and it's always slightly wrong (yellow is expected, red is actual)
Here are the canvas settings
I'm modfiying values in my scriptable object and its saving it out even after play mode, how do I get around this.
its working as intended
I want the SO to reset when playmode ends
you will need to make custom editor for that
I don't think there is another way
Hello , I'm currently making a multiplayer from scratch by using WebSocket. And I wanted to know what would be the best way to display bullets when an ennemie fire , because right now we can only see enemie moving and turning, and we can also take damage and die from ennemie but we can't see theirs bullets.
what do you think :
-should I send the cordinate of each bullet each frame to each player
or
-should I tried to replecate the shot when the amo is fired just by getting the velocity of the bullet the rotation of the player and the rotation the dispersion of shots?
This is not ideal then, maybe SO is not the way to go, don't know why it must reset every time
Hey I have two hands(here O) with a configurable joint on them each and an object(here X) that i want two grab with my two hands
would it be possible to calibrate the cofigurable joints in a way so that when i move my hands away from the object that it would stay in the middle of the hands... like this
OXO
O X O
O X O
Set the length of the joints to half the distance from the hands?
I am so incredibly confused, I have an animator, where i want to switch back to the walk animation at a condition. If i put the transition from any state to walk it works but if i put it from attack, there is no attacking, only walking
I haven't been able to find the specific video, but another one which I think use the same tool called Yarn Spinner.
It's some scripting language that compiles into a graph, and vice-versa, and is integrable to Unity
wdym set the length of a joint, what in this variable mess of a configurable joint is its length?
Does anybody have any idea if this is normal with the Vsync?
Also it's getting those spikes that do not feel in game. I've noticed they are from VSYNC
What is the "this" in that picture that you're concerned about?
Yes. The Rendering Thread is waiting for the Main Thread and the Main Thread is waiting for the TargetFPS.
So I have a cinemamachine 2d that has a farming transposer that lets me move around a few steps before moving the camera. This feature is very good for the game I want, however, how can I make the camera recenter after a few seconds after I have moved the few steps?
Please help!
it provides the error
UserProfile' does not contain a definition for 'PhoneNumber'
My code
if (User != null)
{
// Create a user profile and set the username
UserProfile profile = new UserProfile
{
DisplayName = _username,
PhoneNumber = _number
};
// Call the Firebase auth update user profile function passing the profile with the username
Task ProfileTask = User.UpdateUserProfileAsync(profile);
// Wait until the task completes
yield return new WaitUntil(() => ProfileTask.IsCompleted);
What should I do?
Show the definition of your UserProfile class
And use code blocks to post !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To 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.
Yes but now for class UserProfile if you created it
I think I don't have that class
Ah yeah, it's from the Firebase library
This does not have a PhoneNumber property. It only has two: DisplayName and PhotoUrl
you are right! What should I do if I want phone number?
Looking at the docs, FirebaseUser has it, did you mean to use that class?
Yes I think, essentially, I want the phone number to be displayed on my text panel along with the username,since I have a register input field of phonenumber and username
about the long yellow bars and the spikes that occured from vsync
That's what vsync does. It fills up the remaining time so that the framerate stays constant.
The spikes aren't normal, but if they don't lag the game then it might be a measuring error or something like that
this is a code realted channel
Sorry, just noticed #🏃┃animation . Going there 👟
can an extension method be added to be a static member of a class?
ty tina. that's unfortunate
separate question: if two floats are approximately equal, but not exactly equal, does > just give an arbitrary result?
no
so C#'s > and < are smart enough?
for reference. I'm making an extension method right now for the Bounds struct to quickly get the intersection
nothing to do with C#. It would be a very poor FPU that could not tell which was the greater of 2 float numbers
I just don't know how smart the float class is implemented in C#. Since we do need to use Mathf.Approximately to truly check ==
again, nothing to do with C#
you can simulate hardware in software level though, but in an extremely bad performance
I effectively want to ask, is there a real difference between
|| (newMin.y > newMax.y && !Mathf.Approximately(newMin.y, newMax.y))
|| (newMin.z > newMax.z && !Mathf.Approximately(newMin.z, newMax.z))){```
vs
```if ((newMin.x > newMax.x || newMin.y > newMax.y || newMin.z > newMax.z) {```
because the latter feels like what the language would guide me to, but I think the first would be necessary to really check for approximate floats not accidentally tripping the >
no, the first is totally unnecessary
you can change it to a>A+THRESHOLD
> and < is done by comparing the sign then exponent then mantissa
I see. so threshold is probably the smartest way.
so in this case, it would be + Mathf.Epsilon
easiest way is (A-B) < or > 0
I think I'll lead with
|| newMin.y > newMax.y + Mathf.Epsilon
|| newMin.z > newMax.z + Mathf.Epsilon) {```
dangerous
oh, because of the float precision
actually i dont think mathd.epsilon is useful anyway for threshold
1 0000_0000 followed by 22 of '0' then '1'
if you add this smallest unit to any floating point number, i believe it will just be rounded of
|| newMin.y - newMax.y > Mathf.Epsilon
|| newMin.z - newMax.z > Mathf.Epsilon) return default;```
this would lead to stable subtraction, i think
the computational errors will be accumulated, using a number can actually be said to 0 is not a good way for threshold
return Abs (b - a) < Max (1E-06f * Max (Abs (a), Abs (b)), Epsilon * 8f);
}```
wow. what an implementation lol
I'm getting the vibe here that I should probably use the Approximately method to be consistent.
this is very dumb
this is standard float math
I'm going to just hardcode a threshold of 1E-6, and be done with it
I get that, but it should not require mental work to figure out how to do a proper < inequality
Is it possible to do Rigidbody.Cast() from another point (not the current point of the rb) without actually moving the object?
Or maybe there is similar function to do this kind of cast
not really. but you can set rigidbody.position, cast, and then move it back
tell that to the guys who designed the single and double precision storage system
the physics simulation doesn't happen until end of fixed update, so you won't get a bunch of weird things going on with collision calls etc
You can do other forms of casting. Does it have to be rigidbody.cast?
Rigidbody.Cast is a really good method tbh
I need to check the point of collision between two objects
yeah, just move rigidbody.position. .Cast, then set rigidbody.position back
as long as you don't have some weirdness where you are depending on colliders not being synchronized etc, or multithreading, then it should be fine
Hi, I'm creating a game for free and I would like to add voice chat to it. What is the best way to do this? The game will be on Steam and the online system is being created using Mirror and FizzySteamworks. I would like to have this chat both online and offline.
I believe unity has a service for this, vivox
Does it also work over LAN?
how could i also workout the yAngle?```cs
private void HandleVision()
{
Collider[] colliders = Physics.OverlapSphere(visionPosition.position, visionRadius);
foreach(Collider collider in colliders)
{
if(collider.CompareTag("Player"))
{
var target = collider.transform;
Vector3 direction = (target.position - visionPosition.position).normalized;
float xAngle = Vector3.Angle(visionPosition.forward, direction);
float yAngle = ;
if(xAngle <= xVisionAngle / 2)
{
seesTarget = true;
}
else
{
seesTarget = false;
}
}
}
}```
the pink work is the xAngle
the yAngle has to be up and down
Its built for multiplayer so I'd assume so.
I havent used it personally
If you want a separate x and y angle,
for the x calculation, set the y to the same value for both vectors
For the y calculation set the x and z to the same values
Then do the same Vector3.Angle calculation
The error is in SaveGame(), line 68
The stuff I underlined red could be null, so you need to ensure it's not the case:
its npt
The exception you're getting says otherwise
Have you checked all of the 4 things that could be null here?
currentCharacterData, playerNetworkManager, characterName, and Value
Just because you assigned it once, doesnt mean it cant be null. Maybe some object was destroyed, something set to null, maybe theres another copy of the script and it didnt get assigned. Dont assume what values are, even if you directly plug in the reference. Debug it and confirm
i just want to check if the player is inside these angles
so for the xVisionAngle i need Vector3.Angle
Yes, what I said still applies. Your calculation for the X vision angle will need to exclude the different in height (so set the Y values to the same value)
Your Y angle calculation will need to exclude the horizontal differences
and for the yVisionAngle i think i'll need Quaternion.Angle
Why? It's the same calculation you need to do for horizontal or vertical, just with different parts of your vector
You do the same calculation (use the visionPosition.forward) but change the direction based on what I said above.
is this what you meant?```cs
Vector3 direction = (target.position - visionPosition.position).normalized;
float xAngle = Vector3.Angle(visionPosition.forward, new Vector3(direction.x, 0, direction.z));
float yAngle = Vector3.Angle(visionPosition.forward, new Vector3(0, direction.y, direction.z));
if(xAngle <= xVisionAngle / 2 && yAngle <= yVisionAngle)
{
seesTarget = true;
}
else
{
seesTarget = false;
}```
Who can help to make 3d sound in space for multiplayer (photon) so that the sound was for each player of different volume depending on the distance to the source of sound
For 3d sound and rolloff , change the Audio source to 3D (Slider) and the rolloff to whatever distance you want.
Where should i put the debugs?
Lets say I have a dict with str as key
from a str, is there a way to get the index (int) without doing a for loop ?
aa = stuff0
bb = stuff1
cc = stuff2
bb -> 1
wdym by the index? dictionaries do not store the keyvaluepairs in any specific ordering so the "index" isn't really going to be all that useful
Dictionaries are not ordered. There is no index other than the key.
from that index i will use it to get in a list a mat, thats is ordered
i was afraid of that
why not store the materials in a Dictionary<string, Material> if you need to get a material based on a string
The whole point of the dictionary is to use the key. If you want something indexed by integers just use an array
yup thats what i did now
Instead of 0 I believe you want to use the component from visionPosition, so they are the same value. You want the difference to be 0 so that it basically does not consider that axis in the angle calculation. And for the yAngle i think you want to not use direction.z either. Besides those 2 points, that is what I had in mind yes
Before the line that has the error, or use the debugger and attach a breakpoint on the line with the error.
I use rich text color tags on my logging messages to help pick them out in the spam.. but sometimes the rich text breaks if there's special characters in the error message (slashes, angle brackets). Is there a way to change a line of Log.Debug without using the rich text? Or maybe escape the middle part? I'm not 100% which characters are breaking it, but it only breaks in the summary window (the detail pane renders the color just fine..)
My wrapper for this looks like this:
UnityEngine.Debug.Log($"{AppName}: <color={ErrorColor}>E: {s}</color>");
(I tried <noparse> on the string but it didn't work)
I think it might actually be that arrow in the stack trace: --->
Need help with Organizing and making changes to save space. (Keep Changes simple and don't use Enums or anything complicated to a begginer please) https://paste.myst.rs/33hvqarh
a powerful website for storing and sharing text and code snippets. completely free and open source.
Spacing is pretty funky - I'd install SonarLint or Rosylnator which will point these out to you as you go
VS22 has spacing preferences now! They're marked as "experimental" but they work fine
I personally also like explicitly putting private before private methods (even though it's implied), but that's just a style thing.
A few other (minor) cleanup things: IsMovingBoolSet() should return a bool. Whenever you name a method "Is" it implicitly means "is _ true". If you're setting things (which you are here), then don't use "is", use "set". Rename that method from IsMovingBoolSet() to SetMovingState().
I'd also probably just change all that logic and put it behind a property
private IsMovingVerticalUp => movePlayer.moveVector.y >= 0.5f;
private IsMovingVerticalDown => movePlayer.moveVector.y <= -0.5f;
And use braces like C# conventions recommend, alone on their own line
Oh and also you're comparing against "0f" which you can't (shouldn't) do. You can, but .. you can't.
if (movePlayer.moveVector.x != 0f) This won't work like you expect (most of the time)
This is probably how it would look for me: https://pastebin.com/4W3RaaD8
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
although I don't quite know if your animations are compatible up/down with left/right so .. you might have some different logic there.. but that's what I read from your code
i'd go just one step further than this and hash the animator state names
oh and actually this definitely doesn't work as written since you're changing left/right and up/down all in the update loop, so if you're moving up AND left it's gonna restart those animations every frame
but you'll figure that out 🙂
is there any real difference in performance between 4 box colliders, and 1 polygon collider that just tries to go over the area?
I'm trying to make a rectangular annulus
Is there a good best practice to bias the Random.Range() uniform distrbution? I could say like if roll below a certain value you need to roll again against some threshold to actually get it but I'm wondering if there's a simpler pattern to do this kind of thing
hey guys a navmesh agents will always make the best route, but in my case I would like to make some deviation, for example, my npcs will always stick near the walls if it is the closes route, how can I make a deviation on the path?
I found an answer to my thing, if anyone else wants to do that see "Weighting Continuous Random Values" here https://docs.unity3d.com/Manual/class-Random.html
Anyone have any good courses / videos (paid or free) for modern ECS w/unity ? Plus for netcode for entities
https://github.com/mackysoft/Choice
I use something like this just for the algs macky has in place
netcode has a bunch of general information (documentations explains in great detail of how it and general networking between clients work) and they have a demo project called boss room you can tear apart.
is there a way for a SpriteRenderer set to tiled mode to just take in a ruletile instead of a 9sliced sprite?
Actually, I apologize, I was talking specifically about netcode for gameobject, not entities.
I also wrote something like this that's hopefully easy to use (and extremely fast). https://github.com/cdanek/KaimiraWeightedList (not specific to unity)
Just looking through that mackysoft/choice repo.. I have to say his is considerably more engineered than mine. 😛 But I think they work identically.
Interesting, ill take a look at those other options, thanks. Example animation curve impl
AnimationCurve spawnCurve = new AnimationCurve();
spawnCurve.AddKey(0.0f, 0.2f); // Start value at 0.2 to skip bottom 20% of height
spawnCurve.AddKey(0.1f, 0.4f); // For 20-40% height only cover 10% prob, half chance
spawnCurve.AddKey(0.4f, 0.7f); // For 40-70% height, cover 30% prob, standard chance
spawnCurve.AddKey(1.0f, 1.0f); // For 70-100% height, cover 60% prob, double chance
I think you have some typos? I'm not understanding your key/value pairs
what are you trying to select?
it probably would be clearer if i reversed, but it works. I'm printing out the distribution
this is for spawn locations, generating a interpolationT for the spawn area
so you can roll a Random(0,1) pass it as the time, you get back the spawnY interpolation T.
Oh, ok, i see.. Yeah for that, then you'll need a bit of math, but one approach would be to select a random number (evenly distributed) and then lerp it
Yeah
I thought you were interested in specifically selecting one item
i also have systems that do that im gonna take a look. Or selecting N. Like picking items from a table to put in a shop
Yeah, then if so, that'd be what my library would assist you with
List<WeightedListItem<string>> myItems = new()
{
new WeightedListItem<string>("Shop Item 1", 10),
new WeightedListItem<string>("Shop Item 2", 10),
new WeightedListItem<string>("Rare Shop Item", 1),
};
WeightedList<string> myWL = new(myItems);
string nextItem = myItems.Next(); // 1 or 2 most of the time, rare item 4.7% of the time
is it possible to change the navmesh agent radius in runtime and change the path?
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEditor.VersionControl;
using UnityEngine;
public class PlayerControls : MonoBehaviour
{
public float speed = 200.0f;
private Rigidbody2D rb;
public string weapon;
void spawnGun()
{
if (weapon != null)
{
}
else
{
Debug.LogError("No weapon assigned");
}
}
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.interpolation = RigidbodyInterpolation2D.Interpolate;
}
void Update()
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = transform.position.z;
Vector2 direction = mousePos - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
angle -= 90f;
rb.rotation = angle;//Quaternion.Euler(0, 0, angle);
}
void FixedUpdate()
{
float hInput = Input.GetAxisRaw("Horizontal");
float vInput = Input.GetAxisRaw("Vertical");
if (Mathf.Abs(hInput) > 0 || Mathf.Abs(vInput) > 0)
{
Vector2 direction2 = new Vector2(hInput, vInput).normalized;
Vector2 movement = direction2 * speed;
rb.velocity = movement;
rb.angularVelocity = 0f;
}
else
{
rb.velocity = Vector2.zero;
rb.angularVelocity = 0f;
}
}
}
can someone explain why this code works but i am phasing through walls somehow
it was working before but now its like lagging through the wall
i have not changed a single thing but it just suddenly decided to go through walls 😭
ill get a video just a second
could this be because of my pc?
is the rigidbody kinematic?
is its collider a trigger?
what about the collider(s) for the walls?
how would i flip the player when running the other way? since it dosent have a sprite renderer so i cant just use Flipx
then check that the objects are on layers that can collide
hmm i did mess with the layers
rotate it by 180 degrees around the Y axis
ill try that thats probably it haha
thats the only thing i messed with so would make sense
so using the transform i would rotate it ok got it thanks
oh thanks
just to test put them all on same layer did not fix 😭
i think something else is causing my issue
Why is it lagging so much i am so confused
i have one script running... and its just moving the player...
so how would i do that exactly?
would i make a bool for it?
thats the jump script no?
one on the right?
where do you have your movement left and right set up?
this is so redundant i am trynna figure out why you have it set up like this lmao
if its greater than or less than so either then its running or else that makes no sense lmao
how can it be anything other than positive or negative?
dirX = Input.GetAxisRaw("Horizontal")
yeah i know
but whats the point of the if statements
in which case it is idle
no because i want to flip it if it is negative
oh i see
if i did different than 0 i couldnt flip it
no
alright i got you mb
so there is also transform.forward
you can maybe set it to the inverse of that
or the reverse of that
you like add 180 to the transform.forward
it will take the current direction.
and give you the backward direction and apply it via that maybe if that makes sense?
not really, do you have any idea why the running animation isnt triggering?
let me see
you want me to send a clip?
did you do a Debug.log for the facing left and facing right booleans?
most likely the issue from what I can see
they are probably not passing through the if statements.
and yeah sure send the clip
looks like i am gonna have to restart my probject as well cant figure out why this thing suddendly decided not to work after i was gone for 2 days lmao
like this>
ah right of course
well wait hold on
should work either way
where is facingRight coming from
where are you updating that?
ok let me run it
yeah 
like as seperate things?
thats kinda weird though no?
looks like a platformer
horizontal right would be positive dir x
so its a bit repetative shouldnt need that
just remove facingRight you shouldnt need that =
sorry where?
just remove facingRight everywhere you dont need that
so based on your code dirX should give you if they are facing right or left
so if dirX is positive they are moving right
so they should he facing right
you should not need to check for that boolean there
and I dont see where you are updating facingRight
probably somewhere in your update()
I checked and i wasnt
ah thats probably whats causing the issue
regardless you dont need it
keep ur dirX < 0f would be going left or facing left
Is there a way to set the rotate part of transform to a value?
Because really i would just need to set that to 180 when moving left and 0 when moving right
On the Y axis
yeah transform.Rotation = Quaternion.Euler(0,0,0) i believe something like that
one sec
ill get it proper for you
yes it would
Quaternion.Euler(0, 180, 0);
transform.Rotation = Quaternion.Euler(0,180,0);
should rotate it properly i believe....
i am not sure if its in radians or not...
If it is it would be pi right?
yeah it is in degrees so should work
no it would be pi/2
wait
no ur right
i am stupid
Pi/2 is 90
Year 11 trig coming in clutch
yep ;p
Yeah you can also use transform.transform.localEulerAngles = new Vector3(0f,180f,0f); although using the Quaternion conversion would help in a more complex rotation prone to gimbal lock
but it accepts degrees
yeah I just use Quaternion because its what I was recomended before so thats that haha
never questioned it lmao
what is gimbal lock if you dont mind answering
I been on the platform for about a month now and dont know all of unity just yet haha
Ah yeah, the downside to degrees, is at certain angles they become ambiguous, so the rotations 'lock'
Basically, you rotation object seems to freeze or rotate in unexpected ways. Quaternions avoid that:) but take a few extra steps
You are doing it the right way
oh okay good haha
and seems like I found out why my game was bugging
i was gonna be so sad if i was going to have to restart it XD
I am like this seems good...
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEditor.VersionControl;
using UnityEngine;
public class PlayerControls : MonoBehaviour
{
public float speed = 200.0f;
private Rigidbody2D rb;
public string weapon;
void spawnGun()
{
if (weapon != null)
{
}
else
{
Debug.LogError("No weapon assigned");
}
}
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.interpolation = RigidbodyInterpolation2D.Interpolate;
}
void Update()
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = transform.position.z;
Vector2 direction = mousePos - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
angle -= 90f;
rb.rotation = angle;//Quaternion.Euler(0, 0, angle);
float hInput = Input.GetAxisRaw("Horizontal");
float vInput = Input.GetAxisRaw("Vertical");
if (Mathf.Abs(hInput) > 0 || Mathf.Abs(vInput) > 0)
{
Vector2 direction2 = new Vector2(hInput, vInput).normalized;
Vector2 movement = direction2 * speed;
rb.velocity = movement;
rb.angularVelocity = 0f;
}
else
{
rb.velocity = Vector2.zero;
rb.angularVelocity = 0f;
}
}
}
can you look at this the updateportion
so i was recomended FixedUpdate but
with fixedUpdate the rotation doesnt match with the frames and the character seems to jitter if that makes sense
is the angle why?
Nah you are right, you want mouse input in Update.
oh okay good
because for velocity and stuff they were like use that in fixedupdate i am like oh okay
XD
thanks ill keep doing this then
No worries, it is AOK to change those in a normal Update. It won't hurt anything that way. If it's moved to FixedUpdate, your screen and input will be out of sync
yeah thats why it was jittering before makes sense
Yeah exactly! Update basically runs everytime the screen refreshes. FixedUpdate runs about 1/4 as often, and only on the physics timing. So your script would yeah lag and stutter and miss frames. Which is mostly important because you are processing input and it'll be skipped on the between frames
Hi, I usually recommend this video to better understand the difference between Update and Fixed update.
https://youtu.be/MfIsp28TYAQ?si=WzSfb8la1Jqi_Dxv
oh okay
ill check it out thanks
so it basically in sync with the physics engine of unity.
as oppose to update runs on purely fps

Yessir
What is the best way to make a system where I can interact with some blocks (for example furnace, crafting)? How can I turn normal blocks into blocks that have interfaces and can do some actions?
Put a class on the object. Spatial query the object (like a raycast). Call a public method
Interfaces are nice here
I'd also encourage looking into inheritance as you go down that path
But with that I should switch from using prefabs to creating object oriented programming classes and create blocks this way right?
Both! I'd use a base class for the elements for example, and only override them when you have to. At the code level Iron, copper, etc are probably very similar with maybe only a texture change and some values. I'd use prefabs for the block itself. You could store the block configuration in a scriptable object, same with the recipes, etc. But I'd probably pair prefabs with inheritance. Using interfaces for the actual interfaces would be fun and smart as well.
Prefabs can have classes, so I'm not sure what the distinction is here
how would I get the value of a dropdown box?
I'm asking because I have one tile prefab with TileScript attached to it so I would have to make it so this prefab has no scripts and after spawning it I should add one of the scripts on that object (Tile, CraftingTile and so on)
You could do it that way, sure
Yeah @azure dome I'd tackle it with
BaseCrafting > SmeltingCrafting
...```
Where `BaseCrafting` would have an enum for its type. As each table would likely have a timer, input, output, etc - that code should be written once and used at the base. Where `OvenCrafting` may have an override to make sure a door is open, or fuel added, etc.
I'd do the same for the elements
```BaseCraftable > WoodCraftable
BaseCraftable > IronCraftable
```... for example.
The prefab itself would have the sprites / objects/ specific configurations. It could then also be used in a ScriptableObject or a Manager wherever you want a list of the prefab essentially
With more thought around what those are and why of course
Yeah I did it with Items so I just have to do the same thing with tiles.
Also, I have a WeaponItem class. Where should I store information about current magazine size? Because when I store it ScriptableObject and I change it it will change values of that scriptable object. Where should I save variables like ammo or durability?
Anything temporary or consumable I'd have as a separate object with the character. In an FPS example, you'd have a 1x firearm and 4x clips, probably derived from a BaseItem or something therein. And the individual clips store their current ammo and max ammo. Some games go deeper and track individual bullets as a separate data point to the clips, but it would usually be overkill.
So you may have
+ quantity
+ weapon type maybe
+ damage maybe```
You mag also have things like compatible weapons or damage strengths stored in a more common entry somewhere.
In practice, I'd have their inventory stored in a custom restorable data class for saving/ loading etc. And a prefab factory to generate the objects on a data load that should be the same factory used elsewhere for spitting out prefabs on request.
It's a good example of how separating the data type from the prefab template can help with data loading (as you just loop through their stored inventory to create the prefabs and attach them where they need to go)
But yeah, I'd treat ammo as a clip or a total stored elsewhere outside the weapon
But that's just my immediate thoughts on how to approach it. There are probably smarter ways
So instead of storing scriptable object in a slot I should load variables from scriptable object into a class?
Or I can just make it so 1 bullet is a single item, and after shooting I can just remove 1 ammo from my inventory
You could, I like to use scriptable objects as a read-only database or reference list. In practice I usually don't use them as I prefer that data stored in json files
But yeah the last way is definitely a simpler approach
All my assets have a generic template for a scriptableobject to be inserted
Oh yeah I forgot I have to save everything into a json.
For a simple game, you may just have a static int for ammo, and just count down when they fire
But I still have a logic inside scriptable object so I still have to save it in a inventory slot
Yeah, its usually just depending on how important ammo is. If it's a craftsble arrow, definitely should be it's own inventory item. If it's a shooter, a simple integer somewhere could do
But then when I want to add for example durability to my items I have to do it this way
bullet would be a single item with a canStack bool
The reason having craftable items as their own inventory item is helpful is you can make them unique easier (I.e. three +2 fire arrows, +1 poison arrow, etc)
if stackable then the type would be only discarded when the amount of int == 0
Soo I will do it like that
if you're stacking bullets then you append to the int value and discard the one to be stacked
Yup! Durability and individual characteristics --- totally make it an inventory element.
Because that'll impact sale value, repair possibilities, and unique enhancements later
It could still have its own quantity. But makes crafting a lot more interesting. A random crafted SUPER item is fun
Making this item and inventory system is the hardest thing I ever did I think.
if you try to avoid durability and stacking though you'd only need to save SO IDs when you load and reload
Yeah, usually enemies, inventory, and level generation are the time sinks
the more unique data you add to your assets the more you need to serialize/deserialize
Yeah that's what I am doing right now and I think this is the way I will leave it right now
But I know that when I finish creating base classes anad sytems for everything I will be able to just add more content and have more fun later
I have a question. I am using the 2021.3.11f1 version of Unity because the professor told me that most of the codes online are working well with older versions. I am wondering if I should upgrade to the latest version. I am trying to do the tutorial that requires me to play Lego Microgame. Should I upgrade or just leave it as it is?
Tutorials aren't included in the newer versions. 2021 is the last one you can do it with natively. I think you can find them on the Asset store if you really want to upgrade though
And yeah, most tutorials online are gonna be for older versions. There are probably a few for 2022 at this point, and MAYBE some for 2023. But for the most part it's gonna be the same things you're doing
Should I skip the step and learn next step?
Skip what step? The lego microgame?
That is a personal choice I can't advise on
Really up to you. I usually recommend against skipping stuff in learning materials though
I want to learn the coding but I am at this part where I need to learn how to play them.
so use the version that works with tutorials?
I am trying to find the LTS because I do not have the LTS in my version.
Nevermind. I got it.
If it's just this, and not a long term real project, it really won't matter at all
any 2021.3 is LTS
Nevermind. I feel like I am very inconvenience to you. So sorry!
Do the 2021 have the LTS?
No, not at all. Don't worry!
yes all 2021. is LTS thats why its called LTS
Long term (its not he latest LTS but its still supported, and fine for your usecase)
2021.3.11f1 is LTS
here's more info
https://unity.com/releases/editor/qa/lts-releases
Unity 2021.3 is now the legacy LTS. It will be updated monthly until it reaches the end of its support cycle in mid-2024.
Thank you. I am pretty eager to learn how to do the coding. So, I'll try my best. And I want to say thank you, everyone, for being patient with me.
I just realized it now.
All good. Along with what you're doing now, there are resources pinned in #💻┃code-beginner for learning more
Will definite do so. Thank you.
One quick question. Do you recommend creating the game on a Macbook or a Windows laptop? Because I have been battling on decide to get a new window laptop.
It would be fine with either. I always say it's just preference. I use Windows and it's fine. Navarone above uses Mac I think, and they certainly do great work haha
Is using transform.root a sign of bad architecture? I have a child object that acts as a sort of "hitbox", which I then use to shut off the whole gameobject.
Transform.root gives me the top level gameobject to shut off.
sounds fine to me
you'll have to keep in mind if you parent the object to something else, itll suddenly stop working. You could have a script on the child object that processes the hit and then holds a reference to the transform if its ever an issue.
Well not necessarily. I think root will return itself if it has no parent, and if I'm just shutting it off, it's probably not that bad.
Should the hitbox script have some "owningGameobject" field you think?
hi so i'm developing a mobile game and there's a bug where if i press 2 buttons simultaneously they would trigger their onclick events at the same time. how do i do it so that it will only trigger either the first button's or the second button's onclick event?
So whoever is interacting with it explicitly knows who to modify?
thats correct about the root returning itself if theres no parent, but i meant if you suddenly are parenting these objects under anything else. Like if you parent them under an empty GO for organization or any other reasons
Ah super fair.
i guess it also depends on what this is for exactly, but thats probably what id do instead. When i was messing with active ragdolls (many colliders as children objects), things got very weird. Someone working with me made it so it searches the root and stopped when it had a specific tag, but i felt it was just fragile or cant be all encomposed by 1 solution. But if you directly drag the reference you want in inspector to some script, nothing can go wrong. its just more setup
doubtful that it's in the same frame (I'm just affirming that the issue is less about this time constraint and more about the general logic), but you should probably make a bool both buttons can read from and set if one has been pressed.
ah i see, will try it. thanks
I wonder has anyone encountered problems with executing Quaternion.RotateTowards on a child with the parent having different rotations
When I do RotateTowards on a child while the parent has a rotation that is not (0, 0, 0), like on a slope, the child always rotates to look at in another place
you'll have to show more, like the code and what you're trying to rotate it towards in the first place
Ah right, actually it kind of functions like a turret, so child 1 can only look left and right (Removing X and Z local euler), in the child inside the child 1, it can only look up and down (Removing Y and Z local euler).
Parent > Child 1 > Child
If the parent of child 1 has total 0 euler, both of the childs aim at Vector3.zero
But if the parent of child 1 has a euler of (180, 0, 0), they aim at another direction
Quaternion LookRotation = Quaternion.LookRotation(Vector3.zero - transform.position, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, LookRotation, Time.fixedDeltaTime * 20);
Vector3 LocalEulerAngles = transform.localEulerAngles;
if (RemoveXE)
LocalEulerAngles.x = 0;
if (RemoveYE)
LocalEulerAngles.y = 0;
if (RemoveZE)
LocalEulerAngles.z = 0;
transform.localEulerAngles = LocalEulerAngles;```
part of the issue is gonna be that you're using euler angles, not anything with quaternions. I think you should construct the LookRotation based on where you want that to actually look, rather than construct it with all XYZ being considered and remove a certain component
So basically I should remove the X, Y and Z on the Vector3.zero - transform.position and not on the euler angles?
I think it'd make more sense, but I dont know if itll directly solve the issue. I am mainly just assuming that using euler and quaternions is causing an issue here. Im not sure if you should define upwards as Vector3.up either, if the whole object can rotate
Hello! Just asking how can I send emails with custom texts on gmail using firebase and unity? I believe google has issued that it does not receive mail from third party apps.... so I can't use smtp either, what should be the possible solution here?
IIRC there are a lot of factors when it comes to sending email without getting outright blocked or flagged as spam, starting with having a domain with the necessary email things set up. You might be able to find people here to help with hooking things up between your client, server and services, but I think for the email requirements part itself you'll be able to find better resources online.
hello people i dont know how to fix this bug
https://hastebin.com/share/iburubobaf.csharp
https://hastebin.com/share/vebinivuwe.csharp
its supposed to be taking 1 health per damage its set to 3.33 because its 3 healths so it would 1/3 of the bar it was working before but i dont know what i did
it only changes just in the end
Im looking at the code and it is actually changing the value of current heart but it only changes when the condition below 0.1 is aproved
Thank you so much!! I'm fairly new with unity, will you please suggest on where I can start? or what I exactly should I search for?
fillamount takes a value between 0 and 1
hey all! can someone help me figure this out?
I'm getting this error sometimes, when an enemy is removed from a list
its not game breaking (at least not atm), but I'm guessing as it builds up, it'll be
is it literally just because I have the list serialized, or is there something else behind it?
omg im stupid that is why i had to divide the value by /10
thanks i was strungling with that for a few hours
better to divide by startingHealth
nothing to do with the serialization.. why would that cause an error? 😄
You're trying to perform an action on something that has been disposed
it doesnt apply a force
anyone know a solution
it hits the enemy give a damage but doesn't give force,
dont cross post
Well this has very little to do with Unity right now and more to do with how email standards and providers have moved over time. I would start by looking up how email servers are setup and general information about potentially sending frequent emails.
Yeah, but how would I go about fixing it?
its not really telling me much, where the error is coming from, etc
I'd guess it comes from the script that handles the list?
I can't tell as you didn't include the stack trace
oh shoot, sorry
Select (do not double-click) the error message from one of the ObjectDisposedException. It will show the full error message
I thought I sent the one that has it, just a moment
so yeah, I'd guess it's coming from this script maybe
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
None of your scripts* actually
All of the stack trace items point to compiled code (at <memory address>:0), so it's just Unity doing its thing
If that was from your code, then you'd get a file path and a line number in the parentheses instead
haha
and it wouldn't be a load of "UnityEditor."
Which version of Unity?
Dunno why people rarely give the version number when asked that
"latest" isn't helpful 😄
because you might think 2022.3.10 is the latest, but the latest is higher
2022.3.15f1
or you might think 2022.2.15 is LTS
why'd I think that?
if its not the latest, I wouldn't say latest
or maybe thats just me
Because, from experience, A LOT of people don't understand the version numbering system and always get it wrong saying "latest". It's just easier and clearer to give the version number, isn't it
Hi I want to see which is the nearest character to me and that should either be a vampire or a camper and so now the issue is how do I store the closest one kn the nearest character variable when the vamp and camp are two different classes/object types
Nearest character isn't the same type so you'll need to either change the type to something that the vampire and camper both inherits or use the game object property from both vampire and camper - assuming they're mono behaviours.
I cant use the game object not can i inherent (im assuming you mean using Interfaces) because if I use interfaces i cant access the transform because transform is part of mono behaviours and an inferface cannot inherent from that OR if i use the game object then I cant access the methods and variables contained inside of Vampire/Camper. I've been at this for hours trying so many different ways to make this code work I even tried generics 😅
just make nearestCharacter of type object
nearestVamp.gameObject - this will make the types compatible
If both Vampire and Camper inherit Character, you can reference them both as type Character. If you're wanting to reference them as type Game Object, you'll want to acquire the Game Object component using the gameObject property of each - assuming they inherit mono behaviour.
Or yes you can create an interface, and make it force an implementation of public Transform transform { get; }
Once you make your Camper and the other one implement that interface, it will give off no errors, since MonoBehaviour exposes a transform property, the interface will be satisfied
So i put "public Transform transform {get; set;}" inside my ICharacter class?
Yes
Okay! I'll do this! Thank u!
Sweet let me try this quick
It must have the same signature as MonoBehaviour's transform though so the setter should not be there
Thank you so much there seems to be no errors
It's a neat feature of interfaces, you can use them as "adapters" by forcing them to implement properties/methods declared on the parent class of the class that will implement said interface
Having trouble with prefabs.
I have a base prefab and a prefab variant.
How do I move child game objects inside a variant?
It keeps showing a message: "Cannot restrucutre prefab Instance" and tells me to open prefab to edit, but it opens base prefab, not a variant which is completely useless in my case as my variant has different structure.
The reason I have base + variant is to have functionality of the base prefab(script attached)
So the way I can do this is to
- unpack completely
- arrange my objects
- reconnect the prefab
- delete old objects from the variant
- override the variant.
Is there a way to check what Class a certain object is so that lets say I just want to find the nearest Camper i can do so as oppose to both Campers and Vampires
is operator
Sure, you use the is operator: if (thing is Camper c) - then you can use c, which is the variable thing casted to Camper for you
If you don't need to access it further, you can omit that variable declaration
Yes that works
Can i say If ICharacters is ICharacters thus using that way to include all classes?
Made a woopsie with that first argument , i removed it
Yes you can put virtually any type on the right of is and it will type-check that
Also that's a very weird way of looping through a collection, you can just use foreach instead of getting the enumerator and advancing through it manually
Oh I was just following a solution a found online lol
Im still new to c# and unity I dont even know what getEnumerator means lol
It's actually what a foreach compiles to, so unless your tutorial guy works off decompiled code, it's not needed here lol
Im assuming u mean replace the while with a foreach(INearestCharacter character in INearestCharacter.CharacterPool) so the getEnumerator is removed?
Yep absolutely
Thanks!
So i want to add an IPerformance interface so everything i add it to gets timers that go off telling that object to do its performance heavy tasks like finding the nearest object to it
But when i say private or public static bool performanceActionAllowed and i add that interface to my player object
It doesnt recognise the variable in the player object
In the interface you don't specify access modifiers public, private
Else it becomes a property of the interface itself
You'll notice you're doing it right when you'll start implementing the interface, and the compiler will yell at you because you did not implement all the required properties/methods
It still says it doesnt exist in current context
Show your interface declaration, and the class that implements it. If they're long (> 20 lines), use a paste website
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To 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.
Yes it's better than screenshots
But the issue is those are static, they should not be. Interfaces cannot force a class to implement static members in the C# version Unity is using
Try something like this
interface ISample {
int SomeValue { get; set; }
}
class Sample : ISample {
public int SomeValue { get; set; } // if you remove this line, the compiler will be angry because the interface is not fully implemented
}
Interfave properties cannot have initializers
And im guessing there is no way around this
In the class. Default for bool is false so you technically don't need to initialize it if you're going to initialize to that
Oh ok
Sweet but i do need the interval time tho
I was hoping to do as much as this in the interface
So i can just throw on the interface
And wont have to remember to initialize the variables in each implimentation
Nope, interfaces are just here to enforce one rule: "this should be implemented", you still need to do the initialization job yourself
Ok I know what I think im gonna do
I think im gonna use my own personal class of shortcut methods to just add an Initialize method to each start method of each game
I've attempted to do what was said here. (Not sure if it's right?)
But here's what it looks like and my script.
But my character doesn't seem to get parented when I touch it?
first Debug.Log your collisions
and what it is your hitting and whatnot
if its not debugging then the code isn't running
Yeah it's not debugging. Just not sure why
where did you put the log
inside or outside if statement
I did both
alr so collision isn't happening
follow this
https://unity.huh.how/physics-messages
Hi team. The more I read about multithreading using awaitable/tasks/threads/async I get more confused. I want to run a function that uses some unity APIs in the background asynchronously. Don't care when it finishes. Coroutines aren't ideal. Threads and tasks don't allow unity APIs calls. Is async what I need? It runs on the main or separate thread? Any help here would be great!
Ideally on a separate thread but sounds like it's not possible calling unity APIs.
async and task are running on main thread or take a look at job system
Got it
or unitask
Thank you! Same with awaitable/ await I assume
Unitask. I'll check it out
Thank you!!!
Sorry follow up. Jobs is only blittable data types right. So I can't really call unity APIs from them right
Hmm I still cannot be sure why there's no collisions happening. It was working before I tried to adjust the hierarchy, but I would have thought these things should still function
I have a question! I am trying to make a drive horror game and am having a problem with the first person camera. I have clamped the X axis so they can't do a front flip with the camera, but I can't figure out how to clamp the Y axis. Any suggestions?
did you follow all the steps?
if so . screenshot both objects + inspector
Hello, how can I ease the Vector3.MoveTowards method so it doesn't look linear as much?
[CustomEditor(typeof(Health))]
public class HealthEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
var script = (Health)target;
script.isPlayer = EditorGUILayout.Toggle("Is Player", script.isPlayer);
if (script.isPlayer == true)
{
script.EasterEggSound = EditorGUILayout.ObjectField("EasterEgg Sound", script.EasterEggSound, typeof(AudioSource), true) as AudioSource;
script.textValue = EditorGUILayout.ObjectField("Text Value", script.textValue, typeof(TextMeshProUGUI), true) as TextMeshProUGUI;
}
}
}
Hi. I made this custom editor. Does someone know how to hide another booleans? Lets say that I have another bool like isntPlayer And if isPlayer is true then I want to hide bool isntPlayer because I dont need it in inspector How could I do this if its even possible?
A) Don't cross post
B) #↕️┃editor-extensions
Found it! Apparentally there is nothing such as "easing Vector3.MoveTowards"
I just used Vector3.SmoothDamp instead
Hey, is there a way to change transform.position.x and transform.position.y from a script?
thank you
On Line 45, you are setting the Euler to (0, Input.GetAxis("Mouse X"), 0);
You probably meant to put rotationY, the value you're clamping.
I just figured that out! Thank you tho 🙂
what did you change before it stopped working?
Im so confused I used animtor.SetBool("ActionScare", true) to perform a transition to bigfoot_scare and it transitions but it gets stuck? The animation doesnt play its stuck on the first frame.
hello, I need help with accessing a variable from another class in the same script
here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Console;
public class PlayerController : MonoBehaviour
{
public float speed; // I need this value in the SetSpeedCommand Class that's inside CustomCommands Class
class CustomCommands
{
[ConsoleCommand("game.player.speed", "player speed change")]
class SetSpeedCommand : Command
{
[CommandParameter("value")]
public float value;
public override ConsoleOutput Logic()
{
var result = value; // I need the value to be the speed variable in PlayerController Class
return new ConsoleOutput("speed set to " + value.ToString(), ConsoleOutput.OutputType.User);
}
}
}
}
What issue are you having?
read the comments
if its on Any state its probably transitioning onto itself (there is an option to disable this)
Well it works the same as any other two classes. You get a reference to the instance and access it from the reference
The fact that it's defined inside another class isn't really meaningful
It's just an organizational detail
i don't understand
Do you know what the option name is?
Click on the transition (the line/arrow) uncheck Can Transition To Self iirc
Like this?
Ah thank you so much.
You'd have to actually assign the instance variable somewhere.
Doing instance = instance is meaningless and just assigning it to itself
guys i'm having trouble with the new input system and the ScreenPointToRay function of the camera class
i know ( no idea why i did it )
private void OnAimingTarget(InputValue value)
{
Vector2 rawInput = value.Get<Vector2>();
Ray ray = _mainCam.ScreenPointToRay(rawInput);
_plane.Raycast(ray, out float enter);
Vector3 target = ray.GetPoint(enter);
Vector3 aimingDirection = target - transform.position;
aimingDirection.y = 0;
AimingDirection = aimingDirection;
}
where
Anywhere you want
AimingDirection has some weird value after this method is called
Pass it in as a parameter if you want.
Use a constructor.
Just set it directly.
Whatever
A Constructor is probably the best way
i guess the new input system Position [Mouse] inside the input actions uses some different values from the one used by the camera system
i'm just figuring out what constructors are
where you getting your value from ?
I just do
Mouse.current.position.ReadValue()
NullReferenceException because you don't assign to commands
isn't it a bit cheaty? because i'm trying to make it work both with gamepad and with keyboard so i don't want to be so dependent on mouse.current
yeah
got that
how do i fix it?
yeah it probably is, I only used it for that use case. Sorry I don't know as much about the other options, maybe can try asking in #🖱️┃input-system
I gotta brush up on my new input system skills 😅
oh i didn't notice that chat, thank you :)
it seems like you don't understand how to reference another object. i'd recommend going through some basic c# courses. and also checking this out for referencing unity objects: https://unity.huh.how/references
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To 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.
if you do this you cannot have more than one player
you cannot have editor code inside of a build. either put it into its own file inside a folder titled Editor or wrap it in conditional compile directives
Fine for my needs
thanks
I dont get it. Its health script so I cant put it into editor folder because build have to have this script
And how to wrap it in conditional compile directives
the custom editor class at the bottom of the file should not be included in your build
So what should I do to still use editor in scripts?
The convention in C# is one type per file, so I'd advise moving the editor class to its own file, and placing the file in an Editor folder
Thank you guys its working
Don't really understand everything here but if you are asking how to use the same class in the editor and the player take a look at #if UNITY_EDITOR #endif
hi, I have a question: is it possible to have different time scales for different scenes? (specifically scenes loaded as additive)
Because, I am making a first person shooter, and want the pause menu to be another FPS where you can shoot the different buttons. My main idea on how to achieve this would be to have a separate "PauseScene" with the settings minigame in it, have the main camera from that render to texture on the main canvas, then load the scene additively so that the render texture actually works. However I am using Time.timeScale to pause my game, and I would like to know if it's possible to set the "PauseScene" 's timeScale to 1f whilst keeping the main scene's timeScale to 0f.
sorry if this is a lot 😅
I have looked everywhere online for a fix but nothing i tried worked.
You can implement your own time scale pretty easily
E.g.
float myDeltaTime => Time.unscaledDeltaTime * customTimeScale;
In this way you can easily have different timescales for different scenes, you just have to request the correct custom deltaTime for whatever scene you are in
and I assume i'd have to go back into my movement script and such to change all the time delta times into the custom timescale?
or whatever, sorry i'm incredibly tired and can't string a proper sentence together
but thank you this is great
`where would i put this? in the player movement script or in whatever script is loading the scenes?
Yea
Probably some kind of TimeManager or SceneManager script
Excuse me, I've been having some pretty significant problems with a decision tree I'm making, and I'm having difficulty fixing it.
The relevant code section's pretty long, and the person who initially taught me how to make decision trees isnt present to help me fix things.
If someone's willing to assist me, I'll post the code-share and explain in further detail
can you change of the positions of corners of a closed or opened sprite shape in 2d
can't you just move them? what's blocking you?
in code i am trying to make random terrian
i have no clue how to implement it, i've just spent the past hour trying to figure it out but got nowhere. is there any chance you could guide me?
oh
do you know how
no not off the top of my head
i'm looking it up right now
https://forum.unity.com/threads/how-to-move-an-object-along-a-spline-spriteshape.837739/ this thread might prove helpful
What is the best way to reference a field from a another text field?
In the example from the screenshot I want to get value of a _sizeScale from a field to render it for a popup which gets text from this Description field.
Best way is to simply grab the reference from the script itself
Different fields might be there. Some go has sizeScale, some damageScale, some bonusCrit or something. Basically I need a convenient way to reference these fields in description
i am trying to switch to my jumping animation, platform has hills so i cant just do if (rb.velocity.y>0.1f) because the rigid body is getting velocity from going up the hill what should i do?
This all seems to be done in a single script so you should already have everything available to work with, so you'll be needing to parse the new text boxes you create and append them to the description box.
i think you would have to use reflection if you want to grab a field based on a string
Yeah, trying to figure out the right way to do it
I doubt you'd need to use reflection. If you're having trouble using a backing field then break it up and have the getter and setter exposed.
anyway, probably best to show code if you need help
I have monobeh modifierEntity which contains array of clases (modifierAtoms). modifierAtom can have any fields with any names, modifierEntity don't know which field are there
maybe im misunderstanding the problem, seems like they want to be able to type the variable name in their description and then get the value. If its all strings and unknown variables then wouldnt reflection be the only option?
it is triggering my jump while walking up a hill, how would i stop this?
just swap to the state based on input, it doesnt make a lot of sense to do it based on velocity
the problem with that is it would only apply to the first fram and not the rest i believe
up here?
If it's an inner class, then you send in the parent reference then if that's the problem and do a callback or through events
so anytime you create a new modifieratom you'd callback the outerclass
if it's only an editor script though, you can probably get away with onvalidate or OnSerialize callbacks
So I can get it like that
ModifierAtoms[0].GetType().GetField("_speedScale").GetValue(ModifierAtoms[0])
But the field should be only public for that, right?
well its more an issue with how you are changing states. You should check if they are even grounded before it can be declared that its running or idle
i was going to do that after
are you just constructing a string based on the modifier atoms, or is this some custom description you want? It might be easier to just loop through the Modifier atoms and have each one return some string
like i was going to check if it was grounded
I need to construct description using values from fields of modifier atoms. Different modifier atoms have different fields, and one modifier atom can have several fields I want to access.
So I want to be able to get something like "+Hitbox Size {_sizeScale} -Attack Speed {_speedScale}" to loop through modifier atoms and find these variables to render actual values in popup.
this
ModifierAtoms[i].GetType().GetField("_speedScale").GetValue(ModifierAtoms[i])
kinds works, I can check if .GetField("something") is null, and if it's not, return its value. But I'm not sure if this is the best way, and would be better if these fields can remain private (not sure that this is possible in the reflection scenario)
yea i think you can get private values, but i wouldnt really do this. I think itd just make more sense to construct the string by looping through the modifier atoms and have them all decide what string to return. Its kinda difficult to suggest more without seeing the code
So would be better to check just name of a modifier atom and call a function from it to return its special value?
Not sure how to handle the case with several fields I want to access in the one modifier atom in this scenario
honestly im unsure what to suggest since i dont know what the class looks like at all
How do I get a player to move along with a moving object? I feel like it should by default, given that it's a physics driver controller
ModifierAtom example:
[Serializable]
public class AttackSpeed : BaseModifierAtom
{
[SerializeField] [RangeValue(0.001f)]
float _speedScale = 1;
...
}
ModifierEntity:
public class ModifierEntity : MonoBehaviour, IInventoryItemInfo
{
[SerializeReference] [SelectImplementation(typeof(BaseModifierAtom))]
public List<BaseModifierAtom> ModifierAtoms = new();
...
}
Tooltip:
[RequireComponent(typeof(ModifierEntity))]
public class ModifierTooltip : MonoBehaviour, ITooltip
{
public string GetText()
{
var modifier = GetComponent<ModifierEntity>();
var builder = new StringBuilder();
builder
.Append($"<size=12>{modifier.Name}</size>")
.AppendLine()
.Append($"<size=9>{modifier.Description}</size>");
// here I want to parse modifier.ModifierAtoms for the field values
return builder.ToString();
}
}
yea it should be fine then for BaseModifierAtom to return the value, and ModifierEntity can loop through the list getting them all
So I need to specify atom name in the description, then call a function that will return atom value?
im confused what this is for now, are you manually writing a description or do you want it to be automatically made from the list of ModifierAtoms?
Because my thought was just loop through the ModifierAtoms and have some function like GetDescription(), then keep appending that
I want to manually write some parts like "this periodically damages you by" and get from modifier another part like " this damage is equal {_burnDamage}" where _burnDamage is a variable inside on of the modifier atoms
So the idea was to parse some parts, like the one with brackets, and get field values somehow
There is one description field for the modifier. And each modifier can contain many modifier atoms.
You could still just have that exist as a string associated with the modifier atoms, i dont see why this needs to be declared on the ModifierEntity and then attempt to look it up on the atoms with unknown variables
ModifierEntity contains array of the atoms, and info about modifier (description, sprite, etc)
Debug.Log($"Player: {player.name} attempting to interact with wall buy");
foreach (Component c in player.GetComponents<Component>()) {
Debug.Log($"Component on player: {c.GetType().Name}");
}
if (TryGetComponent<PlayerManager>(out var manager)) {
manager.DoWhatIWant();
} else Debug.Log("Cant get manager component");
This logs Component on player: PlayerManager UnityEngine.Debug:Log (object) Showing that it definitely has the component and I verify that in the inspector at runtime but it still returns false and says it cant get the component.
PlayerManager manager = player.GetComponent<PlayerManager>();
if (manager != null) {
manager.DoWhatIWant();
} else {
Debug.Log("Can't get manager component");
} ```
This works fine and grabs the component with no issue tho. Anyone have an idea why?
i am trying to make a random terraian gen in 2d with a sprite shape but in the for loop it gets stuck, can someone help me
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
public class Changeing : MonoBehaviour
{
public SpriteShapeController sprite;
private Transform lastSpline;
private Spline spline;
void Start() {
spline = sprite.spline;
for (int i = 0; i < 3; i++) {
spline.SetPosition(i, new Vector3(Random.Range(-2,2),Random.Range(-2,2),0));
lastSpline.position = new Vector3(0,0,0); //right here it gets stuck
}
}
}
if (TryGetComponent you arent calling this on the player
what do you mean it gets stuck?
like it would make the first spline at a random point and then it doesnt do anymore and i get this error NullReferenceException: Object reference not set to an instance of an object
Changeing.Start () (at Assets/Changeing.cs:17)
Where are you changing lastSpline? Looks like you are setting it to 0,0,0 but never changing it anywhere else
You never initially set lastSpline to anything just the position
the Transform is likely null unless you set it to something somewhere else
so i have to set it to like 0,0,0 at the start
lastSpline is a transform, it needs to be set to a transform first
this looks like all the code, so yea spline/lastSpline is always null. you have an error (and likely error pause on) so your code isnt gonna run anymore
its null, you cant set the position on a null transform
ohhhh
once its not null then you can edit the position
Unless you need scale and rotation
i do not
If you just need position and thats it then I would make it a vector 3
well its not just about scale and rotation. you use transform if you want this to be an actual object in your game
That too
Seems like he is just using it to store positions not be a game object
its werid
Anyone ever used git lfs?
Having a problem... i migrated all large files to lfs. FBX, Materials and stuff.
When i run git lfs fetch it tells me theres about 700 files fetched. Running lfs checkout replaces 4 only.
The other hundreds of files are just not there... only the pointers and it does not checkout them. Any ideas?
@lofty crest Don't crosspost
sorry
Not finding a DevOps channel on this server so I'll post here. What's up with Plastic and identical files seen as changes?
#💻┃unity-talk is the best place for that
But I dunno, that is odd
Answer here.
distanceFromTarget = Vector2.Distance(transform.position, target.position);
if (distanceFromTarget <= distance) {
StartFollowing();
}
else {
StopFollowing();
}
}``` I want to have this object stop a bit after the Player leaves the Distance so that it has a chance to get back into the Distance and keep following.
You can add a cooldown timer that starts ticking down to 0 when out of the distance. Once it reaches <=0, then you StopFollowing()
An example would be greatly appreciated 🙂
Hey guys! im trying to use a script posted on the unity forums to help me create lod groups and set the renderers. it working as intended up to the point of setting each lod mesh to the coresponding lod renderer. It'll create a parent and lod group on the parent, and set the three Lod levels as children. the forum post decribes the same error im getting on use aswell. Someone replied to the forum post with a fix but i cannot figure out how to impliment it. Any help would be apprishiated, i can provide any additional info needed also.
https://discussions.unity.com/t/editing-a-lodgroup-from-script/153487
Hello Unity Answers! My current script is raising this exception whenever I try to set LOD levels: “SetLODs: Attempting to set LOD where the screen relative size is greater then or equal to a higher detail LOD level.” Before I post the actual script, what is supposed to happen, and what is actually happening? The script is supposed to create ...
here is the script I slapped in unity; My understanding of cs scripting is a 1/10. i simply added this from the forum post and made it run on a menu button.
https://pastebin.com/RVLY24rj
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
i get the same error as forum op. “SetLODs: Attempting to set LOD where the screen relative size is greater then or equal to a higher detail LOD level.”
Hi everyone, I am working on a cross platform compatible application. Currently I am facing an issue with build size optimisation. The packages that are unused are also getting included in the build. I tried making a blank scene build and removed packages one by one which helped me reducing the build size from 77 MB to 28 MB. Can anyone help me with any solution to automate the exclusion of the unused packages?
Hi all
Context (this will be ongoing): I'm making a 3D autotiling, sparse graph editor similar to the asset Wildtile
Just saw a random phrase in SO
it is mutable, breaking the rule that structs should be immutable
And i've been doing
Block b = GetBlock(pos)
// Change some value
SetBlock(b)
Which is how i've been doing as well with Mirror. Whether i'll network these Block collection or not (or sync it another way and somehow making it deterministic per machine)
But specifically for the blocks editor itself, if I'm gonna use Block as part of some calculation for the autotiling, should they be class? Or generally for big graphs like this, it should always be struct?
Is the "structs should be immutable" a real thing, especially in graph nodes?
Is this "if" statement obsolete? Simply: Is it bad code and what can I do to fix it? cs if (movementScript.canFollow && !stats.isDead) { ChangeAnimationState(Run_Skeleton); } else if (!stats.isDead){ ChangeAnimationState(Idle_Skeleton); }
What do you mean obsolete? Or bad code?
Like, is there an issue you are having?
Is it safe to be using the stats/movementScript in the same script. These two are other scripts.
Of course
Is there a way to make that if statement one variable? The (movementScript.canFollow && !stats.isDead) not the if statement*
I mean, I guess. I don't think it makes sense to, but you could make a property in the class that simply returns a bool that checks those two variables
Nevermind that then. Thank you for the help!
I'd rewrite it to this for clarity's sake:
if (stats.isDead) return;
ChangeAnimationState(movementScript.canFollow ? Run_Skeleton : Idle_Skeleton;
What does that code mean? I've never dealt with ? and : 😵💫
It's a ternary operator.
It is a condensed if statement essentially
The code before the ? Is the condition. After and before the : is when it's true. After the : is when it's false
Okay, thanks for the clarification.
Well wait. I'd have to test that. It has a syntax error (missing a parentheses), and I thought ternary's only worked as an assignment. But maybe the method call works?
Actually, there is quite a bit wrong with that
But I like the direction, it just needs to be fixed
I can't use that code. Its too advanced compared to what I am using currently. I will just be confused with it when reading my code. I will keep it in mind though as I want to start using those soon.
It's not even right anyways. I'll post corrected code and I think it will look more clear I think
Okay
ChangeAnimationState is your own method, right? What parameter Type does it take?
// Stop the same animation from interrupting itself
if (currentState == newState) return;
// Play the Animation
animator.Play(newState);
// Reassign the current state
currentState = newState;
}```
Ok, I thought it was a string, just making sure
if (stats.isDead) return;
string newState = movementScript.canFollow ? "Run_Skeleton" : "Idle_Skeleton";
ChangeAnimationState(newState);
THAT is valid.
You are assigning newState to either Run_Skeleton or IdleSkeleton based on canFollow being true or false
Then pass that to the method
I really like doing early returns too. If isDead is true, just end the method right there
@spring creek While you are still here, I just created this little branch. It is taking up too much space, how can I shorten the length of this code? cs if (movementScript.canFollow && !stats.isDead) { if (movementScript.agent.velocity == Vector3.zero) { ChangeAnimationState(Attack_Skeleton); } else { ChangeAnimationState(Run_Skeleton); } } else if (!stats.isDead) { ChangeAnimationState(Idle_Skeleton); } By taking too much space, I mean the names are too long.
I made Idle and Run string btw. Don't know if they were variables already. I assume they are though, so you can change that back
They are
I would again do if isDead return there so you only check that once at the top
The inner part COULD be a ternary, but it's fine as is (the attack vs run part)
Idle could just be an else after it all
I have a question about stating variables in a function. If I made movementScript.canFollow into a new bool, would it work the same in the "if" statement?
I don't think any of the names are too long though, nor should you ever really worry about that
Like if you did:
bool canFollow = movementScript.canMove;
?
That would set the VALUE right at the time of assignment
It would not change when movementScript.canMove changes
Even if this function is in the Update Method?
it would update when that assignment runs next time
It would update each frame, but not directly because of the other script changing. Rather, it's because every frame you would be creating a brand new bool canMove and assigning it to that current movementScript.canFollow value
I'm not really sure if there is a point to that
I just tried it. It seems to function fine
I just want to shorten the "if ()"
You can make cool bools like this though
bool attackPossible = movementScript.canMove && movementScript.agent.velicity == Vector3.zero
It is just a preference I have. So whenever I can, I want to shorten them
I would make that one of the absolute lowest priorities.
You are literally making the code less performant in order to look prettier.
You are reserving another piece of memory just to shorten it
But it's a negligable difference in performance, so your choice
Is it going to take more FPS? What performance do you speak of?
As I said, memory
ignore that, always go for readability. There's a decent chance the compiler will optimize out temp variables anyway
Readability yes
Brevity for the sake of it is completely different than that though
Often it means LESS readability
But as I said, it is a negligable difference and to go with their preference
Do you think its enough to really impact the game? Of course I want good performance, but if its only impacting a little bit, then why not?
I didn't say go code golfing, just readability. Performance is not something that should be considered at all
No of course not
Negligable means you can ignore it
It will have a negligable difference
I just think getting your game WORKING and built is WAAAAAAY higher priority
So come back to that at the end
I agree with x that performance is not something that should be considered at all at this stage (however much they misread what I was saying)
If I don't do this now, I will have trouble trying to do it later.
Your choice for sure.
I recommend making it more useful like this though
#archived-code-general message
You can pretty much ignore performance unless you start doing something by the 1000s
When possible of course
how so? you use the profiler to find the hotspots. Much better to have readable beautiful code and then find the hotspots, than to start out with ugly performance code that might not have made a real difference except make everything harder to maintain while you're working on it
I don't understand 😵💫
They mean don't worry about performance at this stage at all. That's what all three people here are saying. They misunderstood what you meant in what you were saying though
What I meant was this: If I don't start applying clean code right now, I likely won't do it later. Basically I will be lazy later after looking at all the code, and give up before doing it. That's all
What are you guys referring to when you say "Stage"?
You are not done with the game, right?
The state of creating the game
Deal with that stuff when polishing it at the end
OH, That makes sense.
Well I have a whole plan set up for this game. I just finished what I needed today, so I am cleaning it up. Thats what I wanted to start doing after my last game was so messy and I gave up even trying to make it clean.
Definitely a worthy goal. And sorry if I was confusing about it.
I just see so many people get stuck in trying to make it perfectly performant and readable that they don't actually DO anything
But as x said, readability first. I would say second to output though. And performance third
I completely agree with "I just see so many people get stuck in trying to make it perfectly performant and readable that they don't actually DO anything". I just learned from my mistake and improving.
Well I'm leaving, thanks for all the help!
Is there a plugin or script I can use to expose all the values of every network variable that I’ve set?
I’m a visual person and I’d like to actually SEE the values in editor
#archived-networking or the discord pinned in there
I have a transform point with some position offset.
It is child of potential hierarchy (up until specific game object with a tag).
I need to cache some value, which I can use to always get my exact point position, from root of hierarchy (that specific game object with a tag).
This doesn't exist on game object level, so I can't just get transform.position
it is also 100% that hierarchy never changes
only position/rotation of root itself
child.position - root.position should give you child.localPosition relative to root
that doesn't take rotation/scale into account and it's also taking into account current root's offset
root.transform.InverseTransformPoint(targetPosition.transform.position)
that did the trick
We can use public GameObject target; to set an enemytarget via the inspector but is there a way I can refer to the GameObject of the object running the script , the keyword "this" seems to not work as it refers to the class itself.
gameObject ?
Sorry my bad
hello, i have shader problem. i used blurShader in built-in for old project. now, i developing URP and this shader not working. how i can do this problem? this is my blur shader for built-in:
use an array and then use the enum as an index into the array
thanks :O
dictionary my goto, but what you have is fine honestly unless you're planning on populating it a bunch more.
fixed array, the number of enum is pre defined so fixed size array can be used
fixed size array is good. you might even make a simple wrapper function to make it look less jank
SetStat(CharacterStat s, float val) => myArray[(int)s] = val;
GetStat(CharacterStat s) => myArray[(int)s];
i have this really weird bug where i try to teleport the player to a certain spot (by transform.position += offset) in one script, and in a different (mouse look) script i rotate the player around. Now the issue is the player returns to his old position as long as "transform.rotation = Quaternion.Euler(0, yRotation, 0)" is in the mouseLook script.
does player have a rigidbody?
yeah
that's why
transform and rigidbody write to each other, and you need to be very careful about this
like, if you have Rigidbody.AddForce, and then the rigidbody moves from A to B, you expect the transform not to lag behind at A. Physics system overwrites
point being, if it is a physics-affected object, you need to consider both RB and transform when you move it
if you require a teleport, then you probably want to set rigidbody.position
which (I think) automatically writes to transform as well
would it also teleport on the next available fixed update or is it instantanious?
ok well i think that fixed it thank you're a lifesaver
anytime. it's super confusing until someone explains it to you
i take it i should do rb.rotation instead of transform.rotation too?
maybe a bit more explanation is in order
your gameobject has a transform, colliders, and rigidbody. transform and rigidbody each write to each other during physics step. Moving transform does NOT update collider positions, but moving rigidbody position DOES.
this includes position and rotation
also, be advised that when you move rigidbody.position, you are just setting position or rotation. Teleporting. you are not respecting physics.
So you can teleport into a block, and nothing will stop you.
same with .rotation
if you have a kinematic rigidbody, then you might want to use .MovePosition(), which DOES respect collisions, but does not move instantly. rigidbody.MovePosition(pointB) effectively queues up your rigidbody to plan to move to point B during next physics step. So when everything simulates, everything in the world will respect the movement of the rigidbody from point A to B
.MovePosition (or .MoveRotation) will smoothly write to the transform on every Update() cycle in between FixedUpdate to make it move as expected.
does this help?