#💻┃code-beginner
1 messages · Page 719 of 1
maybe you can just implement an interface
if(other.TryGetComponent(out ISomethingCoroutine routine))
routine.DoStuff()
also you don't need to StartCoroutine directly, you can just use a method inside that class (probably interface) that runs coroutine
or maybe I'm doing this whole thing wrong, I have something like this ```EffectObject effect = null;
switch (effectType)
{
case EffectType.Burn:
effect = new BurnEffect();
break;
}```
but then I can't start the coroutine on effect
ohh are these not MBs
yeah
the EffectObjects are not MB, that's why I have to start the coroutine from outside
subtle + solid
ya that kinda complicates this whole thing lol also does it need to be a coroutine ?
it has to deal x damage every y seconds, I used InvokeRepeating before but then people here told me to change it to coroutines
true true..could potentially switch it to an Awaitable / Task async, thats easier to store probably
I mean Coroutines can be stored in Coroutine type , just need a way to Return that
My problem is that my interactor detects objects taking in account the layer "Interactable" but my Enemy AI detects de player throwing a Raycast and detecting if it is in layer "Occlusion" but what if I have an object that is Interactable and should have occlusion (Door)??
imo - you could just have the coroutine on the thing being damaged, just have the effect supply the info for the coroutine
ya was also thinking something like this ^
well you can't have two Layers thats for sure, you'd have to possibly break it down into components or something
insert?
might be abbreviated to "ins"
ohh thank you!!!
further reading on what it actually does, if you're interested
https://en.wikipedia.org/wiki/Insert_key
thanks i had the "overtype" setting on
https://paste.ofcode.org/ExwDaR5nhcmV89PCdsf8Ug
I have been attempting to lock my ship turrerts from rotating towards the superstructure of the ship. I thought I had it working great, but apparently I am working relative to world space. Can anyone suggest how I might easily convert this code to be relative to the local space of the turrets?
yawPivot.eulerAngles -> yawPivot.localEulerAngles
yawPivot.rotation -> yawPivot.localRotation
but again - you should not rely on eulerAngles to be consistent
save the state yourself
// Get current yaw angle
float currentYaw = yawPivot.eulerAngles.y;
this is not necessarily the value you set last frame
the canonical representation of a rotation is the quaternion
when you assign to eulerAngles, that's converted into a quaternion before actually being assigned as the actual rotation
when you retreive eulerAngles, that's converted from the actual rotation quaternion
that process is lossy - converting eulerAngles to a quaternion and back again won't necessarily give the same eulerAngles
Because, there is more than one way to represent any given rotation using Euler angles, the values you read back out may be quite different from the values you assigned. This can cause confusion if you are trying to gradually increment the values to produce animation.
To avoid these kinds of problems, the recommended way to work with rotations is to avoid relying on consistent results when reading .eulerAngles particularly when attempting to gradually increment a rotation to produce animation. For better ways to achieve this, see the Quaternion * operator.
right
i understand the issue with euler angles
about order mattering and usch
gimbal lock
etc
so the conversion process doesnt always result in the same ordering?
why else would it be a different rotation
the conversion doesn't result in the same values
it won't
it'll be the same rotation
but it might be represented differently
so the values you're doing math on will be inconsistent
so should convert back to quaternion before applying?
okay
this is the part with the issue
you should store the currentYaw yourself, instead of extracting it from the quaternion each time
okay, and eulerAngles/localEulerAngles is the function that is extracting it from the quaternion
(or turning it into a quaternion, depending on if you're getting or setting)
can you give me a sample of what storing it myself might look like?
make a field
add/minus the field value
for example, if you were just yawing 90° per second, you might have something like this (analogous to your code, the bad version)
float speed = 90;
void Update() {
float currentYaw = transform.eulerAngles.y;
currentYaw += speed * Time.deltaTime;
transform.eulerAngles = new Vector3(0, currentYaw, 0);
}
```you should instead have something like this:
```cs
float speed = 90;
float currentYaw;
void Start() {
currentYaw = transform.eulerAngles.y;
}
void Update() {
currentYaw += speed * Time.deltaTime;
transform.eulerAngles = new Vector3(0, currentYaw, 0);
}
in the assignment line, it could also be transform.rotation = Quaternion.Euler(0, currentYaw, 0);, im pretty sure that's completely equivalent?
okay so it is better to do just get currentYaw at the start of the script instead of every frame
actually, I think this doesn't work because there can be multiple coroutines in parallel, and because I need to keep a reference to each
i don't see how that's an issue
lists are a thing
just to give it the currenting starting value, from there you modify it directly and assign it to the rotation.
or a dict, for mapping the effect enum to the coroutine
better than what...?
because currently as my ship rotates the disallowed angles rotate relative to the ship and it gets silly
yes but if I have the coroutine logic in the DamageController instead of in the EffectObject, then I can only start and stop that one coroutine
im confused what you're asking here
oh, localEulerAngles vs eulerAngles?
localEulerAngles will give you the value relative to parent
to keep it relative to local space
yeah, everything about eulerAngles vs rotation also applies to localEulerAngles vs localRotation
i just used the former for simplicity
so that the turrets can still be prvented from facing the superstructure as the ship rotates
sur sure
sorry if i am being obtuse
just trying to be explicit
yeah that's fine
but each effect is supposed to start its own coroutine
'Cannot Apply attribute class 'RpcAttribute' because it is abstract. Does that mean I have to implement it in the code? Why the tutorial giving me so many errors
an issue that would probably be solved by this #💻┃code-beginner message
I don't understand how that's supposed to work here
you can start as many coroutines as you want in a class, there is no issue
to track them
the entire point of coroutines is concurrency
what is the actual issue you think you have
but how, I have to define the coroutine and then I can use that one coroutine I defined
how do I add coroutines on demand
you might be confusing coroutines vs the methods that create them
by.. starting them
var coroutine = StartCoroutine(MyRoutine()) // hi I'm a new coroutine
wait, so if I do StartCoroutine(TakePeriodicDamage(damage, effectFrequency); multiple times, each one will start a new coroutine?
yes
ah ok
that's the entire point of StartCoroutine
https://paste.ofcode.org/366JjrK6yaLjNS5f6xeju2K so th is is what i am working with now
I thought it would restart the same one
what has invoke taught you man 😭
if you ever worked with Tasks async, its similiar concept
you aren't updating currentYaw here
also you already have this code for getting the "initial rotation"
// Store the initial rotation when the turret is first initialized
if (!initialRotationSet)
{
initialYawRotation = yawPivot.localEulerAngles.y;
initialRotationSet = true;
}
you should have the initial setting for the currentYaw here as well, or have them both in Start
just for convenience/ease of maintenance
oh shit
i didnt notice that shouldnt be there
that is called iniside an Initialize() function i have in the controller too
which is called from outside the controller when the object gets instantiated
public void Initialize(ShipData.TurretMount mountData)
{
mountName = mountData.mountName;
section = mountData.turretMountSection;
minRotation = mountData.minRotation;
maxRotation = mountData.maxRotation;
SetupPivots();
// Set initial rotation reference
if (yawPivot != null)
{
initialYawRotation = yawPivot.eulerAngles.y;
initialRotationSet = true;
}
// Auto-assign gun barrels and muzzle transforms
FindGunBarrels();
FindMuzzles();
// Initialize barrel recoil components on muzzle transforms
InitializeBarrelRecoil();
}
you could probably have the currentYaw set here as well
sure could
How do I implement RpcAttribute the unity networking tutorial doesn't cover this part
perhaps ask #1390346492019212368?
I store the ongoing effects in a list of EffectObjects, what's the smartest way to store the coroutines together with them or linked with them in some way?
since the coroutines need to stop when the corresponding effect ends
Dictionary <EffectObject, Coroutine>
good idea, thanks
why not have this be done within each EffectObject instance?
though I think I already said this like 3 times so
that's what I tried but then I couldn't find a way to start the coroutines
you actually only need a monobehaviour to "start" it
so you could pass a reference to your EffectObject at somepoint for it to use
e.g. your player component
the different effects like BurnEffect, SlowEffect, etc all inherit from the EffectObject, and some contain coroutines. And when I try to check effect.EffectCoroutine, where effect is an EffectObject, it says EffectObject does not contain a definition for the coroutine
so my current approach is to define the coroutine in the MB and make the EffectObject supply the parameters for it
I suggested earlier you can use a Interface to check if the Effect has implemented a Coroutine
okay let me write a quick example to demo how this can be done
shouldn't this work ?
public interface IEffectCoroutine{
IEnumerator EffectCoroutine();
}
public class BurnEffect : EffectObject, IEffectCoroutine{
public IEnumerator EffectCoroutine(){
yield return new WaitForSeconds(2f);
Debug.Log("Burn damage tick!");
}
}
if (effect is ICoroutineEffect coroutineEffect)
StartCoroutine(coroutineEffect.EffectCoroutine());```
public class EffectObject
{
public void StartEffect(MonoBehaviour mono)
{
var coroutine = mono.StartCoroutine(DoEffect());
}
public IEnumerator DoEffect()
{
yield return new WaitForSeconds(1f);
//do shit
}
}
public class Player : MonoBehaviour
{
private EffectObject effectObject = new();
public void Start()
{
//Can do it this way
StartCoroutine(effectObject.DoEffect());
//Or like this
effectObject.StartEffect(this);
}
}
Yea all you need is to have a monobehaviour to start the coroutine. my example shows 2 ways to do this.
@silver fern
I see, thanks
let me try that
seems to be working, even though it's complaining that the assignment of the coroutine variable is not necessary
var coroutine is local, it doesnt do anything outside of StartEffect
if you had a field you could assign it to that, otherwise there is no use for it
now I can just destroy the EffectObject to stop the coroutine?
or do I still have to make the dictionary
remember the Coroutine is running on the MonoBehaviour, Player in this example
btw you can probably return the Coroutine directly
public Coroutine StartEffect(MonoBehaviour mono)
{
return mono.StartCoroutine(DoEffect());
}
if you want to keep track of them, you need store them
I thought I just start it since I'm passing in the MB from the player anyway
{
mono.StartCoroutine(DealDamage());
}```
actually, should I make this override a virtual function in the EffectObject or better not
I suppose I don't have to check if it exists if there's an empty virtual function
if you want, personally I think the Interface is cleaner
especially if you mentioned certain derived classes wont even need Coroutine
if you use the version where we start the coroutine within EffectObject then you can store the returned coroutine and stop it via that...
I presumed you would understand this by now my bad
The point of this was to demonstrate to you how you can handle this within each instance nicely 😐
You can combine the two examples shown..
#💻┃code-beginner message
my example here is how you can check a derived effect even has a coroutine to run so you dont even need to clutter the parent class if not all derived have coroutine
yeah my thinking was I don't have to check at all if there's an empty placeholder
I can just run it and if its empty nothing happens
sure if you wanna do it that way.. its your design at the end of the day, you're the one who's going to be working on it, use what's comfortable, preference at this point.
If you come back to the code in a few months it has to make sense to you not us
well apparently I can't have a virtual coroutine method so my idea doesn't work anyway
you can?
it says not all code paths return a value
would that doc still work today in Unity 6 ?
public virtual Coroutine EffectCoroutine(MonoBehaviour mono) {}
you need yield return null; inside the virtual one
ah
@rich adder @naive pawn this is my new and updated version, hopefully this appears to be better according to your advice and instructions
note that if you want it to be a coroutine it must return IEnumerator not Coroutine. Coroutine is the object returned by the StartCoroutine method
it does ``` public override Coroutine EffectCoroutine(MonoBehaviour mono)
{
return mono.StartCoroutine(DealDamage());
}
Seems pointless to do this tbh
why?
but also yield return null as nav suggested would not be the proper fix for that, you'd want to either make the method abstract (assuming the containing class is also abstract) or return default in the base virtual method (if the base doesn't actually do anything)
but that's the example you gave me, and I'm returning it so I can store it like you said
let me do another example so you understand what I meant
public class EffectObject
{
private Coroutine coroutine;
private MonoBehaviour coroutineMono;
public void StartEffect(MonoBehaviour mono)
{
coroutineMono = mono;
coroutine = mono.StartCoroutine(DoEffect());
}
public void StopEffect()
{
if (coroutineMono != null && coroutine != null)
{
coroutineMono.StopCoroutine(coroutine);
coroutine = null;
coroutineMono = null;
}
}
public IEnumerator DoEffect()
{
yield return new WaitForSeconds(1f);
//do shit
}
}
Is it working ?
I have a basic movement script for a rigidbody but it's really frictionless and not snappy. I've tried to just directly set the velocity but that ends up interferring with dashing and I've also messed around with the drag but that makes the gravity act really weird. Is there anyway to make this stop sliding as much?
Vector3 velocity = (transform.forward * Input.GetAxis("Vertical") + transform.right * Input.GetAxis("Horizontal")).normalized;
rb.AddForce(velocity * speed, ForceMode.Force);
that's even better, thanks
how was velocity interfering with dash ?
Do you see now how we handle these references within each instance, making things easier?
yeah, that's what I actually wanted when I started on it today but then I got lost lol
as you get more knowledge and experience with OO programming it will be easier to design things better
The Dash works by adding force but it's instantly overwritten when the movement velocity is set
Vector3 velocity = (transform.forward * Input.GetAxis("Vertical") + transform.right * Input.GetAxis("Horizontal")).normalized;
rb.velocity = new Vector3(velocity.x * speed, rb.velocity.y, velocity.z * speed);
//Dash
if (Input.GetKey(KeyCode.LeftShift)&&!dashCooldown)
{
StartCoroutine(Dash());
}
}
IEnumerator Dash()
{
dashCooldown = true;
rb.AddForce(transform.forward * speed, ForceMode.Impulse);
yield return new WaitForSeconds(2);
dashCooldown = false;
}
learn something new every day as they say
yes AddForce gets overridden but you can just add to the velocity no?
I want the dash to be a short burst so if i did that it'd just change the speed of the character which isnt my intent
you can even mix in an AnimationCurve to add the extra speed and fade it down or up
no need to change the original, add the burst to it
You could probably just modify some offset that you would add to velocity after computing movement.
You'd need to have that offset gradually decrease to have a burst effect though
@rich adder nope, it d oesnt. took me amionute to get on and test. but now its all rotating about the Z axis, not the Y
sso the turrets are rollign over on their sides intstead of rotating lol
Well im going to add a mechanic where you can use a shotgun to launch yourself which i feel like would be a pain to do with the rb.velocity setup. Is there anyway i could just use the addForce way without the player being so frictionless?
put material with more friction on the player collider 🤷♂️
I could take a look when i'm back, but what values is the inspector changing for it anyway?
@slender quiver Okay just got back and was able to take better look at code, aside from those very sketchy limits that you need to change asap, everything else should rotate as expected on Y..
yea they were set as a test awhile back, but min/maxRotation are always set so the hardcoded fallbacks dont ge tused
== is pointless on floats anyway
you're never going to get exact values unless you explicitly write them
even for a null check?
no ? don't see how null is relevant here
the reason you don't for floats is they are not precise, and have "float point inaccuracy"
the c# docs also mention this issue with float comparison https://learn.microsoft.com/en-us/dotnet/api/system.single.equals?view=net-9.0
Oh nice they also mention solution
Unity has this implemented similiar with Mathf.Approximately() https://docs.unity3d.com/ScriptReference/Mathf.Approximately.html
but you can ofc make your own
or < >
yea c# docs are amazing they often have extra remarks and things
ya glad to see that microsft finally puts those, i recall the old school docs were more robotic. maybe I remember wrong from msdn
@rich adder aye i am aware - am i checking for quality against a float that isnt a null check?
i dont see it
@rich adder Ive also used Mathf.Approximately()
at times
idk what you mean there tbh.. null to me has anything to do with Reference types
(unless you count nullable valuetypes)
if (yawPivot == null)
{
Debug.Log($"yawPivot is null!");
return;
}
well yawpivot is a transform
sorry
yes thats a reference type
i still dont see whre i am checking == on a float
by default value types are never null
yee
oh yes myb I better looked at the code you had!= which is fine there, but I meant in general just incase
!= 0 is okay but even doing it on anything else, it would probably always be true
the rest of the limit thing just seems odd
i changed it to 320f and 40f anyways
but idk why they are rotating about the Z axis now
instead of about t he Y
did you look at the inspector is that really whats happening ?
i watched it happening
I just tested your code for shits and gigs, aside from limits (i commented those out)
it works fine
ill double check
@slender quiver
this might be a hierarchy / model issue
you'd have to show the heirarchy / pivots n all that jaz
it was working before
before what?
YawPivot here says its rotating on Y
you have something else not properly rotated then
hmm it must be different axis in local space
wdym ? the inspector is LocalSpace
for that reason
no my words are just poor
i meant that the axes arent corresponding to each other due to a rotation issue or something
maybe show the scene view with gizmo on show arrows, see if the child turret matches the pivot of YawPivot
or if YawPivot makes sense on the parent
also make sure you're in Local /Pivot mode not Global
ah
no shit now it makes sense why its tilting lol
yep
i guess before you were rotating "wrong" on z and now that its accurate you can adjust it properly
I wrote a custom wheel collider with pakejka tire friction. Am still pretty new to unity and c# could someone give my code a look and tell me if you spot any no no's
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
just skimming through, not gonna look deep into the algorithm itself and i doubt anyone would
the main thing id point out here is your magic numbers. theres a ton of numbers here which look like you'd want to configure them in editor but are just defined purely in a function. they dont have an explanation or variable describing why that number is used. Im not too familiar with the algorithm you're using, so if those are supposed to be static coefficients in the algorithm then its fine for them to not be configured in editor
the variable names like B_lat also clash with the convention you're using in other names. id suggest just finding a way to name it with camel case still
I would split up more of the logic if you want to improve readability. for example look at line 238, it calls MapRangeClamped inside a Mathf.Lerp so the line gets pretty long and this can usually make logic harder to follow
Awesome I will give those a tweak now. As for the "magic numbers" thats kinda just the way the algorithm works. Its called the magic formula and the numbers just kinda work for "realistic" tire friction. I really appreciate the advice!
just curious, are you making this for any specific reason? there is a wheel collider but its not something i used
it seems to fit for most people
man shits so wonky with my turretsn now
Unity wheel collider is great for simple vehicle physics but its just not very good for anything "Realistic" it wouldnt handle making cars like in gta etc. It is a watered down version of the physx wheel collider. Which isn't very good in itself.
The wheel collider I posted it good for making games that are a simcade level of car physics(think forza and gran turismo)
we can't possibly know / help with this statement alone what issue might be...
its all visuals, thats an easy fix
hey, does someone know what would be the best pathfinding solution without a grid in 2d?
pathfinding would imply you have a grid or graph. otherwise what information do you expect to use for solving what a valid path is?
you could go with using physics casts to determine if you can get around obstacles, but this isn't pathfinding and won't be usable for calculating an entire path
oh ok ty how do modern day games often in 3d space to implement monsters move to the player?
hey. i'm struggling with c# in unity, can someone help me? i need a help with my school project thanks in advance 💞
that depends on the game lol
some games stil use A* / Navmesh and some use a bunch of sensors
theres tons of games and not one set way to do it. navmesh exists in 3d, so thatll be a common approach for indie devs at least
okay thank you
!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 #🌱┃start-here
particularly the last bulletin point
i dont understand that, i have specific request of help
What kind of help?
what dont you get?
❔ And don't ask to ask, ask a full question illustrating with screenshots if needed.
Normally folks would describe what they're needing help with in specific and show the necessary details.
"can someone help me" isnt useful to anyone. we already know you need help, thats why you're here
If you're just looking for someone to collaborate or tutor you, you can try asking on the forums but tbh you'll probably not get the help you're wanting within the specific time limit etc !collab
I need some help with my school final project. I need to create a Visual Novel with C#, but I need some help with this
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
again, what kind of help are we talking here?
if you mean someone to write the code for you then this isn't the place, if you mean how to approach a problem with code or fixing existing issues then sure.
"ask a full question illustrating with screenshots if needed."
I have never created a VN with C# before. I have used Python, but I can't say I've listened to many C# lessons. So, I'm talking about good support. At the very least, I want to create a prototype
then do it. nothing is stopping you
"good support" is still vague lol
you can come here any time with question, that is considered support
if you are looking for project collaborators then you need to make a post on !collab 👇
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
okay
no need to be rude btw
I'm just being blunt, sorry if that comes off as rude
I don't think anyone has been rude though 
its !learn ing time
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
im show you how you ask for help in a programming discord since you seem to be oblivious to what they're saying.
Hey guys I made a custom wheel collider it works great and I am also simulating an engine. The engine has a torque curve(ie it produces different torque depending ont he RPM of the engine. That number is then multiplied by the current gears gear ratio in the gearbox script. It works great however the only way I can seem to get it work on hills is by amping up the gear ratio of first gear but then when I am back on flat ground it produces too much acceleration. Is this a problem with my curve you think?
The options I am thinking is maybe more torque at low rpms but idk
Could probably have another curve that would scale the value relative to the normal of the surface or something.
I like this idea
I haven't even been on the server for five minutes, what were you expecting?
think in terms of the real world.
You need to go to lower gears to climb up hills and for down hills you need higher gears
just learn from document tutorial just keep moving if you struggle wee are hear to help you
Yes but the gear ration in the transmission is always the same and I am struggling to find values of the torque curve and gear ratio that work as expected. either it works great on flat ground and I cannot get moving from a stop if on a hill , but then if I tweak values to fix that I accelerate way to fast from a stand still when on flat ground.
Thanks sami
Just make what you want to make and ask for help when you run into issues is your best bet.
@sour forge btw you should look into something like INK it should similify doing a visual novel since well..it was built for them.
I could be off base here but cant a visual novel be built with timeline?
You could do that too, or even combine the two.. there is no limits / set ways to do it
Ink simplifies mostly the dialogue and reacting to specific choices
oh nice
whys that? the language is irrelevant to the project type
its kinda a low level language for such a high level concept is what I think she means.
c# is way easier than python imo
agreed
c# is not a low level language
i think py is easier
its talking about 100% c#
compared to C and stuff sure but for something as trivial as a VN c# is definitely a little bit overkill
its high level language low is binary bro
I meant in the context of what is being made
C is still high level language
in fact most c languages are
Could probably look into VN templates on the asset store and see how they do theirs or build upon those, if allowed. Language isn't a factor unless you're simply expressing your unfamiliarity with the language.
Actually creating vn could be fun
good idea! thanks a lot
depends how complex you need to make it
float targetX = Random.Range(-transform.position.x - sightRadius, transform.position.x + sightRadius);
float targetY = Random.Range(-transform.position.y - sightRadius, transform.position.y + sightRadius);
Vector2 target = new Vector2(targetX, targetY);
Vector2 direction = (target - new Vector2(transform.position.x, transform.position.y)).normalized;```
does someone know why the magnitude of the vector `direction` isnt 1? i dont really get that
What's the value instead?
bro you need some organizing
depends. i feel like the longer the code runs, the wilder it gets
how would you write it? gave my best to organize it😭
Those would seem to be the position and not the normalized value?
you arent even showing us what line is printing these
my fault wrong screenshot sorry
I'm assuming you're expecting 1 from the normalized direction
bro its normal i have 500 lines not organized its being a real dev
wee dont know what line is printing these
at lest you sent a message that makes sense this time..
Unrelated to the issue, but your target range seems wrong when I look at it
The first param for both X and Y
what do you mean?
I would assume you're looking for a target within sightRadius
You're probably wanting to use positive x and not negative x (relative to position). Same with y etc
would help knowing what original problem they were trying to solve 🤷♂️
Hi people, can someone help me with my code? Watch the video first to see how bad it is.
Have you seen what's wrong with him? He does that thing where he jumps the piece instead of staying still.
ok so i found a solution. I need to make an animation curve that slowly reduces clutch input as the RPMS of the engine increase. this will solve my issue.
how are you moving the object currently?
and tbh I think your issue is the small snap size but that cant really be changed now can it?
are you just doing transform.position = new Vector3(mousePositionTOWolrdPos);
?
With the mouse, the mouse disappears and is replaced with the object and if I press the left button, everything returns to normal.
no i mean show the code you're using to make the object follow the cursor position
this person been here forever and still doesnt post it properly..
I need to see the "movepiece()" method to assist
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
bro look at the code he posted i asked him to show where the objects being moved and he showed me code calling "MovePiece()"
// Enganchar en X
if (Mathf.Abs(newPos.x - col.transform.position.x) <= snapRange)
newPos.x = col.transform.position.x;
// Enganchar en Y (arriba de la pieza)
if (Mathf.Abs(newPos.y - col.transform.position.y) <= snapRange)
newPos.y = col.transform.position.y + other.sizeY;
// Enganchar en Z
if (Mathf.Abs(newPos.z - col.transform.position.z) <= snapRange)
newPos.z = col.transform.position.z;
This is your issue
you need to use one of unities many smoothing methods
Mathf.Lerp may help you here but setting the position like that is going to cause jittery movement like you showed.
In my game I'm drawing shapes using multiple Polygons smooshed together to give the illusion of lines
I want to check what shape the lines form after releasing the mouse, how would I go about that? I tried to think about it but I have no idea how to make that translation
What do you mean by "check what shape they form"?
Can you explain the gameplay mechanic here?
You draw a shape on the screen, based on the drawn shape an action is performed
(Square does action1, circle does action2 etc etc)
ahh yea that'd just be detecting gestures
https://github.com/Oponn-1/Unity-Gesture-Recognizer maybe something like this?
This is precisely what I need
I found a resource a gesture recogniser $1 Unistroke Recogniser which I'm reading too to get a better idea of what I'm doing and maybe tweak a few things
ya theres a couple on the store but most are paid.. i just added github to my search in google
Keep in mind a gesture recognizer is a little different from optical character recognition (OCR)
You might want to look into both and understand the difference
:TIL:
A gesture recognizer might care about how the shape is made (e.g. did you start at the top left and end at the bottom right) whereas OCR only cares about the final shape
ya, i imagine gesture recognition is just a continuous line... press -> release
while u could have a more complex one that takes multiple lines and makes something out of that
i myself have never done either.. sounds like a fun project..
ive tried for the last 3 days and cant figure it out
how do i import a heightmap for terrain. I put the .RAW in where it says import, but it just gives me a slightly elevated, flat terrain. Im choosing places with rivers and places with mountains. For example, this is the Himalayas
Here's an interesting one https://github.com/ZeppelinGames/Glyph-Recognition
ya awesome! ^ i was hunting one for a thumbnail/screenshots
hey guys i was refactoring my input system and i dont know how to solve this issue, let alone what even is the issue
https://unity.huh.how/runtime-exceptions/nullreferenceexception
Assets/Scripts/
GameInput.cs:15
means that line 15 of that script is trying to access or modify something that isn't assigned [correctly]
it'd be like having a public MyScript myScript; and then trying to run myScript.DoSomething(); when I never assigned the variable in the inspector
what do you recommend i should do?
look at that line, see what variables/ references that ur using.. check and make sure they're assigned...
you can use Debug.Log(); to print it out in the Console to make sure they're actually there.. also the website i linked goes over it all..
i can already pretty much guess that its this... is that assigned in the inspector?
yeah i assigned it
well what else is on line 15?
it does look like from the error that somethings going on here... GetMovementVectorNormalized()
sorry im just quite confused what should i do?
!code well for starters show the code thats relevant
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
we can't know exactly whats going on at line 15
wait a minute... in the Awake() function.. are you meaning to create a local variable (underlined in orange)
because you actually never set the one in yellow..
yeah i got it fixed it was quite a silly mistake
wouldnt you assign the yellow in Awake() instead?
like playerInputActions = new PlayerInputActions();
but to be honest im kinda lost as to how this works (the new input system)
yeah thats exactly what i did thanks a lot for helping
I'm creating a 2D action game, but should I separate the character scripts? If so, how should I separate them?(I'm using a translation)
Bump ^
As far as I’ve heard, making code more readable is always better. Organization comes in handy later on for refactoring
I don’t know too much though so I can’t help you past that.
I’ve heard people will even split character movement scripts like sprinting, jumping, and crouching outside of a general movement script so…
Where do you assign the height map what does it look like? How did you create it?
Also, probably not related to coding. #⛰️┃terrain-3d
Thanks for channel
Gotten from some GitHub thing, chose an area of the world map. Rendered it. Converted from png to raw. Imported, flat
All the render sites I’ve tried render as png
I’ve tried like 6
You should share more details and screenshots in the terrain channel.
I will, but as of right now it’s 1 am, didn’t notice the channel at first though, so thanks
I keep having to switch my external editor to vscode and then regenerate csproj files for my external editor's language server then switch back, surely there is an easier way to do this?
Manually reconfiguring the settings every time I make a change that introduces a new symbol is a real pain.
You should only need to configure it once normally.
Check the !ide config guide:
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
One thing that could theoretically cause an issue is if you have used the user installer instead of the system one. It have caused some issues for me in the past.
The only requirement for the ability te generate the csproj files is that the external editor is named code.exe. You could just make a symbolic link to your actual editor. Maybe a shortcut could work too
Yeah outside of this 🙁
Guess I have to make a plugin or something
I just make an empty file named code and set that as my external editor then edit all my code in my IDE separately 🤷
I use the external editor thing to open vim
so I need to have it set to an external editor
Then set it as a symlink or shortcut
eg.
And name the symlink/shortcut to "code"
Or you're on Linux. Yeah just make a symlink named code
Hope It's okay to ask here and if this is even the right place, is there anyone here with experience modding unity games willing to do a simple mod for a commission? please dm if you do or lemme know so I can dm you with the details
I'm on mac, are you saying that all it checks to automatically regenerate metadata is if the file name is code?
Yeah
I'm willing to pay whatever price you choose or think is fitting for what I want and willing to pay in full before the work starts so you can feel safe working on it
I've not had any issues doing that
Though I also don't use the external editor setting for anything really. I just open files through my IDE instead of through Unity
Does it need to be cap'd (Code) or something?
All lowercase
I like being able to do both so far it's kinda handy, v new to unity (more of a general prog background than games).
It should show checkboxes or buttons or someuthing to generate the csproj files when it thinks you're using vscode
only shows that under the specific option for VSCode for me
might be a mac thing (unity seems v odd on mac so far)
Maybe. I know it works on Windows and Linux, might be different on macOS
That would kinda suck though 😢
FWIW it's not that bad to just use Telescope in Neovim to switch files
I use command-T it's faster 🙂
Sure, whatever file switcher 🤷
even then do I still have to press regenerate project files all the time?
I don't think so? I've never had issues with that
Using omnisharp?
But if it insists on using the actual VSCode exe on macOS maybe it's different for the csproj files too
Yup
Hmmph another fun thing to debug, thank you for your help so far 🙂
The price of using a non-slow-editor-strikes-again
Hopefully it works out 😅
It always amazes me how slow VSCode and especially VS are
Though Neovim opens horrendously slowly on Windows so 🤷
Opens fine in WSL on Windows though
So does every piece of software on that platform 😄
The Powershell startup time is abysmal 😭
Even Powershell on Linux opens instantly. It's just Windows
private Int64 nextUpdateTimestamp = 0;
private Int64 GetCurrentTimestamp() => DateTimeOffset.UtcNow.ToUnixTimeSeconds();
private async UniTask Update()
{
if (GetCurrentTimestamp() < nextUpdateTimestamp)
{
await LoadData();
}
}```
i guess this should be fine
shouldnt be too expensive tho
not used to shortform lol
int64_t feels like home
lol
But no performance issues to me here seeing as it's a single check then an await
ok nice
Actually I realise it's a bad design because if the timestamp condition is met it may call LoadData many times
Perhaps a single UniTask.Delay to wait the time instead?
private void Update()
{
if (nextUpdateTimestamp != 0 && GetCurrentTimestamp() > nextUpdateTimestamp)
{
LoadData().Forget();
}
}
public async UniTask LoadData()
{
nextUpdateTimestamp = 0;
Debug.Log("passed");
//server loading action (async)
}```
ya i thought of that too
i dont have dedicated server to sync in game data with backend real time , so i need to find a way to actively check the data if i want to do auto update
but if its like this i think using coroutine should be fine
Change Update() to a function that loops on its own then
private void Awake()
{
StartCoroutine(ConstantValidation());
}
private IEnumerator ConstantValidation()
{
while (true)
{
yield return new WaitForSeconds(1);
if (nextUpdateTimestamp != 0 && GetCurrentTimestamp() > nextUpdateTimestamp)
{
LoadData().Forget();
}
}
}```
when loaddata added .Forget, its just a void function
Why make it a coroutine 😭
public async UniTask Loop()
{
while(this != null)
{
if (nextUpdateTimestamp != 0 && GetCurrentTimestamp() > nextUpdateTimestamp)
{
await LoadData();
}
await UniTask.Yield();
}
}
then call it with Loop().Forget();
this way it will actually wait for data to load and then continue to check each frame
Any idea why I am getting this exception, when the animator is still assigned on the script within the editor.
This is my code for the script:
using Cysharp.Threading.Tasks;
using UnityEngine;
public class AnimationController : MonoBehaviour
{
public Animator animator;
public OptionsMenu optionsMenu;
protected virtual void Awake()
{
animator = GetComponent<Animator>();
if (animator == null )
{
Debug.LogError("No animator attached");
}
GameState.decisionTime += PlayerSpeaking;
GameState.distributeDecision += (choice) => NPCSpeakingCaller(choice);
GameState.verdictTime += PlayerSpeaking;
}
protected void NPCSpeakingCaller(int choice)
{
NPCSpeaking();
}
public virtual void NPCSpeaking()
{
//Debug.Log("NPC Speaking");
animator.ResetTrigger("Player_Speaking");
animator.SetTrigger("NPC_Speaking");
if (optionsMenu.IsPlayerSpeaking())
{
optionsMenu.TogglePlayerPanel();
}
}
public void PlayerSpeaking()
{
animator.ResetTrigger("NPC_Speaking");
animator.SetTrigger("Player_Speaking");
}
protected virtual void OnDisable()
{
GameState.decisionTime -= PlayerSpeaking;
GameState.distributeDecision -= NPCSpeakingCaller;
GameState.verdictTime -= PlayerSpeaking;
}
}
This only happens when I load the next level scene, not when playing the scene individually
Also what the hell does this error mean?
It doesn't affect anything when testing it just appears
Is it not assigned in the editor and the script??
Like this only happens when I transition between level scenes, not when testing the levels individually
you probably have stale event listeners
(choice) => NPCSpeakingCaller(choice)
this one was never unsubscribed
this was a very good call lmao, led straight to looking for stale event listeners
Huh yea it subs a lambda which is not referenced to unsubscribe with later.
The missing ref exception is not a great name
Also you should use OnDestroy instead of disable
Alright thanks, I'll try that, I thought for some reason that I wouldn't need the lambda on unsubscription. Just wanna skip to the write up for this dissertation haha.
Oh ok, thanks for the heads up
How come?
Yea because if it gets disabled and re enabled well your event subs are gone
wdym, it says exactly what it is
Could probably have a better name imo but it's alright I guess
you can't use a lambda on unsubscription either
delegates are ref types
you should use NPCSpeakingCaller to subscribe directly
Even if those events are passing things like integers? I thought that's why I needed the lambda
parameters don't make a difference, no
(if they're being consumed in the same order)
if you wanted to ignore them, you would use a lambda then, but then that wouldn't work for the unsubscription
i thought you'd already figured that out, given the separate NPCSpeakingCaller
Action myLambda = () => DoShit();
Game.event += myLambda;
//...
Game.event -= myLambda;
How to do this properly
you need a ref to the exact "function" you subscribed with
Thats why using a method is easier
So long as the parameters are in the same order, the lambda's are only necessary if you intend to ignore them?
or if you want to change the order, yeah
basically - if you use the method (or an action) directly, the parameter list must match exactly
if the parameter list doesn't match, you need an intermediate function to handle the disconnect (which could be a method like you have here or a lambda in rob's example)
This is why I just make a method with the matching args for event subscriptions
VS will even generate it for you if you do += SomeCoolNamePlzMakeForMe; (using the 💡)
Ok I'll sort out the event subscriptions like that then, thanks so much! It's all good as all I need to show my supervisor is just a little demo so even if I can't get it to work it's all good, but it's just nice to have it as a little bit of polish
The main thing is unsubscribing will prevent your event trying to interact with "destroyed" gameobjects/components
the cheaty way is to add a if (this == null) return; to stop early if it was destroyed
And the handling of event subscriptions is why I was getting this error?
I suspect so but I cant read the stack.
Use a debugger if you are interested and you can check if this == null to see the mono instance is "destroyed"
same for the animator/any component /gameobject type
(imo you should let it fail fast to pick up bugs like this though)
Yea the exception informed you of this problem ᵗʰᵃⁿᵏ ᵘ ᵉˣᶜᵉᵖᵗᶦᵒⁿ
So from that, is it because I never made an instance of the AnimationController class?
Because I already have:
if (animator == null )
{
Debug.LogError("No animator attached");
}
And the error is on about UnityEngine.animator
If you have a monobehaviour on a gameobject and it has valid references its all good BUT when that gameobject is destroyed so are the components.
Our monobehaviour instance still exists because a class instance cannot just be deleted, our event sub is still called but it now will try to interact with a destroyed animator... Thats why there is an exception.
Oh right, so is it because I am transitioning between scenes, and these scenes have different NPCs with different animators attached. It's giving me this exception? But then again it's already assigned in the editor?
you are confused, your NEW scene has a NEW instance of AnimationController
the issue was never about something not being assigned
the issue is about something that's been destroyed
the previous scene had an AnimationController that subscribed to GameState.distributeDecision with a method that ultimately called NPCSpeaking and accessed animator
animator was part of that previous scene, which wouldve been unloaded, thus destroying it
but the event listener was never unsubscribed, so the stale listener persists
then when it's triggered, it tries to do stuff to that destroyed animator, that's where the error comes from
any one here know why i cant download Visual Studios on my mac? im new to game dev (it says error -10661)
its not supported anymore so try something else like vs code
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
ah ok so I fixed up the event stuff I think, but I still got the exception
using Cysharp.Threading.Tasks;
using UnityEngine;
public class AnimationController : MonoBehaviour
{
public Animator animator;
public OptionsMenu optionsMenu;
protected virtual void OnEnable()
{
animator = GetComponent<Animator>();
if (animator == null )
{
Debug.LogError("No animator attached");
}
GameState.decisionTime += PlayerSpeaking;
GameState.distributeDecision += NPCSpeakingCaller;
GameState.verdictTime += PlayerSpeaking;
}
protected void NPCSpeakingCaller(int choice)
{
NPCSpeaking();
}
public virtual void NPCSpeaking()
{
//Debug.Log("NPC Speaking");
animator.ResetTrigger("Player_Speaking");
animator.SetTrigger("NPC_Speaking");
if (optionsMenu.IsPlayerSpeaking())
{
optionsMenu.TogglePlayerPanel();
}
}
public void PlayerSpeaking()
{
animator.ResetTrigger("NPC_Speaking");
animator.SetTrigger("Player_Speaking");
}
protected virtual void OnDestroy()
{
GameState.decisionTime -= PlayerSpeaking;
GameState.distributeDecision -= NPCSpeakingCaller;
GameState.verdictTime -= PlayerSpeaking;
}
}
🤨 you have subscription in OnEnable but unsubscription in OnDestroy?
For more context, this is the class that inherits this, which is used in this scene:
using Cysharp.Threading.Tasks;
using JetBrains.Annotations;
using System;
using UnityEngine;
public class Level2Animation : AnimationController
{
public GameState gameState;
public Level2Timelines level2Timelines;
protected override void OnEnable()
{
Level2GameState.EndOfInterruption += RecallingToTalking;
Level2GameState.interruptionOption += PlayerSpeaking;
}
public override void NPCSpeaking()
{
base.NPCSpeaking();
level2Timelines.UpdateTimeStamp();
}
public void DisclosureResponse()
{
if (gameState.understandingNPC)
{
NPCSpeaking();
}
else
{
NPCArguing();
optionsMenu.TogglePlayerPanel();
}
}
public AnimatorStateInfo GetCurrentState()
{
return animator.GetCurrentAnimatorStateInfo(0);
}
public void Recall()
{
animator.SetTrigger("Recalling");
}
public void NPCArguing()
{
animator.SetTrigger("NPC_Arguing");
}
public void RecallingToTalking()
{
animator.SetTrigger("Finished_Recalling");
}
public async UniTaskVoid InterruptedAnimation()
{
animator.SetTrigger("Player_Speaking");
while (!GetCurrentState().IsName("Waiting"))
{
await UniTask.Yield();
}
}
public async UniTaskVoid IdleToArguing()
{
animator.SetTrigger("NPC_Arguing");
while (!GetCurrentState().IsName("Arguing"))
{
await UniTask.Yield();
}
}
protected override void OnDestroy()
{
base.OnDestroy();
Level2GameState.EndOfInterruption -= RecallingToTalking;
Level2GameState.interruptionOption -= PlayerSpeaking;
}
}
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
see the section on large code blocks
Oh right, sorry
you aren't even doing the subscription there lol
this could be an issue
the point rob made was about, symmetry i guess? not sure what to call it
Awake and OnDestroy are analogous
OnEnable and OnDisable are analogous
use 1 set of those for the subscription and unsubscription, rather than mixing them
if you subscribe in Awake, unsubscribe in OnDestroy
if you subscribe in OnEnable, unsubscribe in OnDisable
Oh shit I just realised I overrode without calling base lmao
Yep this is what I was meaning. The setup and clean up should be done with matching events.
@naive pawn @grand snow Thank you both so much, it works now. Can't believe I forgot to call base when overriding haha
You guys should honestly get paid with how helpful you are in this server
Idc if it comes off as me glazing you like it's krispy kreme but unity should deadass give some of you lot a piece rate.
When you have used unity for many years you just learn all this stuff 😆
Glad to pass on some knowledge
hi. wanna ask if using multiple material on one object is a good idea. like using one to rendering 2d character sprite then add more material to it to add vfx on top
or do i have to add all the effect logic into one shader?
idk im a beginner but maybe #💻┃unity-talk will be more helpful
very new to unity, any idea where I've went wrong here?
adjust your collider bound on your character
hi can someone help me with my multiplayer problem https://discussions.unity.com/t/big-multiplayer-problem/1680577
Your link doesn't work. And ask in #1390346492019212368 instead of here.
i get no answer there and here is the working link https://discussions.unity.com/t/big-multiplayer-problem/1680577/2
that link doesn't work either
if someone is available and able to help, they will be in #1390346492019212368.
if there isn't anyone available, you won't get an answer here either
so, don't crosspost
ok but how do i make it public
I need help. Does anybody know how I can access the local scale of an object? Like, from what I can understand, it isn't as simple as controling the position and rotation.
...localScale...?
what's your actual issue?
yes
the scale of an object doesn't affect its position or rotation, it affects the position and scale of its children
Ok, so im trying to make a health bar, my plan is to reduce the X axis scale of the bar as the hp goes down. I have tried a lot of stuff But I cant figure out how do I control the transform.scale with code.
ok yeah big https://xyproblem.info there
if it's a UI element, why not just use the built-in facilities like slider
pro tip: don't use scale or a slider for an HP bar. use an image set as a filled image and you can assign a value from 0 to 1 to manage its percentage
this also has the bonus of looking better too
what does the slider even do, I never really used it
ive never even heard of the concept of a "filled image" what, is it any different from a normal image?
it's an image component where its type or whatever is set to filled. you can literally test it out yourself
Yea thats what you should do instead of your initial crazy idea
you need to assign a sprite to an image component for the option to set it as 'filled' to show
My friend suggested it and it seemed genius at the time
it isn't
they must not know much about unity 😆
it will look awful the smaller it gets (if it's not just a colour)
Their fine with unity, just not the best lmao
it's just a beginner mistake
Beginners teaching beginners rip
LMAO it is just a colour
why's that funny?
Cus it's the one exception
(that's.. pretty much what slider is though)
Isn't a slider a player interaction object? Idk anything about it
you can disbale the interaction
Using a slider for health, you want to remove some of the components/ elements that get auto added when you create it
I think vs is not recognising the dotnet sdk
I can write code and it works but I can't see references and the Using directives are "unnecessary"
Other and new projects work fine, unity ones do not
Clipsize and reload are images set to filled, damage is a scrollbar
!ide
i mean, there are still visual differences. also a filled image doesn't have to be horizontally filled and takes less setup (since you won't have to do things like remove the handle, disable its interactivity, etc)
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
ah, good point. i misremembered, slider uses sliced by default
slider does work with filled too btw
Why is the damage bar different from the rest?
A downside to image filled is that it's hard,flat cut off,
read the text
Yeah I understand, you just didn't really explain WHY it's that way. Can't the damage bar also be a filled image?
it could, but scroll bar has a built in field for setting its position.. so it's much easier to use
I see
so you have it set like this?
size = max-min
center = (max+min)/2
the scrollbar i mean
not exactly what I was looking for
your ide is clearly unconfigured, so that's the resource you'll have to reference
are the "other" projects where it works, using dotnet?
How do I use a filled image. it doesnt show up at the list of components
@pulsar helm ☝️
ooh thanks
yes
creating a new dotnet project works fine, Opening old unity projects works fine
this one worked fine till this morning idk what changed
what does Vector2 direction do in a Physics2D.CircleCast()?
it defines which direction to cast the circle in
- what happens when restarting the language server or restarting the ide?
- any errors in the output tab?
- have you tried regenerating project files in unity?
wdym doesnt it just go from the origin into every direction on the x and y axis?
no
No, it goes in the direction you specify
you may be confusing an overlap check vs a cast check
ohhhhhhh okay thank you guys
Do I still need a seperate sprite renderer component, or just the image one?
you need to not have one
SpriteRenderers are for rendering sprites in the world
Images are for UI, in a canvas
so how do I get it to show up?
show up where?
on the screen, The sprite
yes
... the image component displays it on the UI
and set it to filled
and how filled have you set it to be
!learn -> do UI tutorials
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
this is now beyond the scope of this channel, it's nothing to do with code
I only tried changing the fill origin to right
that.. doesn't answer my question
go do some tutorials
this is what appears when you select filled, wdym by "how filled"
If someone's asking you the amount of fill you have set to, perhaps it's the field called fill amount
huh, yeah Im going to get some tutorials. i have no clue wtf im doing
The same problem, code works fine and is compiled and ran inside of unity. inside of the IDE there is no references though and IntelliSense is not working properly.
No all the output works fine
How do I do that again?
When setting the vertex attributes and triangles of a Mesh, does the check of whether triangles indexes out of bounds of the vertex attributes happen when any of the vertex attributes or triangles is set, or only when triangles is set?
In other words, when I am changing the lengths of multiple vertex attributes, can I always set triangles last (this corresponds the case where the check only happens when triangles is set), or do I have to set it first or last depending on whether I am shortening or lengthening the vertex attributes?
nvm
https://paste.ofcode.org/vSZsJQyDq7k9fbYPxRwvxL does someone know why i get an NullReferenceException at line 132? thanks in advance
Because something on that line is null but you're trying to use it anyway
yea but what could be null on that line
OverlapCircle is returning null
Meaning it didn't find any colliders
Anything before a .
So check all of the .s and see what is the thing that's being .ed
If that thing is something that can be null, check if it's null
oh so i would have to check if its !null? thought it returned a bool
nvm
If it returned a bool how would you call .CompareTag on it
bools do not have a CompareTag function
so i have to check if th overlapcircle returns something, and then i check if the tag is correct?
Yes
I am learning Unity in 3d currently,
I have gotten my camera to spin around a pivot at the centre of a sphere but I cannot get a zoom in/out function to work
float scroll = Input.GetAxis("Mouse ScrollWheel");
zoomDistance = scroll += zoomDistance;
zoomDistance = Mathf.Clamp(zoomDistance, MaxZoomOut, MaxZoomIn);
cameraTransform.localPosition = new Vector3(0, 0, zoomDistance);
// Tilt up if close
if (zoomDistance <= -2.5f)
{
}```
This code above is the one that doesn't work (Only the actual position change doesn't work)
``` private float zoomDistance = 1f; //Starting distance of camera
private float MaxZoomIn = 10f; //Max in
private float MaxZoomOut = -10f; //Max out```
These are the floats I am using ☝️
Can someone please help because I haven't found any online solutions that work?
zoomDistance = scroll += zoomDistance;
this seems a bit off.
but have you tried debugging what you're getting zoomDistance as?
do you see the position changing in the inspector?
are you getting any errors?
I have debug to see that the "scroll" float changes along with the zoomDistance,
Only the movement doesn't work 🤷♂️
hey guys so i'm trying to make a game with my friend and we're using unity version control, how do i make packages sync?
There is a manifest.json in the Packages folder which list your packages and versions.
Ah, I retried it multiple times and after "zoomDistance = scroll += zoomDistance;" nothing is logged,
Before that, it is fine
As I scroll up, it slightly breaks (I think) I am new to Unity to I am not sure
what value are you logging?
"zoomDistance"
that's not really broken, the value is still increasing
so what about this?
Nope, nothing moves in the camera, does it have to do with it being a child of an object?
I have a pivot at the centre of the sphere and the camera rotates based on where the pivot is
that's not what i asked
What value are you logging, and which object is cameraTransform?
check in the inspector of the thing you're trying to move, see if the value in there changes
Yeah, nothing changed?
Only the rotation works.
Sorry I just don't understand 😅
public Transform cameraTransform:
This is the main camera
I am logging zoomDistance which is a float (should be the starting position of the camera as well)
got it, any idea why the packages aren't getting installed on my friend's side?
show the inspector of the component that has this code
what's telling you that?
Ahhh!
Sorry
The pivot has the code
like he showed me his package manager
camera transform isn't set.
you shouldve gotten errors, this
and after "zoomDistance = scroll += zoomDistance;" nothing is logged,
wouldve been a hint to that
...and it showed...?
Ah sorry
Thanks for the help :)
we need info to actually help you
the packages that should've been installed had the button say "install" rather than "remove" or something
package.json?
Let's change the log so it's got more info. Add this log after you set the local position:
Debug.Log($"{cameraTransform.gameObject.name} is at local position {cameraTransform.localPosition}, world position {cameraTransform.position}. Zoom Distance is {zoomDistance}");
whoops sorry, the manifest.json
i'm used to that name 😅
has unity done the refreshing assets library thing
you should just have your friend ask here instead of playing this game of telephone
alright
Hey, I have a problem, I switched one of my unity projects to another laptop and now when I run it I get an error telling me that PlayGamesPlatform (part of the googleplaygames plugin v0.11.1) does not exist in the current context when running PlayGamesPlatform.Activate();, I am running using using GooglePlayGames; so I don't really see where the problem comes from
The platform went back to Windows from what I can see, idk why, I'm gonna try to switch
That fixed it
So you mean to tell me unity has their own version control and the package from package manager are not synced by default? Oof
The manifest.json file tells unity which versions of your installed packages to install specifically so everyone working on the same project can ensure they have the same versions
do i need to use rigid body for character controller?
no, ideally you wouldn't be using those two components on the same object at all
also im flying up
tried to use YSpeed float thing
that most of the videos telling to do that
you need to provide actual details
You're probably going to have to share !code because "YSpeed float thing" doesn't really help at all
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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 wait
void FixedUpdate()
{
if (gameObject != null)
{
jumpcooldown = !(Time.time >= last_jump_tick);
YSpeed += Physics.gravity.y * Time.deltaTime;
if (Input.GetButtonDown("Jump"))
{
YSpeed = -0.5f;
onground = false;
}
if (charController.isGrounded)
{
YSpeed = -0.5f;
onground = true;
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
MoveDirection = new Vector3(horizontal, 0, vertical);
MoveDirection.Normalize();
float MoveMagnitude = MoveDirection.magnitude;
MoveMagnitude = Mathf.Clamp01(MoveMagnitude);
charController.SimpleMove(MoveDirection * MoveMagnitude);
if (CameraObject != null)
{
Vector3 CameraForward = CameraObject.transform.forward * vertical;
Vector3 CameraRight = CameraObject.transform.right * horizontal;
Vector3 CameraLookMove = (CameraForward + CameraRight).normalized;
MoveDirection = SetVectorZeroY(CameraLookMove);
MoveDirection.Normalize();
}
if (jumpcooldown == false && Input.GetButtonDown("Jump"))
{
YSpeed = 20f;
onground = false;
last_jump_tick = Time.time + .3f;
}
Vector3 Movement = MoveDirection * MoveMagnitude;
Movement.y = YSpeed;
charController.Move(Movement * Time.deltaTime);
}
}
}```
the movement lines
Don't call multiple CharacterController Moves in the same frame, and probably don't mix SimpleMove and Move
Build up a vector containing all of the movement you want this frame, and call .Move at the end with that combined vector
ok
wait
ill feedback later
maybe its because of charcontroller and rigidbody is in the same gameobject?
that's definitely not right
they will fight for control
have rigidbody or charcontroller, not both
but having only the charcontroller making my capsule frozen
As was directly told to you already, you cannot have both on the same object
also this should be in Update
ok
Any idea why the list still has an element in it, after restarting the scene? Even though I clearly use List.Clear() in the script that it's established in both in awake and ?
public List<string> sceneFlags;
protected virtual void Awake()
{
decisionNum = 0;
timesStared = 0;
timesAverted = 0;
if(sceneFlags != null){
sceneFlags.Clear();
}
{...}
protected virtual void OnDestroy()
{
Debug.Log("Scene end");
Debug.Log(sceneFlags.Count);
sceneFlags.Clear();
optionsMenu.optionSelected -= relayDecision;
metreManager.GazeWinCondition -= SetGazeCondition;
metreManager.TriggerInterruption -= relayInterruption;
gazeDetector.GazeDetected -= setGazeValues;
metreManager.EnergyDepleted -= EndGame;
}
protected IEnumerator StareAndAversion()
{
while (!sceneOver)
{
if (gameState.sceneFlags.Count > 0 ) { Debug.Log("metres paused");
Debug.Log("pause flags active: " + gameState.sceneFlags.Count);
Debug.Log(gameState.sceneFlags[0]);
yield return new WaitUntil(() => gameState.sceneFlags.Count <= 0); }
{...}
}
protected IEnumerator GazeGaugeMetre()
{
while (gazeGauge.fillAmount < 1f && !sceneOver)
{
if (gameState.sceneFlags.Count > 0) { yield return new WaitUntil(() => gameState.sceneFlags.Count <= 0);}
What happens is that coroutines like this freeze after restarting the scene#
If sceneOver is false, but gameState.sceneFlags.Count is less than or equal to zero, that coroutine will be an infinite loop
unless you have another yield statement in that {...} you cut out
https://hastebin.skyra.pw/curagutowa.csharp hey can someone tell me why my character stops movig affter it oves a few times? the problem most likely lies in the look for food function. thanks in advance
Here's the rest of the class, cut it to save on characters:
protected IEnumerator StareAndAversion()
{
while (!sceneOver)
{
if (gameState.sceneFlags.Count > 0 ) { Debug.Log("metres paused");
Debug.Log("pause flags active: " + gameState.sceneFlags.Count);
Debug.Log(gameState.sceneFlags[0]);
yield return new WaitUntil(() => gameState.sceneFlags.Count <= 0); }
{...}
yield return null;
}
}
protected IEnumerator GazeGaugeMetre()
{
while (gazeGauge.fillAmount < 1f && !sceneOver)
{
if (gameState.sceneFlags.Count > 0) { yield return new WaitUntil(() => gameState.sceneFlags.Count <= 0);}
{...}
yield return null;
}
if (gazeGauge.fillAmount >= 1f)
{
GazeWinCondition?.Invoke();
}
}
protected void ResetBars()
{
staringScale.fillAmount = 0f;
aversionMetre.fillAmount = 0f;
}
protected virtual IEnumerator energyMetre()
{
while (energyBar.fillAmount > 0f)
{
switch (gazeStatus)
{
case GazeStatus.maintainedOnTarget:
energyDrainRate = 3f;
break;
case GazeStatus.maintainedNearMiss:
energyDrainRate = 2f;
break;
default:
energyDrainRate = 1.0f;
break;
}
energyBar.fillAmount = Mathf.Clamp01(energyBar.fillAmount -= energyDrainRate * (Time.deltaTime / totalEnergyTime));
yield return null;
}
EnergyDepleted?.Invoke();
StopAllMetres();
}
void StartMetres()
{
StartCoroutine(energyMetre());
StartCoroutine(StareAndAversion());
StartCoroutine(GazeGaugeMetre());
}
protected enum GazeStatus
{
OffTarget,
maintainedNearMiss,
maintainedOnTarget,
}
void StopAllMetres()
{
sceneOver = true;
StopAllCoroutines();
}
How is it infinite if it's a WaitUntil then is opposite to what is inside the if brackets?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
Instead of cutting things out, share it via !code so you don't leave out vital information
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
Well, there's two places you set the velocity. Try logging after those so you can see which ones are firing. If it's not moving, either the thing that sets the velocity to something isn't running, or the one that sets it to zero is running
add logs and see for yourself why it is not moving, theres a lot of logic here that you should be able to narrow down rather than saying its "most likely" in the food function. There should be no guessing here, use logs to find out where the actual problem is
Also please for all thats holy, cache the Physics2D.OverlapCircle(transform.position, sightRadius) that you do 3 times in LookForFood. you only need to do it once
Okay, so it does have a yield return null outside the condition, so that's fine. What, specifically, is the problem you're running into?
Collider2D col = Physics2D.OverlapCircle(transform.position, sightRadius);
if (searchFood && col != null)
{
if(col.CompareTag("food"))
{
berry = col.gameObject;
if (!berry.GetComponent<growBerry>().gotEaten)
{
target = berry.transform.position;
}
}
}```
better?
Significantly.
fixed it. idk whhy but i fixed it
I restart the scene and then even though I clearly use List.Clear(), it acts like there's still a string in the list. I'm using LoadSceneMode.single to reload the scene as well for more context. How the coroutines work is that they're based on these two boolean values from another class that get fired when the player hovers their mouse over a specified area. At first when restarting the list is empty, but then when hovering again, it now says there's 1 element in the list and locks my coroutines. I really don't get it:
Here's the class that fires an event based on mousehover that passes those two booleans:
Collider2D col = Physics2D.OverlapCircle(transform.position, sightRadius);
if (!searchFood || col == null) return;
if (col.TryGetComponent(out growBerry berry))
{
if (berry.gotEaten) return;
target = berry.transform.position;
}
Which list is the one you're clearing? Are any of these components on a DontDestroyOnLoad object?
what is this dark magic
nvm
same thing, just simplified
This one in my Game State class, level 2 game state is the child class inheriting it.
When I restart, at first it's empty again, but then when I hover over that area to fire the event that passes those two booleans, it now says there's a string in the list, in the editor
I think I might have figured it out now, turns out I never unsubbed from an event that causes one of the specified strings to be added to the list
Just tested it twice, yeah it was to do with events. Still thanks for the help tho @polar acorn
im still having the issues with character controller
it just floating
it cant move
oh i just fixed it
Hello, Does anybody here know how unity calculates scale based on position. Im trying to determine the edge points of a box from one another.
You probably want to use Bounds for that.
https://docs.unity3d.com/ScriptReference/Bounds.html
I believe most renderers and colliders have a .bounds property
also I dont know if it matters for this, but Im on 2d unity. Does that matter much?
Should still work
https://docs.unity3d.com/ScriptReference/Collider2D-bounds.html
ok, I'l trust you
ok I might be dumb, but the documentaion barely explains how to use it, Is it through code or do I need a specific component for it to work?
You would use the Bounds to get the center and extents in any given direction
Then you could use that point for doing your math
You know that one Austin Powers bit where they're very slowly driving a steam roller at a guard and he just stands in the way screaming for like five full minutes instead of getting out of the way?
Sometimes when you're coding you're that guard.
anyone know how to get unity 5.3.3f1 working 😭
I'd say probably don't
the hack comment was 4 month ago...
Very long time not getting out of the way
install windows 7
This cant possibly work right
right, but it'll make a good story
how do i share my project
in what context? With who?
my friend
Version control (either Git or Unity Version Control)
for developing it with you, or for testing it?
if the former, version control
if the latter, make a build and share that
You could have started your question like "I'm using Unity version control to share my project with my friend, but he can't see it even though he's added to the org"
oh mb
show some screenshots of what you did?
here ya go
ok have you actually made a repo for it in version control though?
how would i see that
i really need help
where is your friend looking? Is he signed in properly?
How would I make a web request in a custom editor window
Hey, I'm trying to get started with the gtk.
Making the ui seems pretty easy but I can't find any resources, other than the 2 attached samples, on writing the backend.
Can somebody recommend a good source for understanding that?
I am looking to make a tool that functions in a similar way to the shader graph, several nodes with math operations going down into a single node(the final float result).
Please @ me and thanks in advance!
anyone active rn
so ive made a 'guard' type enemy so they have a spotlight with a range of 10, and i want it so that if the player is seen within the radius the enemy changes direction
if the enemy is inside the physical light?
if you have a fixed light-cone, you could model a mesh in blender and use OnTriggerEnter for certain layers, and then use RayCasts to check if the object is actually visible from the light.
if you're in 2D you can use the Polygon-collider, to make one without blender.
if you're okay with losing some performance you could also do a non-alloc box/spherecast every FixedUpdate and then use maths to find out if the object is within the cone.
plenty of ways.
Hello mates, I'm trying to tilt this rocket by pressing left-arrow and right-arrow keys from keyboard. Here is the rotation script I used for it: -
{
float rotationInput = rotation.ReadValue<float>();
Debug.Log("Here is your rotation: " + rotationInput);
if (rotationInput < 0)
{
transform.Rotate(Vector3.forward * rotationSpeed * Time.fixedDeltaTime);
}
if (rotationInput > 0)
{
transform.Rotate(-Vector3.forward * rotationSpeed * Time.fixedDeltaTime);
}
}```
And ofc I added the namespace InputSystem.
Also, I tried `Debug.Log("Here is your rotation: " + rotationInput);` and it perfectly prints out -1 (by pressing left-arrow key) and 1(by pressing right-arrow key) on console.
PROBLEM: This rocket isn't giving even a slightest tilt after all this. idk why.
dont @ random people to try and get an answer. just wait for someone to reply
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
this is a code channel (hence the name), delete your post from here and ask in #📲┃ui-ux after doing some tutorials on !learn 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
sorry channel was hidden. no need to be passive aggressive
no need to choose a random channel because you can't see a specific one - use id:browse or #💻┃unity-talk
🤣
what "passive aggressive" are you seeing...
the (hence the name) - though when I typed it I was thinking it in a more haha tone, but ¯_(ツ)_/¯
Is it possible to give a line renderer collision?
did you try googling?
seems to give quite a few results
matey im just asking for help😢
yeah and im saying that google is a great place to start for a broad question like that
What are you trying to do?
Do the positions of the line change?
im trying to make a closed box, and the line renderer is the outlines of the box.
Why not just use a box collider
Well, the line itself isn't an object, so the collider would just be wherever the line renderer object is. Also, the box changes size at times and so do the lines.
box colliders can change size
could use quads (though that's just using a really thin box collider) instead, which would allow you to have the colliding bounds "grow" with the line renderer
bump
hello there friends
I need some help with a project, I created a simple cube in a plane just to test some theories i saw
but for certain i have misplaced some line of code
i mean, let me pass the code here
there is the code and video of the bug, anyone knows how to fix this behavior?
use !code to share code properly
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
and use mp4 to have the video embed in discord
i have a basic interface but for some reason the override doesn't work?
public interface SimpleInterface
{
void DoSomething() {}
}
public class SimpleScript : MonoBehaviour, SimpleInterface
{
public override void DoSomething()
{
Debug.Log("worked");
}
}
that void DoSomething() {} needs to be void DoSomething();
oh ok
still says no suitable method found to override.
like this?
A tool for sharing your source code with the world!
i followed a post about doing this and i don't see what i'm doing different https://discussions.unity.com/t/override-interface-member/5281/2.
you aren't actually inheriting the SimpleInterface
@light frost also do this
it still can't find it.
show your current code
https://paste.mod.gg/dwzmtfhazvgo/0
like this?
A tool for sharing your source code with the world!
ah wait @patent wedge you don't need override on interface impls
override is for methods marked abstract or virtual
i know you don't, but i what i want is a interface base where the scripts don't need that DoSomething() {} inside.
and how come doing overide here https://discussions.unity.com/t/override-interface-member/5281/2 works but mine doesn't?
Using classes it should look roughly like this:
they never said it's exactly like that
so you want defaulted methods?
(why not just use a base class though)
so you have both a character controller and a rigidbody?
Then it sounds like you don't want an interface 🤔
shouldn't? I don't know, first time actually trying to use the controller + inputsystem
they're gonna fight for control, you can't have that
oh ok
choose either a rigidbody+collider, or character controller
right, thank you
CharacterController and Rigidbody are two different methods for doing the same thing, so having both makes them fight it out and causes problems for both
because with a base class i can't have extra stuff like networkbehaviour.
isn't that a class
you could just have your base already extend networkbehaviour
or are you trying to get multiple inheritance?
well some need mono and some need network which is possible with a interface but not a class.
so you want multiple inheritance?
yes.
You can make the base class extend network behavior, then anything that extends that would also be a network behavior
Then this seems like an architecture failure. Why do you need such different kinds of things to share a parent type?
Doesn't network behavior inherit from MonoBehaviour?
because some scripts will need DoSomething(); while others will need DoSomethingElse();
Thats 2 different methods. Not sure how that's related to inheritance.
before i bug the game again, Cinemachine and the MainCamera also have this kind of behaviour?
yes, it has a component called camera, i dont know if conflicts or something like this
cinemachine depends on camera
it controls the camera, rather than fighting with it over control of something else
(rigidbody and cc would fight over control of transform)
ok, thank you
ok i have just realized that interface types aren't forced to have the methods if there written like public void DoSomething() {} instead of public void DoSomething(); but i don't know what the boolean equivalent is.
That sounds like two different interfaces then
that doesn't answer my question.
what boolean equivalent are you talking about
It does actually - the thing you're trying to do doesn't work because it shouldn't. You're trying to fit a square peg in a round hole.
what you've just stumbled across is called Default Interface Methods, yes they allow you to declare the body of a method directly in the interface but that should not be used just so you don't have to implement an interface's method. the entire point of an interface is that the members declared on it are accessible. Split it up into multiple interfaces if you want only partial functionality on some things
basically how do i have a boolean in my interface that doesn't have to be in scripts that reference it.
what do you need that for
that's pretty irrelevant to default methods
Interfaces cannot have fields
that sounds like an x/y problem
...yes they can.
No, they can't
no they cannot
if you public bool Bool { get; set; } that works for me
that's not a field
That's not a field
well, they can have static or const fields
but not instance fields
so that doesn't really help you
i never said it was a field. i just need it to not be required in my scipts.
this seems like a nightmare of an architecture
you have yet to explain why you need this
you should probably plan out some stuff about what you're trying to achieve with this
You still haven't said why you need "the thing that forces your scripts to have these methods" to somehow not need your scripts to have these methods
This literally is not what interfaced are for
ok i have a basic interactable interface that can used for buttons etc. it has a field that tells it if the player needs to hold the interact button or not aka the boolean.
ok, that sounds like it's doing too much