#💻┃code-beginner
1 messages · Page 488 of 1
can anyone hop in a vc with me and help me learn this shit, in not learning anything from just coping the videos
then you wont learn in a VC, learn by just making stuff
read the docs
and try to implement what you want
i would with somone guiding me while i try
i learn better when failing but being pushed in the right direction and bouning ideas off someone
unfortunately there is no VC's here anyway, so you would have to find paid services or get lucky to find someone
or alternatively find another server that does have VC's
well not unfortunately haha
That's called tutoring. You should really just google (and if you cant find anything, ask) if you have specific questions.
is there a way to do it where it just generates the points within the cone rather than generating a new point if it isnt in the cone
Make a vector that fits within the distance you want, rotate it randomly such that the rotation cant go outside the cone
if its not too much trouble could you show me what that code would look like
Im on mobile and cant, but you could probably find the code by looking at bullet spread tutorials. Which does the same logic
Just make sure it's a cone spread and not one which can be square, which I imagine some bad tutorials would end up doing
thank you
Hello, I was messing with animation the other day and I come back today and now my player doesn't move when I press the directional buttons
before it was giving me an error for the animator variable
Any idea what that could be?
I have code that spawns a lot of destinations for ai, but i need the destinations to stay when i hit stop, how do i make a script work when the gaME IS NOT BEING PLAYED
sorry for caps
Either save the data to some sort of file or if it's for the Unity Editor only, you can opt to save the data to some scriptable object.
has to be an editor script to work not in playmode
or u can save it to a file like dalp said
how do i save the data to a scriptable object
https://docs.unity3d.com/Manual/class-ScriptableObject.html
When you use the Editor, you can save data to ScriptableObjects while editing and at run time because ScriptableObjects use the Editor namespace and Editor scripting. In a deployed build, however, you can’t use ScriptableObjects to save data, but you can use the saved data from the ScriptableObject Assets that you set up during development.
Data that you save from Editor Tools to ScriptableObjects as an asset is written to disk and is therefore persistent between sessions.
thx
a problem I am currently running into is it keeps running into walls and getting stuck. I could just have it turn around if it hits a wall but I just think I should approach this in a different way. The random movement I have right now works fine I just want it to go back and forth less frequently
i need to make a script which scales the transform its on down to the target scale which is in a variable
but when i scale it the children positions change
so i need a reference object and track its original position
and then also move the transform so that even if i scale it its gonna be in the same position
i need this script to on the start of the game scale the transform on all axis to the "scale" variable, but also move the position of this transform so that the position of the referenceObject doesnt change
If you're wanting parent constraints without scaling, perhaps consider this https://docs.unity3d.com/Manual/class-ParentConstraint.html
i want to scale it
like scale the object down
but keep all the childrens positions
so it doesnt look like it changed
So.. you don't want to scale it and all of it's children - relative to it.
You want to scale it and all of the other object independently.
my ai keeps teleporting down below the ground? any ideas?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I don't see the navmesh agent component on the first 2 objects in the hierarchy 
Also, you know you can dock the game tab/window right?
i dont know what you mean
How are you expecting it to move?
this is my ai inspecter and it was working before
Why are there 0 components on the "wolf" object?
there is another one in the wolf that contains my logic and visuals
Why is the logic not on the root object?
Yes. You want it to move, right? If you're not gonna put the logic and the nav mesh agent on the root, it's not gonna move anywhere. The "wolf" object is basically unrelated to your wolf. It's just another empty object in the scene.
Now share the details of the object during the issue. As well as the navmesh surface.
fr we need deets
i think i might have solved it, i moved the terrain and didnt bake it againn, now the ai is frozen
It keeps changing its destination
ya, b/c u didnt rebake it.. (the actual navmesh is probably no where near where the agent spawned)
Yeah but now its frozen and idk why
i just told you why..
if the navmeshagent isnt standing on.. or close enough to a navmesh it doesn't work
you probably have an error in ur console saying something like that (that is if u have navmeshagent logic running)
anyway.. this is how i normally spawn my units on uneven terrain
starting at 0 + offset higher than highest peak.. (so if ur highest peak was +100 units) i'd start my raycast at 110 units above 0.. and then raycast downards w/ a length longer than that. (so it will touch the terrain)
once it hits u have a position that is exactly at the terrain
(ofc i use a LayerMask so i can avoid tall buildings and trees and stuff, so its only detecting the ground)
i am so confused
how can I some how store all of my game objects in some kind of list/dictionary, then be able to load them back and spawn each saved object accordingly? i'd like to make a save/load system like this, unless there's a better approach
the only attributes i'd ideally need to store are position, rotation, and type
u cant really save objects.. u could since ur already talkin about lists.. add all these gameobjects u want to saved in the list..
each number corresponds to an object..
0 -> this thing
1 -> that tree
2 -> this item.. etc and then save abunch of integers also inside a list or array or something..
then when u go to load.. u can have a script read the value from the save data.. and then load whichever object corresponds to it
private Dictionary<KeyCode, System.Action> keyMethods;
void startMethodBinding()
{
keyMethods = new Dictionary<KeyCode, System.Action>
{
{ KeyCode.LeftShift, updateSprint }
...
};
}
void updateSprint()
{
...
}
is this a valid way to call methods when a key is typed
i want to avoid making alot of if statements
did you try it?
ye but idk if it makes sense to do it this way, this is how i used to handle input in luau
if u figure out the best way to do it holler at me..
i gotta making a mapping system soon..
lol, i hate scripting input
also how do i iterate trough the keys?
i tried this but it doesnt work
foreach (KeyValuePair < KeyCode, System.Action > Key in keyMethods)
{
if (Input.GetKey(Key) == true)
{
}
}
i also tried KeyCode instead
you can just grab the list of keys https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.keys?view=net-8.0 or get the actual key from the key value pair https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.keyvaluepair-2.key?view=net-8.0#system-collections-generic-keyvaluepair-2-key
right now you're trying to plug in a KeyValuePair to the GetKey method
Though really id just use the new input system and not do any of this
so i would have to iterate through each item in the list to spawn it?
Honestly ill rather look more into that then, ty
roger
like here i have two arrays 1 for items and 1 for weapons..
in my load method i'd just loop thru them and i'd have a key or something to compare.. and that would hold all my objects
then the method would just load up all the items i need to begin the game
using just integer values..
then my Inventory Manager would populate w/ my items and weapons
ah interesting
altho theres many different ways..
If you have a list you're gonna have to iterate through it to even read all the values in the first place.
Typically youd wanna save it by some ID
Hi everyone. I have problem.
📃 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.
could you elaborate on the ID part?
no need more. i see where i have problem. thank you.
For anything that youd wanna save in your world, you could assign an ID, associated with the prefab, which could just be a number. Then you save that ID to file along with whatever else. When you read the file, grab the ID and spawn the corresponding prefab
oh okay
Hi everyone, quick question
I'm working on a puzzle automation game, and i have my own level editor, that can save the map i'm working on to a scriptable object, and the game then when playing the level loads the stuff for it in
Editing, saving, loading and playing works perfectly fine, but when i close and reopen unity, one of the scriptable objects storing the level data randomly dumps all it's stored stuff
I have no code that runs without the game running too, so it can't be that i'm calling a function that would do something like this
the map data is basically just a list of a struct that stores the ID of the prefab (it's position in a list of all the prefabs that are in the editor), and the position and rotation of the piece (first pic)
the only time i'm actively modifying this list is when i call the save function, that is tied to a button inside the in game editor, it shouldn't be called anywhere else (pic 2)
am i doing something wrong when setting the stuff in the scriptable object that can cause this, or is this a unity issue? and if it is, is there any way to work around it?
Managed to fix it
For anyone who has this issue, what worked for me was manually marking the SO dirty, and then manually saving the assets
you should not save in scriptable object if you want to preserve data between build play session
It's specifically for an in editor scenario tho sorry for not specifying in the original message, i use this inside unity and not in a build
Anyone have an idea on what I could do for arcade-like racecar movement while still having good, realistic car collisions? it's kind of hard for what i'm going for, since i want non-physically realistic movement while also having physically realistic collisions. rn i'm using convex meshcolliders and mesh deformation and such
https://www.youtube.com/watch?v=cqATTzJmFDY similar to this, but with mesh colliders on the car
Learn how to create Arcade-style Car Driving in Unity with a brand new tutorial!
Download the setup project files here: https://drive.google.com/open?id=1qVal_BSXdE5mYtA_8douoVSKkYNIAM3w
Wishlist 'Scoot Kaboom and the Tomb of Doom' right now at http://bit.ly/scootkaboom !
Get my new Udemy course 'Learn To Create A First Person Shooter With Un...
https://www.youtube.com/watch?v=CpXT5So1Gbg&ab_channel=SpawnCampGames i add collisions to this type of controller in this video
Improving the Arcade Car Controller with Collision.
Skip the Set-up and jump straight into the collision @ 5:36
📄 Scripts
https://github.com/SpawnCampGames/YT/tree/main/CarController
🎮 Assets
Barriers :
https://assetstore.unity.com/packages/3d/environments/barrier-traffic-cone-pack-82549
Track :
https://assetstore.unity.com/packages/3d/enviro...
holy hell you are my saving grace
tysm man
its not perfect collisions
but it works pretty well.. considering its just a rolling ball
i actually searchjed on yt for like
6 hours and didn't find something
u are the actual goat
i hope it works for ya 👍
it should
if u check the description the project is on GitHub also
could help to see it already setup and everything
theres little edge-cases i havent solved yet
but.. its a start lol
ive been trying to make my guy walk up stairs but i cant quite seem to figure it out, he keeps getting stuck and it moves way to jankily when it does work
what am i doing wrong here?
Vector3 qw = manager.gravityDir*1.1f;
RaycastHit lowH;
bool stair = Physics.Raycast(col.bounds.center+qw,frfor,out lowH,0.5f);
if(stair && (Vector3.Dot(lowH.normal,rig.linearVelocity)<0)){
if(!Physics.Raycast(col.bounds.center+qw/2f,frfor,0.5f)){
Vector3 climb = transform.position-(manager.gravityDir*stepHeight);
transform.position = Vector3.Lerp(transform.position,climb+transform.position,0.05f);
} }
}
not sure u wanna go this way.. but a simple way to deal with stairs... is to use a ramp collider instead
stairs can just be visual
i may need actual stair-stepping abilities later on for slight deviations in terrain
I personally use a raycast suspension on my player to negate this effect
Stairs are a pain in general
whats a raycast suspension?
i have this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
// Start is called before the first frame update
public Vector3 jump;
public float jumpForce = 2.0f;
public bool isGrounded;
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
jump = new Vector3(0.0f, 2.0f, 0.0f);
}
void OnCollisionStay()
{
isGrounded = true;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("space") )
{
if(isGrounded)
{
rb.AddForce(jump * jumpForce, ForceMode.Impulse);
isGrounded = false;
}
}
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0); // Get the first touch
// Check if it's a tap (or touch began)
if (touch.phase == TouchPhase.Began)
{
Debug.Log("Screen was tapped!");
// Add your code here to handle the tap
}
}
}
}
but the isgrounded doens't work. it lets me jump while it's not grounded
Exactly what it says it is
You use a raycast and apply suspension forces to your player
It will just go up stairs and slopes normally
oh ok
this is one of my favorite kind of controllers
i looked it up, it seems like something used for vehicles?
A detailed look at how we built our physics-based character controller in Unity for our game Very Very Valet - available for Nintendo Switch, PS5, and Steam
BUY NOW!! https://toyful.games/vvv-buy
~ More from Toyful Games ~
- Animation Deep Dive mentioned in the video - https://toyful.games/blog/character-animations
- Custom Car Physics in Unity...
it can be used for vehicles.. but nothing stops it from being on a character
alright, il watch this then. thanks
its one of my bookmarked videos
b/c of how clever it is
just "game magic" type of thing..
ur graphics will have its feet on the ground.. the actual collider tho.. it floating
Is it possible to run a method from a different script which is on the same gameobject?
yes, if you reference a different script you can access its variables and methods
usually you will have to use GetComponent<>() to reference and set its value to whatever component you choose get
Of course, very common
Get a reference to it, and call the method
thank god
Usually you would declare a Serialized Field in the script and drag/drop the required reference in the Inspector
he said "on the same object"
exactly
If both scripts are on the same game object setting the reference in the inspector is better than using GetComponent
why?
because then you dont need the GetComponent call
using get component is so much easier...
really? why have an extra line of code which could go wrong if you don't have to?
id rather have its value be set automatically and find the script on its own rather than sometimes forgetting to drag and drop in the inspector and getting null ref errors
plus get component cant really go wrong as long as you have [requirecomponenttypeof()]
and if you forget to add the script you still get a null ref
which is why i said this ^
its less of a headache for me in all honesty and i wished i did this more when i was starting out fresh
so 2 extra lines of unnecessary code
"unnecessary" to you 🤷♂️
I don't think you would find many people who would agree with you
and thats ok 👍
It has always been a design philosophy in Unity to keep GetComponent calls to an absolute minimum
is there a specific reason?
overhead and easy to break
script execution order for one
true, i never thought of that nor ran into that as an issue before
thanks for the insight, i guess
yep, SEO can bite you in the arse more often than you would think
yes
hi I have been using unity version control
but i wanna switch to github
do i need to disable unity one
personal preference
there is certainly no point in having 2 different version control systems running at the same time, that way leads to confusion and ruin
Gentlemen I need some help, I have been assigned a project wherein my objective is to simulate a electric motor connected to a load in order to derive the heat, power consumption etc.
the project is a Proof-of-Concept and so far i have managed to basically achieve nothing so far. I have tried to attach the speed of the motor shaft to the sprocket, that did not work, and the opposite too which also did not work
I am basically stumped at this point, Internet and CGPT have not been helpful
right now all this is just a fancy screensaver
What exactly doesn't work?
The Rotation of the Shaft and the Rotation of the Sprocket is Independant of each other
Can you record a video?
I can, but to explain in words basically the Motor Shaft and the Sprocket both move independant of each other based on values inputted manually
there is just no Linkage between the two
You'll need to only move the motor and everything else would either need to be linked via joints or by collision with the motor parts.
I see, There is a problem here tho, the Chain and Sprocket are generated with the use of a Tool from the Asset Store: https://assetstore.unity.com/packages/tools/game-toolkits/chain-and-gear-generator-273628
The Speed at which the Sprockets rotate is controlled by it's own script via the variable "Machinery speed"
Changing the sprokets to Rigid body might break the whole thing
Looks to me that you can easily feed the shaft speed into this machinery speed variable
Do you need the setup to be physically accurate or not?
Physically accurate, The Ultimate objective in my project is to be able to Vary the Load on the larger cog and thus be able to simulate the Heating, power draw etc. of the motor
now if I can get away with doing that without physical accuracy, I'll take it
Then you probably shouldn't be using that asset.
I see
Do I have any options with regard to using Chains and Sprockets?
I'll settle with Gears too
In terms of models you can use whatever, even the ones from the asset you're using. But the setup would need to not rely on hardcoding.
I see, so what are my avenues here
because I am a Complete Beginner to Unity
like, 0 experience whatsoever
Research the available physics components, like joints and stuff and use them in the setup.
The only script you would need is one on the motor to set it's torque.
I see
Thankyou mate
alright so I changed the layout, used two gears, and now only the left gear is spinning not driving the one on the right
The gear on the left is fixed joined to the Shaft which rotates it, the gear on the right is also fixed joined to the shaft which is to be rotated
@hexed terrace whats wrong on line 37?
the last bit -> #💻┃unity-talk message
whats the best way to play an animation backwards?
set speed to -1
thats what i tried aaaaaand it didnt work
retractAnimator.speed = -1; this right?
Well I tried mesh colliders to try and have the two gears spin each other
suffice to say it didn't work at all
then you need to show what you've tried and show how you verified that it didn't work

ok brb
yea so mesh colliders just makes the driving gear fly off from it's axis
is there something wrong with Quaternion Slerp?
The problem is obvious. You are giving values in the Y and Z axis, when you want to give JUST Y.. zero out the other axis.
0, Yval, 0
i did it but it gave me an error
so.. read the error. research the solution
at least did i do it right?
nope
don't you think setting targetRotation to 0, Yval, 0 would be the obvious thing to do ?
im new i have no idea
It's LOGIC
yeah but where do i exactly put it that i dont get
think about it.. you want the correct rotation before you set the turret rotation
step through the life of targetRotation, think about it
you're also dealing with Quaternions for some reason, would be easier with eulers
there's not enough context here
i want to play my animation backwards
Alright I figured it out
I just straight up used a script to do the job for me
you are setting the speed of the snimator not the animation
okay so how do i get the animation state
i'm aware of that, but you haven't even shown how you are calling these methods. you've shown buttons in the inspector but i see no relevant attributes in the code you've shared
how could i know if the PlayBack method is even being called
i showed the methods tho?
theres a code above the video
please learn to read
and enough with the stupid emoji replies, use a reaction so i don't get pinged for inane bullshit
superiority complex final boss
right so i'm definitely not helping you anymore
right... have a good day
you can also use this
https://docs.unity3d.com/ScriptReference/Animator.GetCurrentAnimatorStateInfo.html
i tried that and set the speed but theres only a getter
i cant set it
not sure it would work for you if you are not using Animator states anyway
well that's certainly not a code question, nor is it unity related. but you do know discord has an inbox that will show you all of the direct replies and messages you've received right?
no thanks I look at it and remove the previous post
Anyone know why this isn't working -_-"
public GameObject[] dataPlanes;
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < 100; i++)
{
dataPlanes[i] = (transform.GetChild(i).gameObject);
}
"What" is not working?
It isn't assigning any list items
an array is fixed size. you need to initialize it with a set number . . .
Nevermind, figured it out
public GameObject[] dataPlanes;
// Start is called before the first frame update
void Start()
{
dataPlanes = new GameObject[100];
for (int i = 0; i < 100; i++)
{
dataPlanes[i] = (transform.GetChild(i).gameObject);
}
then you can populate it with . . .
yes, here you initialize it with a set number. it makes sense to use the transform's child count as the size to fit all of them instead of an arbitrary number . . .
i noticed you called it a list. this is where the error lies. GameObject[] is an array which has a fixed size (length) and cannot be changed. List<GameObject> is a list which can grow/shrink dynamically. both are called collections which store a group of objects . . .
I only called it a list cuz I've used Visual Scripting for years lol
How did you confirm that?
by commenting out the for loop
and seeing if the OnEnteredSeat triggers a bool to false
and it does
hey i think i fixed it?
but when i uncomment the for loop it sets it true
because of the for loop
Idk what your code does but the for loop definitely runs before the event invoke
even tho the OnEnteredSeat sets it to false
yeah its supposed to
so im not sure
Use Debug.Log or debugger
You'll probably figure out the issue if you attach and step through it
but how the fuck does it not set the bool
the for loop resets it
wait
something is wrong
this channel is for beginner coding questions. if you want general unity questions, try #💻┃unity-talk
that's fine, as long as it's related to coding, then you're in the right place . . .
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
ive made a state machine for my game and theres a logic if player grounded you can jump once
im trying to change it to double jump
but im kinda having troble with it
my jump state https://pastebin.com/dTBemRd3
my machine state https://pastebin.com/5qP9dkDB
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Would be good to discribe what the issue is
ahh further up, aight
we would need to see pivots
it is on pivot
wat?
Im talking about the gizmos, for the pivot. The axis directions
the colored arrows
i thought u meant this
the axes could be incorrect for the model . . .
what is the pivot for the top part, that seems to be the part rotating
Looks like you have the base here.
Select the gun part
first one is the head and second one is the partToRotate
this one is the entire turret
oh ok , whats first one look like when its in scene not rotated in playmode
make sure this is set to local
Ah, that was scrolled off screen
why did you put it back to center?
Green = Y, should be pointing up
and blue is correct for the first one but not the second
can seeing if my game strains the cpu, ram or gpu help me tell what in my game could use optimising
AND you want it located at the rotation point.. not in some random position (or centered)
use the profiler and find out everything you need to optimize
Just use the profiler
i have used it maybe i am missing something
it looks like this when i remove the head
does the profiler show exactly what is straining the game or something
its fine but backwards
Blue is always your Forward
either use blender and fix it, or just make a parent object then adjust the child so the foward matches parent blue
well yes, how do you claim to have used it if you don't know what it does
you'd ideally want the Z axis pointing the same way as the barrels... otherwise you're going to have to add 180 to your look at calcs
used it and used it properly are two different things
no i didint do anything i just removed the head from part to rotate
what should i be getting from this
Clicking on those graphs will give you information. Also, this isn't a code question, so shouldn't be in here.
Probably look on !learn 👇 for guides on how to use the profiler
Yeah I get that but ideally you want to have the setup described here #💻┃code-beginner message
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
my fault
here Unity has made this, if you watch it all you will understand how to use it https://www.youtube.com/watch?v=xjsqv8nj0cw
IDK if this is the channel to ask, Can anyone explain to me why this code does not work. The tags are assigned but it just wont do anything at all once a collision happens...
follow this https://unity.huh.how/physics-messages
also why is the top OnTriggerEnter nested inside another method 🤔
as im fairly new, i dont know whether the function is called every frame or once start is hit
thanks alot for the info
wdym by barrels?
the barrel of a gun
oh
like this you fix the pivot in unity
do i make the parent for the partToRotate or the Head?
anything you rotate and need calculation to match you need to fix the pivot as shown, graphics should always be children so they can be rotate to match parent with correct pivot
so any object that has some sort of pointing direction, ideally want this fix
Another quick question, how do you combine if statements? For me i get a compiler error if i do it like this. How do i do it right?
&& , || u need to first clear concept before using these
where'd you get %% from? i think you want the AND && operator . . .
double modulo 🤔
oops i mixxed them up, i appreciate it
you should prob specify which one is which 😉
Ok what did i do wrong this time?
did you read what the error said?
hover over the red squiggly error . . .
currently checking this one out it seems helpful but theres just so much info
you have to look at the mistake in order to understand what you did wrong . . .
bookmark it, read it a bit at a time (these operators are very important)
"Invalid Expression &&", which seems wierd as && means AND for all i know now
if statement is not closed by semi colons
Im a total beginner so i appreciate your help so much guys
thats part of the problem yes
its also not in the same statement
if (other.gameObject.tag == "BODEN")
this is a complete statement.
It's not a boolean, it's an entire line
also, you have a semi-colon after the if statement. that makes this a single-line statement; anything inside of its scope will not execute (run) . . .
closed the first parenthesis too early
do these switch states need to be in update, they control where the enemy will go and seem to be using alot of computing power
{
switch (state)
{
case State.Idle:
if (Health.health <= 0)
{
anim.SetBool("idle", true);
}
break;
case State.Patrol:
Patrol();
break;
case State.Chase:
Chase();
break;
}
}```
it is like magic onceit works and now i feel kinda dumb haha
checking switch statement isn't antyhing heavy , its as "heavy" as if else statement chain
Do you want this to run every frame?
yes lmao it caught my eye first so i stopped analysing the rest
when HandleJump is called, does it add to jumpCount and _DoubleJump?
do you mean as heavy as the states they start
you said
" seem to be using alot of computing power"
You have to find out which one of those then because switch in Update alone wouldn't do that. Its quite common
you should check scripting tutorial for unity first to understand how to code properly or u will be wasting alot of time debugging stupid stuffs
any c# tutorial will do. Usually find better less click bait trash that way than Unity specific ones
you cant not now, that's your job is to debug those unkowns
no, you're checking for each of these states every frame. if you're already in a state, you should only have to update that state every frame, not check if you're in each state every frame . . .
_DoubleJump is somthing ive add to debug but it dosnt seem like its effecting it
_DoubleJump = flag
then find out why
ive tried idk why
try it how ? did you debug it where is the debugging and what did you check in debugging
I dont see one single log in your code. nvm maybe 1 and it prints something not helpful
that's weird because _DoubleJump is added right after JumpCount. both should increase by 1 . . .
ive tried flag "_DoubleJump" = 0 then check if its 1 then dont enter if(...)
doesn't it go from 1 to 2?
is there anywhere else you are increasing JumpCount? search your scripts . . .
ok ive had here chatgpt version
now im using the code ive send
its 1 in the JumpCount
but no doublejump still
ive placed public for double jump and it seem to be stuck in 1
jump state
https://pastebin.com/7DqbcmL4
state machine
https://pastebin.com/mQFJLqt7
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
please use a better site listed in !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.
jump state
https://paste.ofcode.org/367qbweiq8EHQ3pjXWZ5WHj
state machine
https://paste.ofcode.org/K9NQ3ufmzsN8gyuF5WC97R
whats supposed to happen instead?
i want to be able to do double jump
so is HandleJump hitting ?
yea it does the first jump
but not the secound
im mean in air jump "double jump"
which line is supposed to make it double jump ?
tihis ?
else if (Ctx.DoubleJump < 1)
{
Debug.Log("enterd the double jump if :: ");
HandleJump();
}
i think handlejump should be able to do as many jumps as u want if u calling it the only thing that should stop it is if statement
i was trying to see if it will go there
taking out the grounded if and if for counts, are you able to run Handle jump multiple times
https://paste.ofcode.org/v7VHuAMNqaJiKqPfvftrDK
this is the state grounded
if i take out
//if (Ctx.IsJumpPressed && !Ctx.RequireNewJumpPress)
//{
SwitchState(Factory.Jump());
//}
it will loop jump but only after he hit the ground
what about this Ctx.CharacterController.isGrounded in PlayerJumpState
im making it but it changes the head position
then your original mesh has pivot that far, just move it into place as well then
since you're rotating the parent , the rest is just visuals
i have nothing about it
beside
state machine:
CharacterController _characterController;
public CharacterController CharacterController { get { return _characterController; } }
CharacterController is somthing that comes unity https://prnt.sc/6dxx5mssy0LG
I'm saying if you take out that if statement are you able to put HandleJump . im unsure how you're supposed to call HandleJump again
i know what a character controller is lol that wasn't the question
XD ok i wasnt sure im kinda confuse about all of this
imo this is already overcomplicated statemachine for simple setup
its complicating it more for you
how many states are you really having ? if you're new to FSM start with something simpler like enum and switch statement
try using super states like grounded state where the child inheritence are like move and idle states then air state with jump and fall states ..simpler logic can make it easier for you to transition between states
So there's a project where there are 4 buttons and each button has a special effect when I click it. For an example one of these buttons move that big cube on the video up when it's clicked. How can I make some event that moves that cube up that gets called from a button's script?
using UnityEngine;
using UnityEngine.InputSystem;
public class Keyboard : MonoBehaviour
{
private Camera playerCamera;
void Start()
{
playerCamera = Camera.main;
}
void Update()
{
Mouse mouse = Mouse.current;
if (mouse.leftButton.wasPressedThisFrame)
{
Vector3 mousePosition = mouse.position.ReadValue();
Ray ray = playerCamera.ScreenPointToRay(mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit))
{
if (hit.collider.gameObject == gameObject)
{
Debug.Log("u"); // instead put here an event and from the other script log "u" and move the cube up
}
}
}
}
}
Not sure if it's related to #💻┃code-beginner but anyways
public override void CheckSwitchStates()
{
//if (Ctx.CharacterController.isGrounded)
//{
Ctx.IsJumping = false;
Ctx.DoubleJump = 0;
SwitchState(Factory.Grounded());
Debug.Log("isGrounded :: ");
//}
if (Ctx.DoubleJump < 1)
{
Debug.Log("enterd the double jump if :: ");
HandleJump();
}
}
public override void CheckSwitchStates() {
if (Ctx.IsJumpPressed && !Ctx.RequireNewJumpPress)
{
SwitchState(Factory.Jump());
}
}
its going up no gravity
if i press jump it stops it
did I do something wrong here?
hit.collider.gameObject == gameObject
why are you checking if the ray hits the object doing the raycast ?
also would use UnityEvent or something to Invoke
from this screenshot alone its hard to tell, did you fix the pivot and which object is the script rotating the parent or child?
because I need to check if the player cursor hits the button
are you trying to check the cubes with a raycast?
you should be checking for the "Keyboard" component
i think it uses SetSuperState
its set here
IsRootState = true;
playerbaseState :
i didnt do the script part i believe
these cubes are supposed to be an ingame keyboard which you can use through clicking with mouse
that doesnt answer the question
what am i supposed to do in the script?
why should I check for the keybord component?
because thats how you tell them apart..
if (Physics.Raycast(ray, out RaycastHit hit))
{
if (hit.collider.TryGetComponent(out Keyboard keyboard))
{
keyboard.DoSomethingInThisKeyboard();
}
}```
Does anyone know how I can render a particle system over a screen space canvas (which fills the whole screen)?
forget the script part, you havent shown the setup being fixed first
code comes after..
i set the empty parent on the turret and rotated it
show w the hierarchy visible and the pivots setup
btw when someone says "shown" they mean visually
I'm not at your computer nor am i psychic so I can't see what you see
alr what about PartToRotate, show the inspectors too..
okay which object has the script you shown snippet from, can you show the inspector for it
that way it does "keyboard.DoSomethingInThisKeyboard();" because the script is attached to 4 buttons
exactly and each button has their own Keyboard that is a separate instance, so they each their own distinguished action or identifier to tell it apart
ah, I guess I'll put the raycast thing into player and button effect into button
you mean in the parent i created in?
where was it before ?
you put this script on a gameobject yes ?
inside one script
no?
you said we'll do the scripting later
OH nah you should have this On 1 script on player
then on Keyboard you put each thing you want to do different
i said fixing the code part, but you had this script on a gameobject before , you remove it?
need to make sure its referencing the correct Transform
see how you referencing Head ?
instead of PartToRotate
you're rotating the one with the incorrect axes
thats first
Turrent 2 component should be on Turret root gameobject anyway.. and referencing PartToRotate in the Transform Turret field
you should not put logic scripts buried in the mesh
i put the parent in the turret, is that correct?
which parent?
just show screenshots so we dont get confused
this is correct
Your reference on the script is not
which is?
ohhh
please tell me you understand 5% of what we're doing so i can keep going 
it fixed a bit
so the parent was useless?
what?
was it just a minor mistake i made or was the parent essential
its there to ensure the code matches the axes correctly
try changing code to
Vector3 directionToTarget = target.position - turret.position;
directionToTarget.y = 0f;
if (directionToTarget != Vector3.zero)
{
Quaternion targetRotation = Quaternion.LookRotation(directionToTarget);
turret.rotation = Quaternion.RotateTowards(turret.rotation, targetRotation, rotationSpeed * Time.deltaTime);
//etc
}
did it work ? @lunar kelp
what's the difference between this
using UnityEngine;
using UnityEngine.InputSystem;
public class Keyboard : MonoBehaviour
{
public void DoSomethingInThisKeyboard()
{
Debug.Log("y");
}
}
which gets called by
if (hit.collider.TryGetComponent(out Keyboard keyboard))
{
Debug.Log("u");
keyboard.DoSomethingInThisKeyboard();
}
and having DoSomethingInThisKeyboard as some event... or something...
why not Put event inside
well no one said copy it verbatim. It was an example
obv you replace it with whatever your names are
oh right i completely missed it
public class Keyboard : MonoBehaviour
{
[SerializeField] private UnityEvent theEventToDo;
public void DoSomethingInThisKeyboard()
{
Debug.Log("y");
theEventToDo.Invoke();
}
}```
if you do this you can plug a different thing inside the inspector on each Keyboard
multiple methods (delegates) can subscribe to the event. calling a specific method will only run that method. you can subscribe different methods to an event per instance of Keyboard . . .
Having trouble making a camera control system for aiming in my top down game. I have written this script to handle moving the camera to where the player is aiming, but because you aim by clicking on the screen somewhere, when the camera moves to that position the cursor's location in 3d space changes, resulting in the aim moving constantly in the direction you are clicking
if (Input.GetMouseButton(1))
{
RaycastHit hit;
Ray ray = cam.GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
//if the player clicked on a valid location
if (Physics.Raycast(ray, out hit))
{
//handle camera movement
aimPoint.transform.position = hit.point;
...
I think I would need to offset the cursor by the amount the camera moved, but I'm not exactly sure how I would accomplish that and I didn't see anything similar on the forums
i dont know why its doing this now
i tried to put partToRotate but it didnt work for some reason
in which way is moving ? like different heights ?
X and Z translation
the idea was that you would aim at a location and the camera would move over where you are aiming to give you a better look
oh I see. First I'd use a planeRaycast
or do you not want player to be able to aim outside the colliders?
its shifting up and down probably because if height variation in hitpoint
shifting up and down isn't really the issue, that I can solve by stripping the vertical component from the vector
but mainly you want to add like a min distance before camera follows the cursor
yeah that fix verticality issue but still breaks your aim if you ever have mouse in the gray area
something to keep in mind
yeah, thats alright for now. I will probably change that now that I am reading about planeRaycast since having your aim get stuck on that isn't the most pleasent
but the core issue still persists, it's using the mouse position as more of a movement vector than a target to observe while aiming
something like this ?
I keep getting this error, I've tried everything to fix it, Google, Youtube and even myself but I simply can't get rid of this error.
Here is where the error directs to:
if (ShouldLoadText)
{
//this one
if (dialogues.Dialogues[DialogueIndex - 1] != null) StartCoroutine(LoadText(dialogues.Dialogues[DialogueIndex - 1], SpeechBubble));
ShouldLoadText = false;
gameObject.transform.GetChild(0).gameObject.SetActive(false);
gameObject.transform.GetChild(dialogues.Expression[DialogueIndex - 1]).gameObject.SetActive(true);
}
you get rid of it very simple, don't go over the bounds
get rid of the line that makes the error?
I can't do that, it's essential to my game.
sorry abt that
there are multiple collections to check here
I tried this:
if(DialogueIndex < 0) DialogueIndex = 0;
if(DialogueIndex > dialogues.Dialogues.Count - 1) DialogueIndex = dialogues.Dialogues.Count - 1;
``` but I still get errors
GetChild can also return out of bounds btw
this will check if it's out of range or negative, but I still get errors
actaully thats a good point, I never noticed that because the error was pointing to the startcoroutine one
I mean its possible thats the one, but its good to double check because transform basically holds collection of children
Debug.Log the indexes in the code
what should I do, like before?
the one you said?
start with DialogueIndex-1
alr I'll tell you the results
also make sure you add this to second parameter of Debug.Log
oh yeah one thing to state is that the error is outputted alot of times, like 1k
then it means you tried doing it 1k 🤷♂️
like this?
Debug.Log(this.DialogueIndex - 1);
I did the embed wrong
so ignore the cs
Debug.Log($"{name} DialogueIndex is {DialogueIndex - 1}", this)
what does the "this" do at the end? just curious
when you click log in console brings you to the object / component that called the log
I've only got one object using the script
still its good habit to do so for future
there could one day be an object with the same component that has an empty collection and you dont notice etc.
ok
https://youtu.be/sWCnL-3JMag?t=184 more along these lines
If you're new to Foxhole or are struggling with picking up kills with a rifle this guide will take you through some quickstart tips that you can use right now to improve your aim and land some hits.
Normally I would enter chapters but it's a short video and if you need to watch some of it you should probably watch the whole thing - I hope it he...
I'm not sure why it's -1, the game works fine.
I dont understand this just zooms out for longer range
everything else moves the same
I found the problem, at the beginning it's -1, and then afterwards it's changed to 0 where it performs fine in game.
thank you for you're help
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
!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.
Touch touch = Input.GetTouch(0);
if (EventSystem.current.IsPointerOverGameObject(touch.fingerId))
{
Debug.Log("yes");
return;
}
if (um.gameState == GameState.MainMenu)
{
Debug.Log("touch");
um.DraggedAtStart();
}
crude drawing time. green represents the non aiming fov around player P, orange represents the fov while aiming at the target T. The camera is normally centered on the player, but then aiming it shifts to a point between the player and the target (and zooms accordingly) to give a better look at where you are shooting
This is in Update. "Yes" get logged like 5 times but after that it logs "touch". The touch is over an ui element. No idea why does it first correctly detect it is over an ui (multiple times) but then doesn't
use 2 cameras with cinemachine, 1 that follows the player.
To get the inbetween effect would be easier to do 2 Transforms, 1 is the target position on cursor transform and the second is the origin of the weapon or whatever aim origin.
The Target Group in cinemachine could probably always keep a proper view between the two. Then just toggle between the two cameras, cineamchine adds nice smoothing you can adjust
lol I forgot the actual problem my b, I have the camera movement sorted, just gotta lerp and it will smooth out. the issue is when the camera moves, the cursor is no longer in the same location in 3d space, and it moves the camera target point, which then further moves the cursors poition in 3d space, and so on
so put a variable for the position that doesnt change unless you cancel out them aim
would that prevent you from adjusting your aim without letting go then aiming again?
so I added OtherPlayer.cs but it still got no function option
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Timeline.Actions;
using UnityEngine;
public class OtherPlayer : MonoBehaviour
{
public void up()
{
transform.position += new Vector3(0, 5, 0);
}
void down()
{
transform.position += new Vector3(0, -4, 0);
}
}
you have to drag the one thats on a gameobject
its up to you when it gets updated again
so when you aim you hold say right mouse, then it locks that position, if you move the mouse the camera is still locked on that spot instead of mouse
unless I'm misunderstanding, that would prevent you from moving your aim without letting go of it first, it would be like playing call of duty except you cant move your camera while ADS'd
I'm confused tbh on when you want the camera to stop moving 😅
its also a little confusing since I have a similiar project but ig we have different purposes on aim 😅
its not so much the camera that needs to stop moving, its the cursor
well you can't technically stop the cursor but you can for example stop capturing its movement for your calc
or if your cursor is custom you can just stop running whatever scripts sets its pos
I did think of that, stopping and starting capturing it only while the cursor is actually in motion/input on mouse axis
But since the cursor gets offset by the camera movement, moving the cursor after the offset would just be the same problem
I just read something about making a custom cursor based on the mouse position's delta. That might be the way I have to go
can anyone please help? I want my enemy to lock in on me but it doesnt. I use enemy.transform.LookAt(enemy.Player.transform); to do it and also it lays down. here how it looks like:
Then the camera movement wont move the cursor, only mouse movement will move the cursor. in theory
yeah thanks it works
ohh thought you had that type of cursor already

LOL, there's the miscommunication 😆
I'll give that a shot and see how it turns out
Please ping or dm
well cleary its working
just not the way you expected
ik but how to fix it
you have to fix the pivot
transform.LookAt uses the Forward(blue arrow) of the transform to look at somewhere
make sure you adjust it in Pivot / Local mode not Global
I did it but nothing changed
oh
wait
my guy thats step 1 of fixing pivots
I did center
there are more steps, which still includes you fixing the pivot 😂
how to do it
help i had a player controll but it didnt save and everthing is gone
wsad? idk what that is
done
it just didnt save i hit ctrl s but it didnt save
what didn't save ? I have no idea
show me
the controll for moving
what is "the controll"
script
ah well without version control if you did not hit save , you're shit outta luck then..
i didnt save the script
and thats it
time to learn version control
hey i just wrote my script that checks for a raycast every frame until it hits something with a special tag and ive been wondering if it matters if i check for the input and than the raycast or the raycast and the input at the same time. does it affect performance in a noticable way?
well do you only care about the raycast when a certain input is happening?
you should only run the raycast when it's needed. if you don't need the raycast until input is received, then do it only when you receive that input . . .
if you want prompts then you need Raycastfirst then buttonPress
eg like inspecting an item before text of "press E to interact"
also the cost of a raycast per frame is not much in the grand scheme of things
basicly yes but for a more polished look it would maybe be nice to highlight the object with edge detection
so if you want to popup something up based on it, before input yeah its fine to do that every frame
yeah, they're cheap . . .
i would use the nonalloc version if you can
is it a good idea to cast it every 3rd or 4th frame so you wont notice the short delay but have the advantage of less raycasts maybe?
yo whats that
would not over complicated it
now you need logic to count frames vs just doing it
and the user might notice
think about this in a shooter 90% of weapons are hitscan and some fire very fast and its fine
yeah ok i might just cast the raycast and its good enough haha
it wouldnt cause performance issues but like everyone else said you would only call it when needed (AKA when you press an input)
like generally do not do work that is not required, but if you have a use for something just for for it
better to keep things simple, then over complicate it worrying aobut performance problems that do not exist
or if you want to highlight it on an overlay
I'm trying to fade out the focal length of a depth of field volume. This isn't working though. https://i.imgur.com/7ilhONQ.png
if you do hit perf issues you got the profiler to tell you exactly why
did you actually read the message..
im guessing its asking for a float
Oh, i was assuming it was.
did you read the error?
check the docs
its highlighted red and should tell you
Severity Code Description Project File Line Suppression State
Error (active) CS1503 Argument 1: cannot convert from 'UnityEngine.Rendering.ClampedFloatParameter' to 'float' Assembly-CSharp C:\Users\RATPr\My Game\Assets#My Stuff#Main\Scripts\Main\Mechanics\Autofocus.cs 36
I mean that prior to writing the code, i thought it would be a float.
ohh ClampedFloatParameter, I was off by the Clamped 😛
How would i get a float out of it then? I tried .value, gives same error.
read the docs see what that type provides for you
it seems to have a GetValue method
Oh ok.
Still gives Severity Code Description Project File Line Suppression State
Error (active) CS0029 Cannot implicitly convert type 'float' to 'UnityEngine.Rendering.ClampedFloatParameter' Assembly-CSharp C:\Users\RATPr\My Game\Assets#My Stuff#Main\Scripts\Main\Mechanics\Autofocus.cs 38
did you save
even if it failed for a other reason the error would differ
signature is T GetValue<T>() so if you give it float it will return float
i have the error parameter doesnt exist and it exist help
Yep i saved and it still gives same error..
well no shit
you really dont know why after what we said?
Mathf.MoveTowards returns float
focalLength expects ClampedFloatParameter
what is wrong here?
what are you even saying
talk with words
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
Now you've got the correct parameter for MoveTowards, but you're trying to set the ClampedFloatParameter to a float
Oh wow, i had to add .value to the beginning focallength.
that works too ig thought it was a private set 👍
if I remove a field in a scriptable object, will the data stored in other fields be lost?
remove it from the script how would it exist on the other instances?
wdym sorry?
no removing one field does not effect other fields
I mean like if I have a scriptable object asset, and remove a field from the script, will the data in the other fields be lost
if you remove a field, it will no longer exist for that SO. how can it be stored in other fields?
ohhh like reset
no it wont
only when you change the names of the field it affects that fields data but not others
okay good, I've got these massive objects that I do not want to lose the data for by modifying lol
thank you
that would suck if all serialized data was lost like that
fr 😅
how does unity handle the preservation of that data when you remove and add fields?
ima guess reflection
only touch the entry/field affected or sum
it all goess in the text file / yaml is just like removing any other entry in a organized structure
Okay so now it changes the focal length but not every update, only everytime the "focus" bool is toggled. ``` void Update()
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, maxPickupDistance))
{
if(hit.transform.tag == "Interactible" || hit.transform.tag == "Item" || hit.transform.tag == "Door" || hit.transform.tag == "BigItem" || hit.transform.tag == "Lock" || hit.transform.tag == "Paper" || hit.transform.tag == "Important")
{
Focus = true;
}
else
{
Focus = false;
}
}
else
{
Focus = false;
}
if(Focus == true && DOFSetting.focalLength.value != 0f)
{
DOFSetting.focalLength.value = Mathf.MoveTowards(DOFSetting.focalLength.value , 0f, 10 * Time.deltaTime);
}
if (Focus == false && DOFSetting.focalLength.value != 50f)
{
DOFSetting.focalLength.value = Mathf.MoveTowards(DOFSetting.focalLength.value, 50f, 10 * Time.deltaTime);
}
}```
I'm trying to make it fade to 0 or fade to 50
why isnt it working
did you check what the warning says?
that if statement is scare 😨
i am in the right channel and i added screen shots
huh?
I know, 🤣
the ! ask
thats not what she said
what then?
i don't know what you're trying to do because that wasn't explained, but i'm talking about the warning message from your console screenshot . . .
i am in code begginer
click on it
oo
you it doesnt exist but it does
huh? just click on the link
i thought you where saying about this
start by simplifying it , an interface or a component for "Focusable" that you only look for this
im flabbergasted
should i start from the begining
no one said anything about this except for you . . .
i had a error
but the error say si dont have is walking
but i have
and i have this also
we don't know if you do (have an isWalking parameter). you have to show us that it is really there . . .
show us the entire script !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 clear the console and run the game, does the warning still appear?
YES
this is the code
are you actually getting the correct animator?
as dec_vew mentioned, is the correct animator referenced?
yea i checked
Do you notice anything wrong with the script that would cause my issue?
is isWalking set in a animator transition
Yes
show us that transition
I can't the power went of or something
whats happeneoing now
It doesnt Movetowards the end float, every frame.
It only moves when the bool is changed.
!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.
!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.
which one you have 2
code looks good other than the nesting
im a bit stumped here
I follow a lot of turtorials
how do you round a float to 3 sf ive tried mathf.round but its not working
Both lines dont move every frame. ```
if(Focus == true && DOFSetting.focalLength.value != 0f)
{
DOFSetting.focalLength.value = Mathf.MoveTowards(DOFSetting.focalLength.value , 0f, 10 * Time.deltaTime);
}
if (Focus == false && DOFSetting.focalLength.value != 50f)
{
DOFSetting.focalLength.value = Mathf.MoveTowards(DOFSetting.focalLength.value, 50f, 10 * Time.deltaTime);
}```
Anyone know why my PlayerDash() is not firing when I press the associated button?
{
// Inspector Variables
[SerializeField] private TrailRenderer myTrailRenderer;
// Operational Variables
private bool isDashing = false;
private float coreMoveSpeed;
private float dashSpeed;
private float dashCDTimer;
private float dashDuration;
// Scripts
private PlayerController playerController;
private PlayerControls playerControls;
private void Awake() {
playerControls = new PlayerControls();
}
void Start()
{
playerController = GetComponent<PlayerController>();
coreMoveSpeed = GetComponent<BaseStats>().GetStat(Attributes.MoveSpeed);
dashSpeed = GetComponent<BaseStats>().GetStat(Attributes.DashSpeed);
dashDuration = GetComponent<BaseStats>().GetStat(Attributes.DashDuration);
dashCDTimer = GetComponent<BaseStats>().GetStat(Attributes.DashCDTimer);
playerControls.Movement.Dash.performed += _ => PlayerDash();
}
private void Update() {
if(playerControls.Movement.Dash.triggered){PlayerDash();}
}
private void OnEnable() {
playerControls.Enable();
}
private void OnDisable() {
playerControls.Disable();
}
private void PlayerDash() {
Debug.Log("Dash fired");
if(!isDashing && Stamina.Instance.CurrentStamina > 0) {
Stamina.Instance.UseStamina();
isDashing = true;
playerController.moveSpeed *= dashSpeed;
myTrailRenderer.emitting = true;
StartCoroutine(EndDashRoutine());
}
}
private IEnumerator EndDashRoutine() {
yield return new WaitForSeconds(dashDuration);
playerController.moveSpeed = coreMoveSpeed;
myTrailRenderer.emitting = false;
yield return new WaitForSeconds(dashCDTimer);
isDashing = false;
}
}```
where do you assign the PlayerDash to input
how doesnt it work? math.round just rounds your float to the closest int
oh i see in Update, thats kinda hidden
yeah thats the problem cause the floats im tryna round are all under 1
if you want to snap the float to the nearest thousands digit (which is what i assume you meant with "to 3 sf", use the Snapping.Snap method
did you setup the button properly from the input manager?
ive never heard of that function ill look it up and try it now
I believe so.
I did the same procedure with all my combat buttons and they all work.
wait so what would i put as the 2nd parameter snap
literally was just on that lol
read the docs and take a guess at what it should be
literally dont know it says rounds value to closest multiple of snap so does that mean if i put 0.1 it will round to 0.1, 0.2, 0.3
yes
snap The increment to round to.
hello guys i am using videoplayer, but how do i check if the video has finished? thanks
i have tried looking in the docs but i still dont get it
i have been stuck for 30 mins
it didnt work im still getting floats that are 6 decimals long
Snapping.Snap(CDP.HPS, 0.01f);
CDP.HPSDisplay.text = "(HPS: " + CDP.HPS.ToString() + ")";```
thats the code im using
CDP.HPS = Snapping.Snap(CDP.HPS, 0.01f);
so shod be this?
use the isPlaying with combination of clip time and current time
nvm you can just use this event
https://docs.unity3d.com/560/Documentation/ScriptReference/Video.VideoPlayer-loopPointReached.html
this may also help you
https://discussions.unity.com/t/how-to-know-video-player-is-finished-playing-video/671347/2
btw, if the intention was just to round it for display, then you should have said that because ToString takes a formatter parameter and F2 would have been sufficient for that
thanks thats useful but im also using the value for incremiting stuff aswell
ahh yes i came across this before but im not sure how to implement into my code
like what variables should i change and so and so
you just subscribe to the event
look at the third post and implement that
its just a void
which you invokerepeated
literaly just
[SerializeField] VideoPlayer videoplayer;
void OnEnable()
{
videoplayer.loopPointReached += Videoplayer_loopPointReached;
}
private void Videoplayer_loopPointReached(VideoPlayer source)
{
//do somehting
}
exposes it in the inspector so it can assigned there
shows private variables in inspector
btw when subscribing to event is good measure to unsubscribe, dont forget to clean up by doing the opposite in the OnDisable or OnDestroy method
eg cs void OnDisable() { videoplayer.loopPointReached -= Videoplayer_loopPointReached; }
weird. do you have any other scripts with access to PlayerControls? if so, check for dash input there . . .
I did get it to work
Well, at least my debug log is recording lol.
Now to get it to actually adjust my move speed from my primary movement script (:
oh, nice. what was the solution?
well, that's a start . . .
I'm not entirely sure lol.
I changed:
playerControls.Movement.Dash.performed += _ => PlayerDash();
to:
playerControls.Movement.Dash.started += _ => PlayerDash();
But I also did a few other things.
This was in the Start()^
Removed the stamina references and now it 100% works!
Now just to bring back in the stamina control and tweak the duration / speed.
It's a kind of cool system to use if anyone wants to have different dashes for different character classes.
Feel free to ask if anyone wants more details (:
good. i would move the subscription += to OnEnable so you can unsubscribe -= in OnDisable. it ensures you're removing the listener from the event to avoid memory leaks . . .
Hello!
I started learning Unity and i want to ask a few questions regarding scripting.
I learned how to disable a script from another script (using a toggle event for on/off)
I have a Circle prefab that i spawn on the screen multiple times whenever i click a button. The circle prefab has a script attached to it that makes the circle moving in random direction. While in edit mode i can see in hierarchy tab that a clone of the prefab is created each time. Because each of the circles move in a different direction, my understanding is that the script is also cloned? I want to make a button to stop all moving circles at the same time. Here are my questions:
- Can i disable/enable the Circle prefab script for all clones at once or do i have to loop through all of them and disable each one individually?
- When disabling a script and then enabling it again, does the Start() function execute again?
- In a scene with multiple scripts each with their own Update() function, does Unity use any multithreading for running all the Update() functions? I read something about the order in which those are run -> does it imply that all Update() functions are ran sequentially single threaded?
Like this:
//playerControls.Enable();
playerControls.Movement.Dash.started += _ => PlayerDash();
}
private void OnDisable() {
//playerControls.Disable();
playerControls.Movement.Dash.started -= _ => PlayerDash();
}```
I still don't fully understand OnEnable/Disable. Do you have any documentation by chance?
almost, you can't unsubscribe from an anonymous method. it has to be cs playerControls.Movement.Dash.started += PlayerDash;
if this gives an error, it's bcuz you need to add the parameter (even if you don't use it, that's fine) . . .
- loop though all of them yes but disabling parent gameobject disables all child gameobjects scripts from running though (unless they have something else referencing the script and running a function)
- no it does not, only OnEnable and OnDisable do for example
- unity runs single-threaded until you use jobs so all Updates are ran sequentially also no guarntee which script runs first the specific event,
hi my capsule character clip through the wall its acting like there is no collision how to fix that?
how should we know we havent even seen the script / setup?
give us more details, are you using a RB or CC? , how are you moving it?
I get the error "No overload for 'PlayerDash' matches delegate 'Action<InputAction.CallbackContext>"
You mentioned adding the parameter. Do I add this parameter in the Input Action Map or somewhere else?
player is using this script
in the method you sub Action to, is expecting a CallbackContext as parameter in the function
show video of what is happening
also the inspector for this gameobject
Thanks for the clarifications!
- My parent object isn't in the scene since i didn't want it to render at start. The prefab is only in the assets not in the Scene. What do i do in this case?
- How can i use Jobs to tel Unity about running Update() functions in parallel? Aren't jobs used inside another function like Update()? (didn't read that much on jobs yet)
also !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.
what are you trying to accomplish here with jobs?
main useful only if you're doing long and complex calculations
I don't know what a "CallbackContext" is.
Is there something I can read to understand this better?
its a struct that unity uses to pass around Input info https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/api/UnityEngine.InputSystem.InputAction.CallbackContext.html
The Jobs question was more of a general question. for now i'm not trying to accomplish anything with it. Although i want to see how my performance is improved when i have hundreds of circles in the screen
yes. finding nearest neighbour for all circles
ig it depends how many you have sure and how long. Or if there are no altenatives
solving issues by tossing multicore at them isn't always the solution
lot of people still have cpus that perform better on single core
ig. i was trying to learn both unity and algos at the same time. hence the togles with scritps enable/disable for different algos or single/multiple threaded and see the difference in real time
-
Yes: PART 1: by using events, each circle instance can subscribe to an event. when that event is called, all circles will execute the method subscribed to the event (disabling them).
PART 2: you can add each instantiated circle to a list, then loop and disable the script on each circle -
No:
Startis only called once during the lifetime of a GameObject, however,OnEnableis called every time the script is enabled (or the GameObject becomes active). -
By default, Unity is single-threaded. you can setup a system where an UpdateManager with a list iterates runs an
OnUpdatemethod on each component (in the list), or an event that other scripts subscribe their customOnUpdatemethod to that runs when the event is invoked . . .
do you create and destory or just create the circles ?
both
look into pooling
probably would do that first before jumping straight into multi-thread / jobs esp in the beginning
Well, I read that page. My understanding of it has increased 2% lol
I need a tutorial on how to read these Unity Docs I guess lol
its just a type its expecting in the method that was giving you error line
you dont have to exactly understand the details on how it works
just passes specfic data "grouped up" the way its expected
public event Action MyAction;
public event Action<int> MyActionWithInt;
void Foo()
{
MyAction += Bar;
MyActionWithInt += Bar; // gives error because bar is missing expected int in signature
// void Bar (int theValue) {}
}
void Bar()
{
}```
when you receive input CallbackContext has all the data about the input, that's all. you can access a bunch of fields or properties holding input data. for certain input, like a button, you don't always need that data but its passed (given to you) regardless . . .
you just add it to the method . . .cs private void PlayerDash(InputAction.CallbackContext ctx) {}
Alright so im getting a null reference exception when trying to use OnDisable() and I think im tracing it back to this.enabled not existing
but it does exist
cant be this
!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.
show the exact error (like the line number + script name)
Ok. So buttons are inputs. When an input is passed into Unity, it has a group of data associated with it termed a 'Callback'.
What is "ctx"? Some sort of 'ignore' command?
the error is not in visual studio, but only happens when I run the scripts in game
OnDisable is automatically called on a MonoBehaviour when it is disabled . . .
because its a runtime error
ctx is the name of the variable
what is on Line 10 in ghostchase.cs
It is a variable of type InputAction.CallbackContext named ctx
whats ghost and scatter
ghostchase is a subclass of ghostbehaviour
Either ghost or ghost.scatter is null
which contains the Enable method
Ah, ctx = "CallbackContext"
Or just "Context"?
or just Context
private void PlayerDash(InputAction.CallbackContext chungasAmogus) is an identical method declaration and exactly as valid
that's just the name of the parameter. cs private void OnTriggerEnter(Collider collider) {}
collider is the variable name of the parameter. you use this variable within the method to access the collider of the collided GameObject. ctx is the same thing . . .
doesnt seem like it
everything checks out when I look it over
So this code is then going to have the Callback Context essentially be blank because nothing is surround the curly brackets: IE {}
how did you check?
usually, i name it context but i just abbreviated it to ctx for easier writing when responding . . .
"Seem" isn't proof. How did you check
how should I check
debug logs where
in the place you want to check the value
no, the CallbackContext parameter variable will have information. i just showed you how to correctly write the method signature to fix the error. you do not have to use the parameter variable within the method if you don't need its data. what you put in the method is what you need when the player dashes . . .
https://gdl.space/ipekejutag.cs
ive followed this movement script from a tutorial but im running into an issue where simple bumps or dips like in the photo means the player can't walk up them
void OnEnable(){
Debug.Log($"{name} is ghost here? {ghost} is ghost scatter here ? {ghost.scatter} ", this);
//etc
scatter was null but I'm not sure what to do with that information
Make it not be null
Or stop trying to use it if it's null
Then find out why it is and fix it
show where it assigned
oh my
Does the object with the Ghost component on it have a GhostScatter component on it as well when it's created?
and if you do check if this function running at all
yes
the function does run
Show the inspector for it
just like you were sure the other things were assigned?
private void PlayerDash(InputAction.CallbackContext ctx) {...}
When I added InputAction.CallbackContext ctx it broke all uses of
playerControls.Movement.Dash.started -= _ => PlayerDash();
I tried dropping _ => as well and added using UnityEngine.InputSystem; to the top of the file.
Thoughts?
not sure what you are asking but I used debug.log to check and it runs
ill check and see if everything gets assigned
Did you log the value of scatter in Awake?
dont use a lambda just directly sub the function
i mentioned you have to change how you (un)subscribe to it: <#💻┃code-beginner message>
playerControls.Movement.Dash.started += PlayerDash
PlayerDash now takes a parameter. _ => PlayerDash() is an anonymous function that takes a parameter, discards it, and calls PlayerDash with no parameters
That is no longer valid
Ahhh, silly lambda. What's it doing there??? 😉
also your -= to unsub before was not even working, since both times you are adding and removing functions you just created in that place
not the one you actaully defined permanently
yes it is assigned correctly
as mentioned earlier, you need to use a method in order to sub and unsub correctly because an anonymous delegate (using a lambda =>) creates a method on-the-spot and therefore cannot be referenced to use later to unsubscribe . . .
Then one of these situations is happening:
- You're checking it in
OnEnablebefore awake runs - The object with
scatterset is not the same as the object you're checking inOnEnable - Something is setting
scatterto null between awake andOnEnable

