#💻┃code-beginner
1 messages · Page 107 of 1
📃 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.
I think whatever version of Unity you're using doesn't support switch expressions
but the code for this asset is using it
Fix your IDE
i'm using unity 2019.4.11f1
exactly
Unity 2019 doesn't support C# switch expressions
it's too old
Your options are:
- upgrade Unity
- rewrite that code
- don't use that asset
got it, thank you
note you really shouldn't go around sharing code for paid assets
will there be a change if I used Visual Studio Code instead of Visual Studio in terms of speed? because my pc is barely holding on with Unity alone...
Hello. why am i getting this error.
i started working with Networking rn, and i dont know, do i need to use NetworkRigidbody instead of normal one?
ok ill use it cuz some components are asking for it
State.Fried is an enum, why are you qualifying it with an instance reference?
I think you meant StoveCounter.State not stoveCounter.State.
StoveCounter is the class
stoveCounter is a reference to an instance of the class
u are right. lmao, thanks
The numbers get turned around, (42 becomes 24) is there a way to fix it
what? Show what you mean?
Are you certain it's 24 or 42?
Log the value of integer to display
somehow i encountered a strange thing
such as?
theres a card object in my game scene , this card object will have its material loaded when we enter the scene, it has no valid material until then
i have a script, that will modify a parameter of the material
however, it seems that even it successfully modified the param, the card cannot reflect the changes
i need to get into the inspector and manually modify the value in order to get it works
The inspector for what?
Are you modifying emission by any chance
You know that Renderer.material creates an in memory copy of the material. It won't modify the original.
i know, but it will modify that object with the renderer mat right
Show some code
yes
You reassign the shader??
and the code successfully changed the parameter of that material
That's not a check, that's an assignment
Right so that will always be false yes?
public GenericDictionary<int, UnityEvent> diamondHPThresholdIncome;
private HashSet<int> triggeredThresholds = new HashSet<int>();
public void CheckForDiamondIncome()
{
var currentHealthPercentage = enemyUnit.healthSystem.LifePercentage();
foreach (var threshold in diamondHPThresholdIncome.Keys)
{
if (currentHealthPercentage <= threshold && !triggeredThresholds.Contains(threshold))
{
diamondHPThresholdIncome[threshold]?.Invoke();
triggeredThresholds.Add(threshold);
}
}
}
What's the difference here if I'd use private List<int> triggeredThresholds instead of HashSet<int>? None?
the checking is correct
I don't even know what happens if you assign a null shader
It might be slower but with a small collection size you won't notice either way
instantiate a new one via Material mat = new Material(Shader.Find("someShaderType"));
then just copy the properties via mat.CopyPropertiesFromMaterial(oldMat)
let me show u the complete flow of the card object
- game was initiated
- card object spawned
here the card object does not have a valid shader
- players get into the game scene
- based on the game scene , a URP or a standard shader will be loaded (changed)
BTW the thing that would be slower is the .Contains check. HashSet is generally much faster at that.
we change the shader
so If i just want to check if a collection contains element X (not plan to do anything with that element, just check if it's there) it is better (faster) to use HasSet?
why is that?
- this script should be executed after 4
Generally if you are doing contains checks a lot, yes HashSet will be faster. lists have to check the whole list to know if an element is contained. HashSets can do it very quickly based on a hash function or at worst a log(n) tree operation
Why do you get the shader in Start, which can occur after OnEnable?
yeah i just found out its not replacing material , but the shader instead
the difference is that HashSet will always be unique/ no duplicates
damn wait
that's good to know, thanks!
bruuuh its fixed!!!!
the weird thing is, even i put the urp ref on start, the parameter still changed
i swear i saw that
so i think , welp it should be fine? but then the changes didnt reflect
lol ty guys
Check with the debugger next time and you'll see what executes when and can be extra sure what you saw
ok ty
I have no idea how that could occur, but maybe enabling RTL on the text component can do that?
Thanks, it works now
public void NewGame()
{
this.gameData = new GameData();
}
public class GameData
{
public int time, day, week, money;
public float stamina;
public int LustLevel;
public int LustExperience;
public GameData()
{
this.time = 0;
this.day = 1;
this.week = 0;
this.money = 1000;
this.stamina = 100f;
this.LustLevel = 1;
this.LustExperience = 0;
}
}
I don't understand why is it not loading the new instance of GameData. It's returning day 0 instead of day 1. It's working before but now it's not...
then something is changing day to be 0, in visual studio you can right click -> find references, to see what is modifying it. Add debugs to see what its being set to during these areas
I checked it and none sets it to zero. but after checking a bit more. it seems like only the day variable does not change. If the day is 3 and I instance a new "gameData" it will still be 3 and not 1 for some reasons I don't understand...
how are you sure that currentDay isnt 0?
what is the difference between gameData and data ?
Vector3 Direction = (transform.position + Player.transform.position).normalized;
transform.position -= Direction * Time.deltaTime * MiniSpeed;
i was trying to make a projectile move towards the player but for some reason it just mirrors the players moves anyone got any ideas on why?
{
public int time, day, week, money;
public float stamina;
public int LustLevel;
public int LustExperience;
public GameData()
{
this.time = 0;
this.day = 1;
this.week = 0;
this.money = 1000;
this.stamina = 100f;
this.LustLevel = 1;
this.LustExperience = 0;
}
}```
```//DAY
private Text[] dateNDay;
private int currentDay;
//DATE
private string[] week = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
private int weekPos;
public int WeekPosition { get { return this.weekPos; } }
private bool napChoice = false;
public void LoadData(GameData data)
{
this.currentDay = data.day;
this.weekPos = data.week;
this.currentIndex = data.time;
}```
Direction is target minus origin. You have origin plus target
the screenshot above shows you have a line data.day = currentDay. Thats the line i was referring to
doesnt work just goes away from the player in the opposite direction and adding gives us the same issue as before
Well, it's definitely not gonna work as it is now
I think we went over it earlier today or yesterday...
mhm we did and that worked for smth else
Well, it's the same issue...
actually its not
if we use what we talked about earlier it will go directly away from the target which is what we needed
i swap the values and it just mirrors movements
now we just want it to go to the target
First let's clarify one thing: when we say target, we mean the position/direction that we want to move to. Not any specific target in your game.
yes
Yes. And so the direction of movement is always target position - origin position.
And you move the object by adding direction times speed to it
yes
This is common sense and anything else would make things more complicated
And that's not what you have currently
Hey, is there a thread or website with some basic "do"/"dont do" tips for beginners ?
Like how to use references, components, tricks,...
look in the pins on this channel
Im asking because sometimes I code something and I feel it might not be the "right way"
i tried every combonation i started with that it made sense so i did it and it just didnt work and now it is thank you im sorry im this thick skulled lol
Get it to the correct state then share your correct code and issue details again.
Another question to be sure, private vars are usually named with the _ prefix yes ?
Oh, is it fixed?
yep
That's for saving...
I debugged it to see what are the values of the day before and after the new game
{
Debug.Log(gameData.day);
this.gameData = new GameData();
Debug.Log(gameData.day);
SaveGame("save0");
}```
and it returned me
0
1
0
It did turn it back to 1 but for some reasons, when the saving happens, it returns back to 0 even tho it's already been set to 1
Debug it at saving and loading.
Before/after
it doesnt matter what you think it was for, if thats the only place you assign a value to .day, then that is the place where it is assigned 0
im not sure where that 3rd debug comes from, because theres only 2 shown here. But its still clear that its initialize to 1 correctly
Or it's not assigned at all and it's the default value.
based on this code, #💻┃code-beginner message, thats not possible
assuming they didnt cut out a default ctor
now this error showed up. an error that did not show earlier
Sounds like your code is erroring and not executing as expected.🤷♂️
It shows an error for Line 46 rooting from Line 26
gamedata is probably null before you load.
Where is that debug that prints 0 located btw?
the first error is before loading the first 0 is after loading
A method that errored would return immediately, so that's not possible.
You should show us the stack traces of the messages.
you should turn on error pause also, anything that prints after an error basically shouldnt be trusted
how do I do that?
that button should be toggled
then you should properly look at why the error happens through the stack trace, which you can see by clicking on the log. At the very bottom you should see more about it, like what even called the method that caused the error
idk whats wrong, but i cant move forward and jump.. everything in video
Cool feature
Without code, folks won't be able to help (video code isn't useful)
How 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.
ok lemme post
its not animation bug, i tried removing animator
Does jumping allow you to move forward?
any way to play animation just once via script?
no
animator.settriger()
Either way, your else immediately removes all velocity on the z
Comment out line 47
somewhat silly question, I have a poco class like this
public class TypeData
{
[HideInInspector] public string name;
[HideInInspector] public string typeString;
public List<string> assetList;
public TypeData(string newTypeString)
{
typeString = newTypeString;
assetList = new List<string>();
name = newTypeString;
}
}
and I have a list of them, How could I go about sorting that list based on their name?
usually i would just use Sort() but this doesn't implement that and It wouldn't know to reach for name
but List does implement that, this one doesn't need to
Mhm?
Why would this need to implement Sort? The list does the sorting, not this class
you could use https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderby?view=net-8.0
alternatively, implement IComparable on TypeData so the list knows how to compare and sort the type
oh that might work
usually linq scares be but finally doing editor stuff that can let me go nuts with that kind of stuff
why im much faster on build??? speed is same
Transform snowParticleClone = GameObject.Instantiate(snowmanParticle, transform.position, transform.rotation); Destroy(snowParticleClone.gameObject, 1f); why is this giving me Can't destroy Transform component of 'SnowmanEffect(Clone)'. If you want to destroy the game object, please call 'Destroy' on the game object instead. Destroying the transform component is not allowed.?? i literally use that same code for all of my particle and all of them works fine except for this one
nothing
Ah anyone here use Mirror for multiplayer? I'm facing a problem, the OnCollisionEnter method doesn't call on client but it work on host (to popup a canvas). Here my setup:
- Car (networkbehaivor, boxcolider, rigidbody networktransform, networkrigidbody).
- House (monobehavior, boxcolider)
- All client control 1 car, client has no authority, client call Command[bypass authority] method to tell host to move the car.
Whether it's the host or the client who is moving the car, the house only popup the canvas on host.
Maybe the destroy call is occurring from elsewhere
Fix errors from top to bottom, if possible. Else you may be evaluating false positives
I'm assuming you're destroying a reference to a Transform component somewhere.
i instantiate and destroy that particle during 3 scenarios. the first one is if the object/snowman lifetime hit zero i instantiate the particle then destroys the snowman, for this scenario the script is not attached to the snowman that is being destroyed. the second one is if the snowman hit a bullet before a certain time. the third one is if the snowman hit a bullet after a certain time. for the second and third scenarios the script is attached to the snowman that is being destroyed
this is the script that i use for the first scenario
if(other.CompareTag("PistolBullet") && timerSnow > parryTimer) { snowScript.isCooldown = false; snowScript.timerSnow = null; snowScript.snowmanLifetimeTimer = null; CameraEffects.ShakeOnce(); parryTxt.Play("parry", -1, 0f); Transform snowParticleClone = GameObject.Instantiate(snowmanParticle, transform.position, transform.rotation); Destroy(snowParticleClone.gameObject, 1f); Destroy(this.gameObject); this is the second
else if(other.CompareTag("PistolBullet") && timerSnow < parryTimer) { CameraEffects.ShakeOnce(); Transform snowParticleClone = GameObject.Instantiate(snowmanParticle, transform.position, transform.rotation); Destroy(snowParticleClone.gameObject, 1f); Destroy(this.gameObject); } this is the third
andd it is exactly what's been happening, i also instantiate the particle if the snowman spawns and forget to add the .gameObject when destroying it
i also happens to forget about that scenario
for hats,shoes.sunglasses,hoodies and stuff is that a character change script or a cosmitc script?
Whichever you want it to be.🤔
no eventmanager?
What do you expect it to be?
well, did you create a variable called EventManager?
whats the different between using
public UnityEvent onshoot;
and
public delegate void onshootdelegate();
public static event onshootdelegate onshoot;
Not much difference.
beside one is use in the editor and other in script
You can use both in script.
okie
what is the name of the method to trigger something when a key is down/up/hold ? instead of getting the key on update
UnityEvent is serializable while the others cant
what does that mean? the event tab appear on unity editor?
oh its storing instance of game object?
You need the new InputSystem for that
ok ty
whats wrong??
`public float GiftSpeed;
public Transform GiftObj;
Transform GiftObjClone;
public void Update()
{
if (Input.GetKeyDown(KeyCode.J))
{
GiftObjClone = GameObject.Instantiate(GiftObj, transform.position, transform.rotation);
Rigidbody rb = GiftObjClone.GetComponent<Rigidbody>();
//rb.velocity = transform.up * GiftSpeed * Time.deltaTime;
}
}`
It means you can assign it before you start the game, while regular events need to be assigned to after the game starts.
maybe you have that script twice in your scene?
could anyone explain why i'd be getting these errors? here's the code i just wrote https://codeshare.io/RbPKXW
its referencing my unit selections code for the instance but i just don't understand why its erroring
yeah your right lmao
i didnt realize i accidentally put that script in other object aswell
Either Instance or unitList is null in UnitSelections
best guess is that you didn't create the list
can i post my unit selections code? maybe you can spot something that i missed? its not totally done yet. i'm following a tutorial for this and hes not explaining any errors i could have
UnitSelections.Instance.unitList.Add(this.gameObject);
three possibilities, instance is null, unitList is null, or both of them indeed after you fix one
where you set the _instance?
yes that should be one of the first things set in the code.
Im sorry. This is all new to me. I didn't realize selecting multiple units would be so difficult 😫
So does that mean you figured out what's wrong?
I've looked it over again and again and I just cannot see what's wrong. I've even went back through the tutorial to see if I maybe typed in something wrong and I didn't see any errors.
The Awake method in UnitSelections is only halfway finished. Look that up in the tutorial.
Oh! I see now. I'll change that and see if it works
That absolutely worked. I must have been typing too fast and forgot my else statement. Im a dumbass 😫 thank you for the help!
ok so i know theres a better way to do this
so right now i have an enemy script, with my enemy script being divided into two parts
one controls the movement and manages health and collisions
the other controls the enemy's hands, which pivot towards the player
what i want to do is make it so that when the enemy dies, the hands stop moving and the enemy no longer flips to face the player
i set my health to public and my hand script to pull the health value, but it falls apart when i summon in multiple instances
once i kill all enemies, all hands on all enemies stop pivoting
show code
You'd need to share some code and start with solving one issue at a time.
ok i was thinking
if i use an if statement to check for the current tag that could work
how can I swap animator controller in the animator? i've created public AnimatorController enemyAnimator; then i just replace the animator.runtimeAnimatorController = enemyAnimator and it works perfectly fine, but I cannot make a build with it as this is a part of UnityEditor
What is part of unityeditor?
hey
i got a OnCollisionEnter function in a parent gameobject, it has a Rigidbody and a script only
i got a child with a meshcollider
when the meshcollider detects a collision, OnCollisionEnter is called in parent
my question is: can i get the "source" of the call of OnCollisionEnter from the parent ? I would like to know what child is the source
edit: or even can i pass some extra data to the parent ?
the AnimatorController
i meant the namespace
I think you gotta use the RuntimeAnimatorController type
Not sure, I have done that but dont remember how, can check in a moment probably
Yeah the editor version inherits from the runtime version
And unity is chill like that
Guys can I do animation on key press without animator controller?
Why don't you want to use an animator controller?
can i invoke an event with an argument that trigger two method one with and the other without using said argument?
How do you insert an element at runtime into the middle of a layout group? Say I have a vertical layout group, with buttons #1,3,4 already in it, and now the player just unlocked button #2 so I want to create it and add it to the UI. I only know the SetParent() way of adding to the group, which adds it to the bottom
I don't quite follow what you're asking, that seems contradictory. Maybe show some concrete examples of what you're trying to use?
Set the sibling index after you've spawned it in as a child:
https://docs.unity3d.com/2020.1/Documentation/ScriptReference/Transform.SetSiblingIndex.html
ahhh it was a property buried in the Transform, ty so much
Yeah there's no way to directly spawn it in at a specified index, it'll need to be a two-liner
It's complex...
Pls say can I do it or not sir
It is not complex. You just don't know how to use it yet. Making an animator play an animation when you push a button is very straightforward.
the legacy Animation component is very annoying to work with.
Why annoying sir?
It was made to reduce complexity of the legacy animation system
Just sir can u pls say how to do animation on key press with animation controller
You should learn it. You're going to need it
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Make an animation controller, add your animation as a state, transition to it when a parameter is set, change that parameter on key press
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
An Animator Controller is a Unity asset that controls the logic of an animated GameObject. Within the Animator Controller there are States and Sub-State Machines that are linked together via Transitions. States are the representation of animation clips in the Animator. Transitions direct the flow of an animation from one State to another. In thi...
https://docs.unity3d.com/Manual/AnimatorControllers.html talks about how to use animator controllers.
the Learn course will be even better for picking them up
@tender stag public links are editable. Just trolls.
oh alright
public class Walking : MonoBehaviour
{
Rigidbody rigidBody;
public float walkingSpeed = 5f;
void Start()
{
rigidBody = GetComponent<Rigidbody>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
Addwalk();
}
}
public void Addwalk()
{
rigidBody.AddForce(transform.forward * walkingSpeed * Time.deltaTime, ForceMode.Impulse);
Debug.Log("Got to here");
}
Shoulden't my character move forward?
I am making a 2d endless runner game with randomly spawned platforms, and items for the player to college.
I have a script attached to a game object called generate platforms, which is randomly generating platforms at 3 different layers. I have another script called generate coins, but i want the coins only to be generated ontop of platforms. How would i do this?
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref
It's a way to pass a value type by reference
smoothdamp needs a ref float to remember its "velocity" between frames
The float should be in your class, not local
right
i just decided against using it in the end cus its too complicated for what i want
i wanted to use lerp but apparently thats not a good idea
Not really complex, did you look at the doc..?
https://docs.unity3d.com/ScriptReference/Mathf.SmoothDamp.html
yeah but i think its just a bit too much to change a value from 1 to 0 and so on
Simpler example than the one in the docs:cs float smoothTime = 0.3f; float velFloat = 0.0f; float smoothedFloat; void Update() { float targetFloat = // Enter target value here smoothedFloat = Mathf.SmoothDamp(smoothedFloat, targetFloat, ref velFloat, smoothTime); }
Then you will either use Mathf.MoveTowards which is linear (not smooth at all)
or Mathf.Lerp which is not consistent with framerate unless done correctly, more info about lerp as a smoothing function here: https://unity.huh.how/lerp/wrong-lerp
I heard that mmorpg server games need to handle each client as a separate thread to avoid waiting for the client to complete the job.?
Can someone help me understand why my character doesn't move?
GetKeyDown triggers only once per key press
I change it to getKey but my character doesn't move a inch
Also, continuous forces should be added in FixedUpdate not Update
And don't multiply the force with deltaTime - it already does that
Where did you read that? Doesn't make much sense to me why you would do that.
And FixedUpdate?
Aand check the value of walkingSpeed in the inspector
walkingSpeed is 5
Also, ForceMode.Force or ForceMode.Acceleration for continuous forces
I'm learning about mmorpg server processing, multithread or singlethread
Impulse/VelocityChange is for one-shot forces (jump, dash etc)
Oh yeah
Why would you have a server single threaded? 
Yep I also don't know about mmorpg server, I'm looking for documentation about it
Well good luck then, it's an insanely huge topic that you can spend months on. 
How should I add friction to the movement so I can better control how my player moves?
I don't think friction is the right word but do you need like snappier movement?
If so, see my answer(s) here from yesterday:
#💻┃code-beginner message
Hey guys, Sometimes during my game, something wierd happen and I am not sure why. I have 2 code. One to keydown SPACE and other F1 but sometimes during the game when i use SPACE it does what is inside the F1 code.. and I cant understand why.. here are both: ```cs
if (Input.GetKeyDown(KeyCode.Space) && _canShield){
if (!_hasShield && !_uiManager.isCooldown){
StartCoroutine(ShieldOnTimer(3, _shieldCD));
_uiManager.StartCooldown();
}
} ``` and the other: ```cs
if (Input.GetKeyDown(KeyCode.F1) && _isF1 == false){
ToggleF1();
_f1.SetActive(true);
} else if (Input.GetKeyDown(KeyCode.F1) && _isF1 == true){
ToggleF1();
_f1.SetActive(false);
} ```
why in the world would the game do what is inside the F1 keycode if I use space?
Well my movement is very slidey
Yeah, in other words not snappy
The solution I linked solves that while still using forces instead of directly changing rb.velocity
Got it thank you
how can i add an offset to this
spawnTransform.position + offset
You can't "offset" a transform. You can offset a vector though with addition
Yeah note it's the position you likely want to offset. The Transform represents position, rotation, scale, and hierarchy relationships.
you can also use spawnTransform.TransformPoint(offset) if you want it to be relative to the object's rotation and scale
So I did something wrong. My character is now flying to the right up in the air
Show your code
public class Walking : MonoBehaviour
{
Rigidbody rigidBody;
Camera playerCamera;
public Vector3 moveDirection;
public Vector3 desiredVelocity = new Vector3(1f, 0f, 1f);
public float walkingSpeed = 5f;
// Start is called before the first frame update
void Start()
{
rigidBody = GetComponent<Rigidbody>();
moveDirection = Vector3.zero;
playerCamera = Camera.main;
}
// Update is called once per frame
void Update()
{
Addwalk();
}
void Addwalk()
{
Vector3 difference = desiredVelocity - rigidBody.velocity;
Vector3 cameraForward = playerCamera.transform.forward;
cameraForward.y = 0f;
cameraForward.Normalize();
moveDirection = Vector3.zero;
if (Input.GetKey(KeyCode.W))
{
moveDirection += cameraForward;
}
if (Input.GetKey(KeyCode.A))
{
moveDirection -= playerCamera.transform.right;
}
if (Input.GetKey(KeyCode.S))
{
moveDirection -= cameraForward;
}
if (Input.GetKey(KeyCode.D))
{
moveDirection += playerCamera.transform.right;
}
if (moveDirection.magnitude > 1f)
{
moveDirection.Normalize();
}
rigidBody.AddForce(difference * walkingSpeed, ForceMode.Force);
}
what exactly happens when you press Space? did you put debug.log insie are you sure its running from space press?
You should first calculate moveDirection and use that as the desired velocity
Then calculate the difference, then add the force
You should not be adding forces in Update btw
only in FixedUpdate
What is FixedUpate?
Alright
the place where all your physics code should go
If you don't put it in FixedUpdate, you are going to move at different speeds at different framerates
Which is a very poor player experience.
So my Addwalk should be placed in FixedUpdate?
That is what I said, yes
technically input handling should be in Update, and physics in FixedUpdate, but in this particular case for now it will work alright if it's all in FixedUpdate
Alright, thank you
If and when you add jumping you'll likely need to switch to a more robust separation between input handling and physics
I already have jumping
I put moveDirection as Vector3.zero
95% of the time.. happens what need to happen.. i receive a shield for 3 sec.. but sometimes after playing a while.., the space gives the shield and at the same time opens the F1 menu.. what doesnt make sense as you checked in the code i sent here. Basically there are no other code pieces regarding this.. so no way the keys are messing up.. must be a unity bug
You aren't using it anyway. You should use it as desiredVelocity
When calculating difference
So just change the name of Desired Velocity to moveDirection?
Yeah or do thiscs Vector3 desiredVelocity = moveDirection * walkingSpeed;
That might work
Try to understand how it works otherwise I'm just spoonfeeding you here
Yeah, i'll try
You have a target velocity, you calculate a difference from current velocity to target velocity.
If your current velocity is already close to the target velocity, the difference is minimal, and very little force is added.
If the difference is bigger, the force will be bigger
OH, I think I get it
It's like a rubber band
Yeah, it's kinda cool
Also don't multiply the difference with walkingSpeed inside AddForce
Multiply it with a separate float, like acceleration
It lets you control the 'snappiness'
need help this suddently not working anymore for some reason
"this" is what
debug.log
Which one.
onpointer enter and exit
Exit doesn't have a Debug.Log, and Enter has two.. so.. which Debug.Log isn't working?
Is the object you're trying to interact with 3d or UI ?
Event System present in the scene and active ?
Bet, thank you
UI elements shouldn't have colliders
The Pointer interfaces work with raycast targets, like the Image component here
Check to make sure you don't have another raycast target covering them up, it'll only call the functions on the topmost thing you're hovering.
If you select your Event System in the scene, at the bottom of the inspector is a little status window (you might need to drag the handle up to see more than a line of it). If you keep that visible while playing, it should display the name of the object you're hovering over
Wait, do I even need to include the walkingspeed inside the Addforce or do I only need it when I times it with moveDirection?
Only with moveDirection
Got it
Like I said, use a different float to multiply the force so you can control the acceleration
That's make sense
ooohh.... i remembering delete Event System gameobject cuz i dont know what its for

That's why it was like the first thing you were asked once it was confirmed to be UI
public class Grapple : MonoBehaviour
{
private RaycastHit lastRaycastHit;
[SerializeField] private float maxDistance = 2f;
private bool PullSurface = false;
CharacterController characterController;
// Start is called before the first frame update
void Start()
{
characterController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
Vector3 origin = Camera.main.transform.position;
Vector3 direction = Camera.main.transform.forward;
RaycastHit raycastHit = new RaycastHit();
if (Physics.Raycast(origin, direction, out lastRaycastHit, maxDistance))
{
if (raycastHit.collider.gameObject.CompareTag("GrappleAble"))
{
print ("Can grapple to!");
if (Input.GetMouseButtonDown(0))
{
GrapplePull();
}
}
}
}
public void GrapplePull()
{
characterController.enabled = false;
transform.position = lastRaycastHit.point + lastRaycastHit.normal * 2;
characterController.enabled = true;
}
Why do I need to select a object refernece to set a instace of an object?
I don't know what you mean by that question
If you're asking why you have to assign a value to a variable to use it, it's because what would you be referencing if you weren't referencing something?
Like, how would you call a function on nothing
Which is lane 29?
if (raycastHit.collider.gameObject.CompareTag("GrappleAble"))
You didn't create the raycast itself right?
Your RaycastHit has nothing in it
You never actually store anything in it, you just create an empty one
so it has no object in it
Oh
You just told the engine "when a raycast that I didn't declare hits something" and it was like "?????"
im getting null errors with this field, even though it is being set in the inspector. how do i fix this?
If you're getting errors telling you characterSpriteImage is null then characterSpriteImage is null
maybe you have another copy with the field not set
Make sure you aren't changing it in the code and make sure you've set it on the specific instance of this script that's throwing the error
{
data.stamina = this.staminaBar.value;
}```
```public void SaveGame(string dataFileName)
{
foreach (IDataPersistence dataPersistenceObj in dataPersistenceObjects)
{
dataPersistenceObj.SaveData(ref gameData);
}
dataHandler.Save(gameData, dataFileName);
}```
I don't understand why I'm getting a null error on the first code
Either data is null, or this.staminaBar is null
my jump physics are extremely floaty and weird. what's happening? (isGrounded functions properly btw)
void FixedUpdate()
{
xInput = Input.GetAxis("Horizontal");
zInput = Input.GetAxis("Vertical");
player_rb.velocity = new Vector3(xInput * speed, player_rb.velocity.y, zInput * speed);
if (Input.GetButtonDown("Jump") && isGrounded())
{
player_rb.velocity = new Vector3(player_rb.velocity.x, jump_force, player_rb.velocity.z);
}
}
oh wait
i fixed it
nevermind...
found that data is null. but I couldn't find the reason why.. I've been in this one error for 2 hours now...
is there another way to jump isntead of addforce? or can somebody explain me why it boosts the player up insanely fast and it falls isanely slow?
Where do you set gameData
One would guess because you're giving a lot of upward force and not having much downward force
i have gravityscale on 3 and jumpforce at 800 if that helps
here in datapersistancemanager. the gamedata is a serializable
Where do you set gameData
does this animation setup work?
Show code
rigdbody too?
sorry for interrupting
Sure
what do you mean?..
I mean where do you set gameData
how are we supposed to know? what is work?
Dunno. You tell us
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
[SerializeField] private float Speed = 10f;
[SerializeField] private float JumpForce = 400f;
[SerializeField] private float CrouchSpeed = 6f;
[SerializeField] private float SprintSpeed = 18f;
[SerializeField] private bool IsFacingRight = true;
[SerializeField] private bool IsGrounded = true;
[SerializeField] private Rigidbody2D rb;
[SerializeField] private playerControls PlayerControls;
[SerializeField] private Animator anim;
private bool Jumping = false;
private void Awake(){
PlayerControls = new playerControls();
}
private void OnEnable(){
PlayerControls.Enable();
}
private void OnDisable(){
PlayerControls.Disable();
}
private void OnTriggerEnter2D(Collider2D collision) {
IsGrounded = true;
}
private void OnTriggerStay2D(Collider2D collision) {
IsGrounded = true;
}
private void OnTriggerExit2D(Collider2D collision) {
IsGrounded = false;
}
void Start()
{
Application.targetFrameRate = 60;
}
void FixedUpdate()
{
float move = PlayerControls.Floor.Move.ReadValue<float>();
rb.velocity = new Vector2(move * Speed, 0);
float Jump = PlayerControls.Floor.Jump.ReadValue<float>();
if (Jump >= 0.1)
{
Jumping = true;
}
else
{
Jumping = false;
}
print(Jumping);
if (IsGrounded && Jumping)
{
rb.AddForce(new Vector2(0, JumpForce));
}
}
}
``` we dont talk about graphics and leveldesign just a test
should prob be using impulse for jumps
https://docs.unity3d.com/ScriptReference/ForceMode2D.Impulse.html
ty didnt know this one
- You're resetting your vertical velocity to 0 every frame
- 9000 jump force is like stupid high of course it's jumping high you're giving it Dragonball Z levels of vertical speed
dragon ball z powers😂 but thank you that makes sense
tysmm you just made my day much better. im working on this script since hours haha
Ok I have code that teleports me to a object but I want to teleport on top of that said objecrt. How would i do that?
Change the position you teleport to to be on top of the object
im not good at this but maybe with teleporting to the y axis + a bit so it teleports you on top?
But how do I do that. How can take a object and tell where the top of that object is?
But different shaped objects
- Get the center of the object, add half the height
- Make a child object, position it where you want to end up, and teleport to that instead of the parent
Two options, depending on your use cases
have another question how do i "Cancel" the jump so the hight changes depending on how long i press space for exaple?
I know, i was just saying
Thank you
np
Use GetKeyDown for the initial jump and GetKey for holding the jump key to add additional force
is there a way with the new inputsystem?
Yes, look it up
I GOT THE DOOR TRIGGER TO WORK LETS GOOOOOOOO
are those mc textures
no
that looks like dark gray concrete powder
i dont know which version of minecraft you played but concrete powder?
now whenever you spawn in, the door opens 4 u
it's a pretty old block
Where do you make gameData not be null. Every object is null by default until you set it to something.
int number = 1;
I set it here
at "start" it will load the gamedata with a value, that's why Im confused how is it null when I save it
show that
you can probably fix is by changing it to:
GameData gameData = new GameData();
or when you pass it as parameter create a new GameData() there
So show the code where you set gameData
void FixedUpdate()
{
xInput = Input.GetAxis("Horizontal");
zInput = Input.GetAxis("Vertical");
player_rb.velocity = new Vector3(xInput * speed, player_rb.velocity.y, zInput * speed);
if (Input.GetButtonDown("Jump") && isGrounded())
{
player_rb.velocity = new Vector3(player_rb.velocity.x, jump_force, player_rb.velocity.z);
}
}
This is the code for the movement of my character controller, but my character isn't moving in the direction that it's facing in. I know that this is due to the fact that the Vector3s are moving the player relative to the world and not to its own orintation. How can I fix this?
you need to transform your input into the direction the object is facing. you can do so by creating a Vector3 from the input then pass it through transform.TransformDirection
wait im reopening my pc
Thank you! It works perfectly now.
private List<IDataPersistence> dataPersistenceObjects;
private FileDataHandler dataHandler;
public static DataPersistenceManager instance { get; private set; }
private void Awake()
{
if(instance != null)
{
Debug.LogError("Found more than one Data Persistence Manager in the scene.");
}
instance = this;
}
private void Start()
{
this.dataHandler = new FileDataHandler(Application.persistentDataPath);
this.dataPersistenceObjects = FindAllDataPersistenceObjects();
LoadGame("save0");
}
public void NewGame()
{
this.gameData = new GameData();
this.gameData.day = 1;
}
// Saves the game
public void SaveGame(string dataFileName)
{
foreach (IDataPersistence dataPersistenceObj in dataPersistenceObjects)
{
dataPersistenceObj.SaveData(ref gameData);
}
dataHandler.Save(gameData, dataFileName);
}
public void LoadGame(string dataFileName)
{
this.gameData = dataHandler.Load(dataFileName);
if (this.gameData == null)
{
Debug.Log("No data was found. Initializing data to defaults.");
// Initialize gameData to defaults
this.gameData = new GameData();
}
foreach (IDataPersistence dataPersistenceObj in dataPersistenceObjects)
{
dataPersistenceObj.LoadData(gameData);
}
}```
What calls SaveGame? It might be getting called before LoadGame or NewGame. Put logs at the start of each function and see the order they're posted in
Does anyone have any cool tips and tricks for debugging endless loops? On my end, I just slap a bunch of breakpoints everywhere until I can narrow down what's causing the problem
savegame is only called when I clicked a button
Still, put logs in all of the functions. See what order they happen in.
how can i add crouching in my game the best with the new input system? new action and adding bindings with modifiers?
Do you want press-and-hold crouching, or toggle crouching?
Either way, you only need to use one/two modifier bindings if you want to do something like
ctrl-A
ctrl-shift-click
press and hold
Okay, so you'll make a new input action and call it "Crouch"
then add one or more bindings
You'll leave the action as the default kind -- "Button", rather than switching it to "Value"
k thank you
To decide if you're crouching, you'll use the IsPressed method on the input action
How are you getting input right now? There are several options.
InputActionReference, the Player Input component, the generated C# class, ..
i think c# class should i send you my code?
this is how it should look like
Yes, show me the script you're working on !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're using the generated C# class, this will be very easy
!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.
cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class UIGameOver : MonoBehaviour
{
private TextMeshProUGUI textMesh;
public AudioSource GameOver;
// Start is called before the first frame update
void Start()
{
textMesh = GetComponent<TextMeshProUGUI>();
}
// Update is called once per frame
void Update()
{
if (GameManager.instance.gameOver == true && textMesh.enabled == false)
{
textMesh.enabled = true;
GameOver.Play();
}
}
}
the buttons should only be visible if i die yk
your code does not turn the images on. the images are disabled.
ok but when i able the image it will also show when i turn on the game
whats the command?
you already know how to enable a TextMeshProUGUI
sry took quite a while https://paste.ofcode.org/sLP38hbfXfcLq8jx8v4vWt
so you know how to enable an Image
yeah
okay, so you are using the generated C# class
e.g.
PlayerControls.Floor.Move.ReadValue<float>();
this is reading a float value from your Move action
PlayerControls.Foo.Bar.IsPressed()
This will return true if Bar is a button action that's currently pressed
So, maybe, PlayerControls.Floor.Crouch.IsPressed()
ok ty i try
Image is not image
capitalization matters.
you've declared a private field named image
ah wait
also, you'll need to give image a value
i would suggest adding [SerializeField] to those two fields so that they show up in the inspector
then just assigning them
Do you have a script named Image
howß
NO
by adding [SerializeField] before each field
[SerializeField] private Image image;
or, equivalently
[SerializeField] Image image;
fields are, by default, private
its the same with sprinting or not? btw ty it worked great
This works for any press-and-hold action
Pretty sure you have a script named Image
Oh, I missed the error, sorry
ok ty
Get rid of this using line.
There are many places that declare Image
and your code editor can't know which one you meant to use
You want using UnityEngine.UI;
literally just remove the line
using allows you to use things without typing the entire name
ok
before the game starts i have to make the image of the button invisible so that it only shows when i die
how do i do that?
yeah wait how can i upload a video
my englisch is not the best and its complicate
look
yeah, but then it wont show up when i die
Show me your current code.
Drag the Image component into the field down here.
that's why we added [SerializeField]
ahhh
this shouldn't change anything, though, since you still had the GetComponent
you'd get an error in the console if the variable was null
One thing, though..
restard.enabled = true will do nothing, because the button was already enabled
Oh, and the button was already enabled!
So the if condition was never met
Disable the button in the inspector. It should start working.
ok
hi i get the following error and wanted to know how i can make for add random number to my list in a fonction ?
the error: ```UnityException: RandomRangeInt is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'boutonJouer' on game object 'Image'.
See "Script Serialization" page in the Unity Manual for further details.
UnityEngine.Random.Range (System.Int32 minInclusive, System.Int32 maxExclusive) (at <40205bb2cb25478a9cb0f5e54cf11441>:0)
boutonJouer..ctor () (at Assets/boutonJouer.cs:14)
You should not give MonoBehaviour-derived classes a constructor.
as the error suggests, Awake or Start are often a good replacement
If you aren't sure if your code is running, you can add a Debug.Log statement to check
Debug.Log("Showed the game over text!");, for example
Do what the error says - run your code in Start or Awake. You're trying to do it in a field initializer right now
oh i can call my class start? but what that made if i make that?
That is not what I said.
mb i have understand that
Awake and Start are the names of methods.
specifically, they're messages
Unity will call them at specific times
still like that but now even the button wont work
but i dont want put it in a start methods i want that was in a other method
You cannot use unity-specific methods or classes in a constructor like that.
I see nothing wrong with using Awake
Awake runs the instant a component is created (as long as its game object is active)
"trigger event"?
Then put it in the other methods. You just have to put it in a method
yeah
!bug
🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!
💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
Show !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.
i want when i click on my ui that run this code public void down() { myButtonStart.SetActive (false); boutonController.boutonListe.Clear(); boutonController.boutonListe.Add(random); boutonController.boutonListe.Add(random2); boutonController.boutonListe.Add(random3); boutonController.boutonListe.Add(random4); timer.temp = 30; timer.jouer(); }
if i put it in awake that gonna run at the start of my game not when i click
I don't know what this code has to do with your error
No one is saying to move any of this
this has nothing to do with your error. your error talked about doing something in a constructor.
Share the entire script.
wait i have a better idea
Filename and line number of your error are right here. That is where you should be looking
I have a trigger enter that reproduces a sound (basically the most basic code in the world) But it dont works, i dont really know what i am doing wrong since i saw 2 different tutorials and tested with different things that may cause the error, someone could help me?
Hey how do i start a test run in virtuel studio community?
i dont see a run button or something
let me grab The Guide
"don't works" is very vague. You need to test and make sure the code is running (use Debug.Log) and if it's not, you need to double check everything in the scene is set up properly.
Walk through this. It troubleshoots all of the ways physics messages can go wrong.
using System.Collections.Generic;
using UnityEngine;
public class boutonJouer : MonoBehaviour
{
public timer timer;
public score score;
public GameObject myButtonStart;
public boutonController boutonController;
int random = Random.Range(1,9);
int random2 = Random.Range(1,9);
int random3 = Random.Range(1,9);
int random4 = Random.Range(1,9);
public void down()
{
myButtonStart.SetActive (false);
boutonController.boutonListe.Clear();
boutonController.boutonListe.Add(random);
boutonController.boutonListe.Add(random2);
boutonController.boutonListe.Add(random3);
boutonController.boutonListe.Add(random4);
timer.temp = 30;
timer.jouer();
}
}
int random = Random.Range(1,9);
int random2 = Random.Range(1,9);
int random3 = Random.Range(1,9);
int random4 = Random.Range(1,9);```
that's your problem
those Random.Range calls need to go in Start or Awake, as mentioned earlier.
You cannot use Random.Range outside of a function
as we said before
put them in Start or Awake
oh ok i see but when i put it in a start or awake i cant use it after in my other methods
This does not mean that random will constantly get new random values
Rnadom.Range
not the variable declaration
It's just running Random.Range(1,9) once and sticking the result in random
ohhhh ok ty
the trigger works but somehow the sound dont plays
int random;
void Awake() {
random = Random.Range(1, 9);
}```
e.g.^
i already made a debug.log
how do you know this? You need to debug it
Honestly just get rid of the fields and put Random.Range directly into the Add calls in down
why isn't it shown in your code?
Show it with the log
and show what printed
this isn't code
show code
I don't know what this means, this is just random
ok good, then that means it is playing
If you have a sound issue it has nothign to do with this code or OnTriggerEnter
1st make sure there are no errors in console
second, double check you don't have audio muted or something
or that the volume is not just too low etc.
(you can, indeed, mute scene audio)
All that is good, if i place it to sound when i enter the game it sounds
thanks
So it has to do with the gameobject or something?
where did that question come from
I don't think Play re-winds the audio
use Stop, then Play
maybe i'm just misreading the docs though
If AudioSource.clip is set to the same clip that is playing then the clip will sound like it is re-started. AudioSource will assume any Play call will have a new audio clip to play.
ty it worked
but one stays without working
Oh wait
it does work
i confused the trigger for the other one
thanks
using System.Collections;
using UnityEngine;
public class SwordCollision : MonoBehaviour
{
public AttackingEnemies enemies;
public int damage = 2;
private bool isHit = false;
private float hitCooldown = 0.5f;
private void Update()
{
// Your other Update logic here
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Enemy") && !isHit)
{
enemies.enemyHealth -= damage;
Debug.Log("Hit Health is: " + enemies.enemyHealth);
if (enemies.enemyHealth <= 0)
{
Destroy(other.gameObject);
}
// Start the HitCooldown coroutine
StartCoroutine(HitCooldown());
}
}
private IEnumerator HitCooldown()
{
isHit = true;
float timer = 0f;
while (timer < hitCooldown)
{
timer += Time.deltaTime;
yield return null;
}
isHit = false;
}
}
if i hit the enemy in quick succession isHit never equals false
Hey in my 2D game i'm getting these errors:
Can't you not hit them in quick succession since you are doing && !isHit?
Use Debug.Log and see what's happening
yes it does, you can do Pause and Unpause to achieve result where it doesn't replay
click on one of them and look at the full stack trace to see where it's coming from
I can hit them in quick succession but the animation just keeps playing and it has the looped off
in another script
looks like some other script is handling animation, which has nothing to do with this script
ty everyone that work perfectly now that was a pretty dumb error xdd
hey, i have 2 animations and i need help with making them work on all characters. as in i have a sitting animation that should work fine but when i play the animation on my characters their arms go through their legs and stuff like this. i believe i need to do something that is called ik or something but i have no idea on how to do it. can anyone help
The trigger keeps getting set?
I can still play my game and it works fine can I just live with my life and move on?
Ik that this may be a extremely stupid question, but someone knows or got a tutorial on how to make a sound not able to repeat anymore? I mean, when i do this and stop hearing the sound. If i get close again i came back to hear the same sound again, someone knows how to stop it?
i think you can make the code make the audioclip empty after its played
have a bool inside your class 'hasPlayedSound'
Before you call Play() you check if it is false, and after you play you set it to true
Yeah because you're setting it to true in Update. Every frame while that is true which will be the whole duration of your cooldown
You should only be setting it true when the coroutine first starts
Where?
right here
it's literally in Update
think about it
isHit is true for the whole duration of the cooldown
so you're doing it every frame during that time
ok that makes sense
The cleanest way to do this would be with an event
but you can also have the SwordCollision script drive this interaction by calling a function when the coroutine starts
That works but for some reason i cant hit them after i do that
after they do the animation
so i added slimes into my game
when i attack them there health goes into negative but they dont disappear
Seems pretty obvious - create the parameter
or make sure you spelled it correctly
etc
Also what calls RemoveEnemy()
also make sure you actually call RemoveEnemy from somewhere. Is it happening in an animation event?
Don't just throw up your arms and give up. Check on everything
nothing
Then it will not run
ok ill re attempt
So you should probably either use it or delete it
how can i make an equivalent of an oncollisionenter with the floor when im using a character controller? i have an IsGrounded bool which is a raycastspehre, but i want something to run once when they touch the floor (i.e. a ground puff)
Sorry, fixed link^
you can also just do this with your grounded check though
e.g.
if (!groundedLastFrame && groundedThisFrame) {
EmitPuff();
}```
i'll havea look at the collider hit, looks a bit easier
thank you
your getter is calling itself
make sure the property getter returnt he backing field health and not itself Health
If you have it call itself you will always get a StackOverflowException
So I want the editor/game to abort if something goes terribly wrong. Right now, I have this:
public static class UnityShortcuts
{
public static void Quit()
{
Debug.Log("Quitting...");
Application.Quit();
UnityEditor.EditorApplication.isPlaying = false;
}
}
While it does close the game, it seems to do so only when the editor has already attempted what it was going to do. I want more of an emergency abort. As in, as soon as this function is called, we instantly quit out of the application. Is that even possible?
only when the editor has already attempted what it was going to do
What do you mean by this?
ngl i dont understnad
What was it going to do?
Your current code is equivalent to this:
int health;
int GetHealth() {
return GetHealth();
}```
What you want is this:
```cs
int health;
int GetHealth() {
return health;
}```
properties are just functions
and you have a function that just calls itself, infinitely, until the computer runs out of memory.
you must change the property to return the field, instead of returning itself
I might need to record it to explain it better, but basically, when the function is called, the editor only closes when it gets the chance. So, for example, if I have an infinite loop running, the editor never closes since, I'm guessing, it needs a frame to close, which it won't ever get.
Once an inifnite loop starts there's nothing you can do from the Unity Editor UI or anything like that to stop it
dang
the only chance you have is force quit or attach a debugger and cause it to break out of the loop
Well, that's certainly good to know
in the video im watching
it like this and its able to work
how come they dont face the same issue
Show yours
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 139
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2023-12-20
Check line 15
didn't PraetorBlue explain this already to them
loool
Yes but they didn't listen
That one's less of a problem than 20
Actually a great argument here for _health < this private variable naming convention
underscore is one more key I have to press though
The only thing I could think of is that they're about to set it to private and look for all the compile errors to change them all at once
Indeed.
environmentally unconscionable
im sorry but im not very experienced with unity so which health shall i change
Literally just write your code like the tutorial is
and it will work lol
omg i cant even copy right
hint - your error is on line 15, as it says
i replaced Health with health
Do any IDEs warn about recursive stuff inside property getters?
I feel like they should
but do you understand why that's an issue ?
I'm kinda surprised intellisense didn't pick that up
Rider does
well it shows at least a recursive icon, there might be an inspection for it too
You didn't save the scene
scene != assets
Those assets aren't in the scene
dammmmmm the tghing closed cauise of the overflwo error im pretty sure
if it crashed unity without save prob
doesn't the scene save when you play though. I wouldn't know because I'm always saving
btw, the error is (mostly) in line 20. Your "get" for Health tries to return the value for Health, which tries to return the value for Health, which tries to return the value for Health,... creating an infinite loop
Nope. Only when you actually hit save
yh i cahnged it to health
its fine guys learning experience
Good perspective!
just be careful just copying blindly
yh i will
eg . it helps knowing what a property is and why is it you're using it in the first place
Yes, but people were pointing to the fact that the mistake was in line 15, when the issue was actually in line 20. You can keep the "if(Health <= 0)" as is without creating an infinite loop as long as Health doesn't "get" itself
This doesn't create an infinite loop, although I wouldn't advise doing it
GUYSSS
There was an issue on both 15 and 20. setter on 15 and getter on 20
oh, I looked at the fixed version, my bad
nevermind collider hit sucks, how would i calculate last frame and this frame like that?
Store your previous grounded state in a bool before the ground check
Or in a class-level bool at the end of the frame
just in simple bool variables with whatever your current grounded check is
To make sure my character grounded the ground has the layermask ground. If i want to make my character be able to walk on certain objects should i put the layer ground to them or make something else?
It's fine to use the same layer as for ground, unless you have some specific reason to have them on a separate layer
I just have a layer "Scenery" that I put all map objects in
Makes sense
guys im so lost
after thje slime deleted everything all over thje place
like my sword animation dosent work now
does any 1 know where i canstart to fix this
you're gonna need to explain More, you break down ur problem into smaller steps..
asking a question like that is too unspecific to get any real help..
thats like calling a mechanic and asking why your car "isn't running right"
why does the sword animation stop working..
i'd start there and find out whats happening and work backwards until u see something you know doesn't work the way you intended it to
theres a warning there in the console..
maybe its the code controlling the animator?
let this be a reminder to always use version control. and always commit changes before making significant changes so you can revert things if necessary
^ if u think ur saving often enough, u probably need to save more often 😄
wwhat version control
like a backup
versions of your projects so you can go back if something messes up
every day after u work on something important it gets uploaded to a server online..
oh ok i see what u mean
so if anything messes up u can revert it back to an earlier version
thats what www.github.com is
not even just versions of the project. it tracks every change you commit so you can revert anything at any time very easily
for example
its basically your project folder.. theres programs that will pull and push (save and load) for ya
what the program called
but yea, keep that in mind.. at some point when ur projects get big enough its something u'll wanna start using
GIT
@whole isle GIT
imagine the power going out and corrupting a project you've worked on for months
You can find basic setup and tutorials on youtube.
yh i probs do need to add that
you should always use it
Because if you push wrong you can overwrite stuff.
guys i think the problem is somewhere here
it was working fine before idk what changed
wasnt like that before tho
😭
well idk the exact problem, but u do have two if statements that are identical
did u know that?
oh crap ur rijt
So you Animator is trying to look for that parameter but its not there, Check your Animator
^ thas the problem tho..
isMoving is not set up as a parameter in that Animation Controller
so when u try to call it, it doesn't exist and causes errors/ undesired behaviour
you should be looking at the parameters list
An good idea to do when working with Animations is to have the animator window pulled aside and run the game as you watch the animator,
What are your paramenters in the controller.
in the code i wrote its moving should it not be player walks cause that what it called in my animaotr
parameters are on the left there.. you have to create it, bool, trigger, etc and use it as a transition or w/e
you create it and name it.. but it has to match w/e u reference in the script
if u use isMoving in the script make sure ur parameter is called isMoving
IsMovingis Moving- etc are not the same
omg ur a lifesaver i remeber doing that
i just closed unity and re opening it lol
but imma go check
ty
how would i set a rigidbodys velocity to 0?
You can assign things with = in C#
do you know how to assign to the rigidbody's velocity?
i know how to add velocity but not set it
if only a place to see all this info..oh wait..lol
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
rb.velocity = 0?
im facing another issue now
that wont work
almost. rigidbody.velocity is a Vector3 or a Vector2 depending on the type of rigidbody you are using. so you need to create a vector that is all 0
thats the circle of game-dev
instead of starting the game when im idle my idle animation is the walking animaiton
so vector3.zero?
u need to mark ur idle animation as the Default starting animation.. (it should be orange)
and then u transition into ur movement clips
OMGGMG NOW IM WALKING IN THE IDLE ANIMATIONM
Set as Layer Default State, thats how I commonly do it.. i'll create an Idle animation.. or for hard surface things, like a blender for example, my idle animation will just be a single keyframe and then i'd transition into the "running" animation
sounds like a transition problem
make sure ur clips are transitioning to the clips they should be..
and if not.. check the transitions/ the parameters, and the coding
if its not an error in the code then it'll most likely fit better in #🏃┃animation once u start getting into the editor stuff
in DetermineHeadbob() on line 64 i set the target amplitude and frequency according to the movemenet type, but it changes instantly when i switch the movement type, i tried like smoothing it on line 82 - 83, and then on lines 92 - 93 i tried replacing the target values with smoothed values, but it gives me weird results, so should i smooth the offsetX and offsetY instead?
https://hastebin.skyra.pw/difipawexe.csharp
is there a better way to do this? i think finding objects of type is kinda ass but its meant to account for new joining players
void Update()
{
PlayerScript[] players = FindObjectsOfType<PlayerScript>();
if (players.Length == 0) {return;}
foreach (PlayerScript player in players)
{
if (player.ID == playerID)
{
rt.position = _camera.WorldToScreenPoint(player.gameObject.transform.position + offset);
}
}
}
instead of using FindObjectsOfType every single frame, which is a pretty expensive call. just have the newly joining players register themselves with this component on join
wherever you have the logic where player joins do the stuff there
doing that in update is probably the worst way to utilize that
yup, as u work think does this make sense to be running every frame
super simple optimization hack
yeah thats why i asked
cus it felt a bit expensive
what does this mean?
nvm figured ito ut
did the wrong thing
Weird question, but if I have a bunch of essentially “nodes” and I want to connect them and fill in whatever shape is made, even as the nodes are moving, how would I go about something like that?
Question : how I earth do I begin with making a Shop System for a Portrait Android 2d Game?
Uh, start with the UI design then implement a shop script
sorry if this is a really stupid question but will tuts for character controller work with rigidbody?
if not, whats the best tut for rigid body 3rd person movement
CC and rigidbody are two completely different things and making movement systems with them are very different processess. Is that what you are asking?
yeah
CC does lot of stuff for you, rigidbody just simulates physics. Rb requires quite much of code to get character behaving correctly unlike CC which is made just for it
can you make momentum based movement similar to sonic frontiers with CC?
If you do the math and plug that into the move command, yes
Catlike coding has some text tutorials for RB movement. Haven't checked it much but their tutorials are usually decent
https://catlikecoding.com/unity/tutorials/movement/
If you want a video tutorial, I can't remember a decent one off the top of my head.
That being said, like Aleksi said, RB movement can get complex and you should get familiar with Vector maths
alr ill look at those, thanks
CC is easier to get basic movement fast
hey so im trying to have a ui image stay on top of a game object and its kinda working this is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InteractPrompt : MonoBehaviour
{
public Transform target;
public Camera cam;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector2 screenPos = cam.WorldToScreenPoint(target.position);
transform.position = screenPos;
}
}
and this is how it looks ingame how do i make it not be so far under it i want it to be right next to it
add an offset
why dosent it always let me drag the sprite into the animation
how??
screenpos + offset ?
anyone know why?
this is a code channel
screenPos.y += 50;
??
just make a new vector3 lol
[SerializeField] private Vector3 offset;, so you can adjust in inspector
in CursorLockMode, what is the thing to make it unlocked?
Google it
Since it is CursorLockMode.locked, which is the one to unlock it?
Type CursorLockMode. and look at the IDE suggestions for the one that looks like what you want
Thank you
What is that?
What is what
IDE
IDE is your code editor
The thing you type code in
I dont see suggestions in my code
so its not configured
Then you need to configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
ok, thank you
how to get mouse position in the scene tab?
I guess i wont, it's not available for my unity version
ty tho
huh
What?
It's for 2021+ unity versions
No