#💻┃code-beginner
1 messages · Page 362 of 1
doing it the other way around would mean taht stunRemaining immediately drops to length - 1
I'm not really thinking anything if I'm being honest just hoping I can read suggestions when I type that in to get my player to look around lol chatgpt failed me and so did youtube sadge
i see, thank you
you're going to have to actually write some code..
i just suggested a method name
instead of asking the spam machine to generate code for you, consider using the material on !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I did that today already for a few hours just wanna get started on my personal project to keep me motivated while im learning
also did ws school too on top of my electrical theory class my brain is kinda fried atm LOL
how do i sort this out?
cast both ends to float
thanks
or just make the length parameter a float instead of an int
what does it say if you right click it
nothing, just to change the formatting lol
It's warning you that you've done integer division, but then stuffed the result into a float
this is completely legal, but rarely what you meant to do
tbh I kind of like to do this
float progress = Mathf.InverseLerp(length, 0, stunRemaining);
when stunRemaining equals length, it's 0
when stunRemaining equals 0, it's 1
are the C# keywords such as async and await supported?
How would i make it so it changes to a different animation when facing left or right. This is a 2d game and the animations for left and right are different, so i cant just transform the player to have a negative scale
note that this is very recent
this page showed up in 2023.2
You've definitely been able to use things like UniTask in earlier versions
Hey all! God some rather odd questions that have been driving me crazy!
I do not know much about that library, though
Wondering if anyone would be able to help.
Modding for a game that restricts custom scripts and such, my problem is that I am trying to create, or mash together rather, some different functions to allow for what would be considering a tracking missile.
why lmao
Unrelated to the modding, as my questions are purely unity in this case.
I am essentially trying to figure out how to perform a relatively basic GetComponent transform on an object which may or may not be present in the scene at the time without a script.
I wouldn't have come to ask if I wasn't stumped.
Not sure what you're asking, do you mean how to prevent errors if the object is not found or something (null checking)?
aint no way that's begginer thats some nex tgenius shit
how to code without coding god damn yall smart
given that you're asking about this because you have a set of constraints while trying to mod a game, it's hardly "unrelated to the modding"
hey, it's point #2!
My questions are purely unity, the modding section is more of background as to why I can't run custom scripts. I am thinking about potentially using the transform.broadcast message function to pass commands but as to how I could actually use them to tie back a transform to a LookAt function is where Im losing my mind
The types of conversations modders have are often non-standard, often it's discovered someone's modding because they cannot do simple debugging or necessary basics, because they usually have access to an extremely limited subset of the engine.
I mean yea it says no modding in the guidelines but the best we can do is give him an engine/editor answer, right?
weird-ass problems you only run into when you're trying to mangle a game
I'd go to the game modding specific forum but this question has been consistently referred over to unity experts
This is all I need
No, I can explain exactly what Im doing actually
So, its for a game unturned(bully me all you'd like) but specifically to create Air to air missiles
I wish I could help but not really understanding. Are you asking how to decouple? Fen knows more than me, if they say it's mangling the engine then most others will give you the same responses
could i get some help with this from a more experienced person ;-;
Its more of just finding a creative way to solve a problem which I have a script to solve already
you can set an animator parameter based on which direction you're moving
call it isFacingLeft, maybe
right, but how would i actually change the animation loop?
by having transitions between animator states
does unity have a vc channel
there would be some duplicated work, though
So the earlier part of your question comes down to null checking. If the object (missile) exists, then do X, if not, then do Z. But the part where you're asking about "without a script" doesn't make much sense, hence why people haven't answered yet
you'd have two states for each of your original states
Basically I have:
- The missile which is just a projectile that has a trigger, trigger enters colider, boom. Hardcoded
- I have vehicles, of which I have already made. I'm trying to avoid having the track function specific to vehicles I've made, but I'd take anything at this point.
Problem is, without the objects existing as either parent/children of each other, I cant tie what I'd like to the Look-At function
Please explain it stupider :C
This is a good question I could explain/screen share
I'd be easier anyways
you're asking a question about something that makes zero sense in the context of unity game development. it's unsurprising that you aren't getting much of an answer
the problem simply does not exist when you are developing a game. you write code to do what you need to do.
I know... once again I am sorry. Nobody else in my community, be it the other modders or otherwise have any clue. I keep getting pushed here or other unity related discussions
If you know somewhere else for me to go where they'd be able to help I'm all ears.
Best thing I can say dude, is null checking. If nothing exists to tie to Look-At then you simply just set it to null or clean up the object (or give it an alternative behavior if it don't want it to go away)
I mean it really ain't that deep to be such a stickler of rules tbh
Yes, the official community. If developers wanted for you to have access to something it would've been provided. It's a multiplayer PvP game.
Well problem here is that this was the guidance I got straight from the source... I've emailed him on it. Its relatively frequent in the community to find work-arounds for it.
If anyone would call or just take a look I'd be massively appreciative.
It is not unity specific though. There is a limitation placed by the game. We don't know the game.
Even soliciting help from here is against the rules
But my question is purely unity specific
@open locust Enough already.
how would i do that, im sorry for having you explain it a bunch, im rlly new
I mean not really man it didn't seem like it but that doesn't mean someone shouldn't help u
Okay just let me know where to take it then.
I promise you that is the case.
No. Just stop
Just because it was made in Unity engine, it doesn't mean it works like that. It has an API, otherwise Escape From Tarkov would support the same code or something
Same thing as before? I literally just need someone who knows unitys ins and outs more than I do.
Aside from the rules, people tried to help. We don't know, and it is clear why (wrong place to ask). Do you have an answer then?
Maybe they'll have an idea I dont, I had an idea for how to make a camera that would align based on culling layers
bombbaaclat
!mute 227255921561174018 1d Ignoring warnings.
burning_bubbles was muted.
u can't read cna u didn't mean to sound so mean***
uh ohh someone had a power trip
I thought he got banned lmao
im a scary troll grr
@timid oriole You can stop with off-topic already. Please read #📖┃code-of-conduct
!mute 1126560790028238848 3d Off-topic, trolling
nicholas_004 was muted.
Hey now they got three days to figure out which part of the if statement goes inside the parenthesis at least
Anyway. So I was wondering is there any massive advantages to using await and async in Unity over stuff like coroutines or Invoke? First clear advantage is it is asynchronous but also the drawback seems you need to manually stop the task when the editior/software is out of focus or paused.
Another better question for this is, is there a use-case you can tell me where it would be better used?
if you're in 2022+ there's the destroyCancellationToken on MonoBehaviour you can use to cancel your tasks
the biggest advantage really is being a more familiar workflow for those who have experience with c# and asynchronous programming but less experience with the unity engine
How would i use (or make) an animation machine to change my 2d sprite from a rightward facing idle animation to a leftward facing idle animation. Im very new so please mansplain it to me
with the animator and the bool, you were already told this
then just make the bool true or false
based on direction
thats it
Let me look some stuff up, thanks
Funny you say that, that is why I asked yes. I followed some Microsoft C#'s tutorials and ended up there, then had a "thought" about how I could have alternatively used it in some of my recent Unity solutions
If you don’t know how to use the animator, check out the Unity Learn site
you just have to be careful and not touch any unity stuff off of the main thread. but that's fairly easy, if you're not starting tasks using Task.Run or explicitly putting them on the threadpool or a separate thread then your tasks will run on the main thread. There's also the Awaitable class in unity 6 that allows you to hop back onto the main thread from background threads (ande vice versa) which can be pretty handy
Yeah, that functionality looks really neat
But I don't clearly understand how it is useful. Also if it is generally accepted as "ok" or good convention
I'm thinking maybe for a use-case like rendering long distances...
Not literally rendering, but disabling useless/clogging objects that the player can't see
it is quite handy too, can do some stuff off of the main thread, like with steamworks to fetch a user's steam data/avatar then jump back to the main thread and assign it to some UI stuff
i don't really see how async/await would be all that useful for this. unity already has OnBecameVisible and OnBecameInvisible to determine when an object is visible by any camera and you can use that to toggle behaviours on/off
Ah, I was unaware. Just more of an example anyway
Trying to think of a use-case that takes advantage of the async aspect and more control of the task cancellation
Hello! I'm trying to make a menu where all the tabs exist on the same scene, and when the corresponding Menu Button binded to that tab is pressed, It moves through all the tabs in between the one you're on to the tab requested. It is in intervals of 600 because that is the length of each tab. For some reason when I use any of the buttons, only half the tab is displayed, and on top of that I can't change tabs after I've pressed one already. However It's not showing any errors...
https://paste.ofcode.org/NvArVyzwXnh2mTdiAUw4jy
This is the code, I can send screenshots of the Unity Environment if needed.
Maybe you could give me some advice actually, I want to try and learn more C# .NET stuff, coming from a Unity background. So my initial step was to go through MS C# tutorials. But wondering how you guys did it (if they were ever in the same boat?)
one thing i used it for when i was first learning about async/await (and i actually just talked about this earlier too) was spawning pipes in a flappy bird clone. I started the task in Start and just let it do its thing for the duration of the game/until the player died. That plus using the destroyCancellationToken (which did not exist when i did this a few years ago) for cancelling the task when the object is destroyed/play mode ended was a decent use case, though it absolutely could have been accomplished just using Update or a Coroutine
It's hard to tell how efficient/readable my code is, I've worked on quite a lot of collab projects and in a small indie company too, ut it has been a while since then for people to let me know
Interesting idea. My eyes are set on the Delay because I've always had issues with coroutines since the dawn of time X)
As you say though, Update/Coroutine was really the better solution, so it is more finding a use-case that the async/await apporach execels at
(ping me if you respond to any of my messages anyone, just brb)
can anyone help with this conundrum? (please 🙂)
I don't entirely understand the relationship between time and space in your message. Is "intervals of 600" about time or space?
Also, what debugging steps did you take so far?
oops sorry, I mean the width of 600
I tried moving the checks for position equaling 0 in and out of the if (tabname) statments
I made changeTab a function
but that changed nothing
I also made it have a offset of +300 to balance out it cutting the tab in half but that only broke it more
and I uh ran out of ideas
Oh I also tried putting Debug.Log() everywhere I could but that only raised more questions...
Why did you remove the debugs? More questions is good.
oh ok I'll add them back in
Never remove the debug related code when asking for help. It could help a lot to understand the issue.
good to know
oooooh wait
I just realised
When I did this:
if (_SettingsTab.transform.position.x == 0) { Debug.Log("Settings0"); }
It never send a message
Okay, then it never arrives at 0
bad idea to check floats with ==
yeah I think I'll try to check it around there
like this:
_SettingsTab.transform.position.x <= 0.001 && _SettingsTab.transform.position.x <= 0.001
ooooh approximates
floats 😅
my brain hurts, what's an Epsilon 😭 lmao
A very small number
from the docs
Description. A tiny floating point value (Read Only). The smallest value that a float can have different from zero.
https://docs.unity3d.com/ScriptReference/Mathf.Epsilon.html
why cant i use MoveVector.x?
i know it says why
but like
what can i change to fix this?
You can assign a whole vector, instead of just one of it's components.
what like new Vector 2 or something?
If that is what MoveVector is, sure
Ah, yeah the screenshot says it is. So yes
okay
thanks
MoveVector = new Vector2(launchSpeed * curveMultiplier, MoveVector.y);
doing this seems to multiply it massively and idk why
Debug it
I have a problem I can't fix an exact solution for, I basically want an enemy to have an "average" player location that updates over time, such that if you are moving constantly it will be low, yet if you are running around in a circle it will be high and "lock on" even if you are moving very fast in that circle
I think I need something like a moving average, but for a Vector3
and if I just take a moving average of the delta, then I think that's just a moving average of the VELOCITY
not the actual position, so running in a fast circle would count as "moving around a lot"
Just store the position of the last several frames and find the average.🤷♂️
what about deltatime, and then how do I then get a value of how much the player is moving from that?
I want the average to be over a specific period of time, not a specific number of samples
and then what, do I check the player's distance from that average point as a measure of how much they are moving?
Assuming your game is stable, that would around the same time. If you want, you could do it in fixed update. It's guaranteed to have the same delta time all the time.
Well, that's just velocity
A measure of how much the object is moving
is it a good idea to reference data created in fixedupdate from update?
well I don't want that
I want a measure of like, how much an object is moving over time, how much it is staying in one "area"
so if something is going in a circle, its average movement over time should be pretty low, even if its velocity is high
It's fine, sure.
compared to moving in a straight line
Could try getting the average of velocity
I mean why not do all logic in fixedupdate by that logic then, surely there is some tradeoff
no because thats just the average velocity, stripped of any spatial information
going in a cirlce would have high average velocity
even though your average position over a few seconds isnt moving at all
You can. Physics for example run exclusively during fixed update.
Velocity contains spatial information. It tells you how much and where the object is moving at a given time.
No, they would cancel out
In ideal situation it would be 0
ok so you mean the actual vector not just the average "speed"
Yes, velocity != Speed
for some reason I wasn't thinking about being able to average vectors, just the change between two vectors
I assume you average a vector by just averaging each component or something?
Sure, you can
like each group of components
and then just take the magnitude of that averaged vector?
which in theoretical conditions, while running in a straight line, would be equal to the players max speed
but if running around in one basic location, would be approaching zero
Yes
Yep
Though it depends on how often you sample it and how many samples you average.
shorter sample window being easier to "keep moving" within I assume because it has less memory, while a wider sample would discourage you from changing directions in a more harsh way
though, one possible problem, if you make a wide half-circle, it might consider your average velocity zero despite you being in a new location
well, no, it would be like half of max speed I think
because your movement on one axis would be nothing, but your movement on another axis would be the diameter of the circle
so maybe it's fine
This kind of stuff really needs to be tested and backed up with visual debug info to adjust it properly.
Why is movement weird/diagonal when im just pressing 1 key, and why am I only able to move in a certain direction once?
Sending code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class NewBehaviourScript : MonoBehaviour
{
public float moveSpeed;
private bool isMoving;
private Vector2 input;
private void Update()
{
if (!isMoving) {
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("Vertical");
if (input != Vector2.zero) {
var targetPos = transform.position;
targetPos.x = input.x;
targetPos.y = input.y;
StartCoroutine(Move(targetPos));
}
}
}
IEnumerator Move(Vector3 targetPos)
{
isMoving = true;
while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
yield return null;
}
transform.position = targetPos;
isMoving = false;
}
}
what are you trying to do lets start with that
do you want it to press w > move up the amount that you hold w for or press w > move up + 1 or something
move the character when pressing wasd in their respective direction
and do you want that to happen so if you hold it for 1 second it moves for 1 second then instantly stops?
basically like any normal movement
yes
then scrap all this code
it only moves when holding down key
i would just do rb.velocity = new Vector2(movement * speed);
movement = new Vector2(input.x, input.y);
and move it via the Rigidbody2D which you probably need to add and reference
my camera code is not working because in 'Physics.Linecast' have a error idk what is that error and idk how solve he
If there is an error, you should tell us what it is. Also, for mobile users like me, that is a download link. Share code like this 👇
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok sorry
if anyone knows a good tutorial or a good way to create like a playerID for a player spawned from the PlayerInputManager so that i can use that ID both outside and inside the prefab. my goal is to be able to reference the player and tell it to change its transform.position (its a racing game so i want to return them to the start of the track in certain positions)
No worries. Now, you said there was an error?
I am not sure what is expected by setting the z component of local position to the negated distance between the transform and the hit btw.
That doesn't seem like anything you would want
what do you mean use the ID outside and inside the prefab? this part doesnt really make sense
All this sounds like to me is you want some collection of players, whether that be an array or dictionary. Then either use the index as ID or really anything to look it up in the dictionary
The only problem i having is that in Physics.Linecast it is giving an error, not finding anything, this error here CS0117
you should show the error, no one remembers the codes
So, again, what is the error
That is the most crucial thing to tell us
theres a playercontroller.cs inside the prefab, i want to be able to use the PlayerID system inside this script but im not sure how to get a reference to another script other than making it a Static and not MonoBehaviour, I also want to be able to reference from other scripts Such as a Laptriggers.cs which is just a bunch of OnTriggerEnters to track if a lap has been made, reason i want this one to be able to track which player has made that trigger lap and have UI change from this.
this is for a splitscreen local coop not online if that helps
So you've got a playercontroller component on a game object prefab and what to use a member from another class/component etc?
Create a public or private-serialized field and drag the other object into that field from the inspector.
but the playercontroller.cs wont exist until i spawn the player using the PlayerInputManager so i cant assign anything from inside the scene or prefab to another script via inspector, or am i mistaken?
So when you spawn the object with the player controller component, you'd cache the instance and reference the necessary data:cs var instance = Instantiate(prefab); instance.playerID = playerID;where the spawner would have pass the playerID reference to the instantiated object with the controller component.
so i do this on the script that spawns my instance of the prefab
ok
so i have to find it in this then right
Where do you call instantiate?
Is it called for you? I havent used this component before if its built in. You might be able to tie into some event or method, like the ones listed at the top there
yeah it is called for me here, its a built in but it looks like I can edit the script itself, im looking for where it instantiates right now
They likely have some list of current players then
not sure if this is doing it but
This is just the property for the player prefab.
i think i found it
Look into that AllActivePlayers, see if there is any public getter for it
There should actually be more about that NotifyPlayerJoined too
That notification tells you exactly who joined
Hey. So, whenever you share the error, we can help.
But just wanted to let you know, you should not ever name a class the same thing as a unity component. Your class is named Camera.
generally is it better to have 1 big script that handles everything with the player for example movement, attacking, health, moves. or seperating them each into seperate scripts
Separate scripts definitely
aight bet thanks
What happens if you want an enemy that has health?
If you want to follow C# coding guidelines, you'll respect single responsibility.
https://www.digitalocean.com/community/conceptual-articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design
But doesn't move the same way
With separate scripts, you can just put that script on both
With a big script, you have to duplicate code or inherit or do not great stuff
also whats the thing for serializing a private variable again its [SerializeField] right
Yes
aight thanks
So i found where i can see the reference in inspector
private void Update() {
Collider[] colliders = Physics.OverlapSphere(gameObject.transform.position, scale, enemyMask);
foreach (Collider c in colliders) {
Debug.Log(c + " entered");
var enemy = c.transform;
if (enemy.childCount == 1) enemy = enemy.parent;
else enemy = enemy.GetChild(0);
for (int i = 1; i < enemy.childCount; i++) {
if (enemy.GetChild(i).TryGetComponent<Renderer>(out var renderer)) renderer.sharedMaterial = visible;
}
}
}```
so i have this code for changing materials of enemies that enter a certain sphere around the player, but how do i change them back to the original material when they exit it
Hey Devs, I've been trying to code on my unity project with a partner of mine on my windows system and we're collaborating using git... A lot of things have been annoying to use within my powershell terminal in VSCode to which I code in and I was wondering if you guys have suggestion on development when it comes developing w powershell bc i personally prefer bash or linux
is there a work around or do us Windows users just deal with it?
you should use nonalloc btw if you're doing this every frame.
put the results in a dictionary then use temporary Hashset maybe to store the new found objects and for all the ones not in the dictionary anymore revert their material and remove them from dictionary
hope that made sense
processing it
so use the dictionary as a kind of storage, then next time it populates collider check if it still is in the dictionary, if it isnt then change back and remove from dictionary
yeah the ones that are no longer inside the array of colliders from overlap the next frame, revert them as needed and remove from dictionary
how do i adapt the current code from overlapsphere to overlapspherenonalloc
cause it wants a collider[] results
yeah you need to make the array at the class level and assign a quantity
you want to pre-allocate
the original material, though you might not even need that now
yeah i was thinking it could just be a list
if they have the same materials
use a Hashset instead of list
yes it returns you an amount of hit colliders
yeah since now they are stored in a colliders array you made
for loop the amount of hits
then use that index for the array of colliders
for (int i = 0; i < hits; i++)
{
var colider = colliders[i];
}```
i really need help trying to figure out how i would access playerInput in pic2 and where the instantiation happens is pic1
do i loop through the hashset every time i update to check the colliders
yeah , you need two i think
two loops in hashset?
one for hashset and other for adding the new colliders hit
oh ok
private void Update() {
for(int i = 0; i < Physics.OverlapSphereNonAlloc(gameObject.transform.position, scale, colliders, enemyMask); i ++) {
if (!collideList.Contains(colliders[i])) {
Debug.Log(colliders[i] + " entered");
collideList.Add(colliders[i]);
var enemy = colliders[i].transform;
if (enemy.childCount == 1) enemy = enemy.parent;
else enemy = enemy.GetChild(0);
for (int j = 1; j < enemy.childCount; j++) {
if (enemy.GetChild(j).TryGetComponent<Renderer>(out var renderer)) renderer.sharedMaterial = visible;
}
}
}
foreach(Collider collider in collideList) {
if(!colliders.Contains(collider)) {
Debug.Log(collider + " exited");
collideList.Remove(collider);
var enemy = collider.transform;
if (enemy.childCount == 1) enemy = enemy.parent;
else enemy = enemy.GetChild(0);
for (int i = 1; i < enemy.childCount; i++) {
if (enemy.GetChild(i).TryGetComponent<Renderer>(out var renderer)) renderer.sharedMaterial = invisible;
}
}
}
}```
so like this
ok i'm trying to make an enemy that chases you while its far away and shoots at you when its close by
im using coroutines for its shooting cycle, but I can't get the coroutines to stop
either it shoots a trillion bullets because the coroutine starts every frame, or it never stops shooting even when I go far away and starts new coroutines when I go near
this is my code
im lost
ive been on this for 2 hours now
That is not how you stop a coroutine
You can do StopAllCoroutines or cached the return of StartCoroutine and pass that into StopCoroutine
Or just make a bool, like "firing" and do while (firing) instead of while (true)
ive tried StopAllCoroutines and had the same issue
ive messed around with bools too and no dice
ill try a firing bool tho, might make more sense for some reason
You probably want to set coStart to false at the end of the coroutine itself.
After the loop ends
nah doesn't look right
the issue im encountering with a fire bool is that i'd need to call that in a seperate method and carry it over which doesnt work
is there a way to do that
yeah the changing material works but the changing back doesnt
i was responding to navarone
oh ok
I don't understand what you are saying
just an example. Adapt to your usecase, should work though
private HashSet<Transform> transforms = new HashSet<Transform>();
private Collider[] colliders = new Collider[30];
private void Update()
{
var hits = Physics.OverlapSphereNonAlloc(transform.position, radius, colliders);
var newColls = new HashSet<Transform>();
for (int i = 0; i < hits; i++)
{
newColls.Add(colliders[i].transform);
colliders[i].GetComponent<Renderer>().material = newMaterial;
}
foreach(Transform t in transforms)
{
if(!newColls.Contains(t))
{
t.GetComponent<Renderer>().material = oldMaterial;
newColls.Remove(t);
}
}
transforms = newColls;
}```
Set firing true in update
i see
like id have to chance firing to true inside the update, and then if its changed in update it doesnt work in the coroutine
ive tried stuff like that
Why would it not work in the coroutine?
I promise it will. That is the normal way it is done
Oh, are you making a local variable? So it is out of scope outside update?
Yeah. You'd have to make it a class member
so I switched to StopAllCoroutines and set coStart to false inside the coroutine itself and now its making projectiles every frame again
but it does in fact stop when I walk away
what does this mean
private WaitForSeconds fireWait;
void Start()
{
fireWait = new WaitForSeconds(0.5f);
}
void AI()
{
if (distance <= 30f)
{
if (!coStart)
{
coStart = true;
StartCoroutine(Shooting());
}
}
else if (distance > 30f)
{
coStart = false;
}
}
IEnumerator Shooting()
{
while (coStart)
{
Instantiate(//blah blah)
yield return fireWait;
}
}
Means the variable is declared in the class, not in a method
But this is how you would stop a specific coroutine instance 👆
oh ok so that makes it so you can call it in all the methods and it carries between methods
this works but starts producing a bunch of errors when the enemy destroys itself, how do i adapt for that
oh wait i can just check for null ig
ok I see
my current problem is it starting about 1000 coroutines
ill look into a firing bool
My code makes that not possible
but couldnt I kinda do the same thing wiht my coStary
Yeah, as I said, you want to set that false INSIDE the coroutine
That was the main change I made in the example code
yeah I did
what is fireWait
sorry im just trying to understand your code so I learn rather than just copying
a cached WaitForSeconds object, so you don't allocate a new one every iteration
No reason to make a new one every time if it is just the same length of time
yeah managed to fix it on my own
yeah make sure to clean those up up properly and check null
I use GetComponent for writing quick in dc but you should ofc use TryGetComponent etc.
i did cs if(t == null) { transforms.Remove(t); break; } before the if (!newColls.Contains(t)) {
one issue im getting looking at this code is that when coStart = false is outside of the while loop within the coroutine it will never be called
Why not?
because while true never ends
Oh, I see
true true, the stop coroutine doesn't let the code finish iirc
Then yeah, one sec
So are you saying you did your code like the new edit, and that didn't work?
Wait, I didn't really look at the distance code, why are you doing it like that at all? Instead of just
distance = Vector3.Distance(transform.position, player.transform.position);
tbh didn't know it existed
should make things easier
I googled how to get distance in unity and was told i needed to calculate it
so im going through these edits and it doesnt like the firewait code
Sorry, phone coding. fireWait is the name, and there should be no = sign on that line
oh ok thanks
ok so Im probably missing some edits since the code i was studying disapeared at some point
but im still getting a ton of projectiles
sorry im really helpless
Show your current code.
Also, what object is this script on? The enemy?
So, you still have while (true)
did you try changing that to while (coStart)?
also, remove both coStart assignments from the coroutine for now. (I know, I said the opposite before, sorry)
hey so i have a fist weapon and i have it so it rotates around the player depending on where the mouse is looking at i want it so when i attack the fist like punches so it goes out a little then back how would i ahieve this because i cant just change the x position because that wont work if its rotated
also how do i have it smoothly go not just teleport
so I changed it to while(!coStart) (which is the same as coStart == false right) and now I get no output from the enemy
Not while (!coStart). while (coStart)
well the point of the coStart function is that the coroutine doesnt happen while its true
but I can just change that
Exactly
that is why it needs to be while (coStart)
wouldnt that set off the loop while its not supposed to tho
also still no output from the enemy
while coStart is true, do the things in the coroutine
Still no output? Show the current code again
you should add some debug logs. Log the values of distance in AI, and do one in the if(coStart == false) condition
ok
How does this script use the grid/tile system to move the player around? I wrote it down from a video tutorial on a Pokemon-like game
private void Update()
{
if (!isMoving)
{
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("Vertical");
if (input.x != 0)
input.y = 0;
if (input != Vector2.zero )
{
var targetPos = transform.position;
targetPos.x += input.x;
targetPos.y += input.y;
StartCoroutine(Move(targetPos));
}
}
}
IEnumerator Move(Vector3 targetPos)
{
isMoving = true;
while((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
yield return null;
}
transform.position = targetPos;
isMoving = false;
}
I have an old debug log overwriting, I gotta go find it
found it
miraculously one I removed the debug log from a completely unrelated script it started working
got it mostly figured out main problem is making it change depending on where you look aswell because rn it just goes in the positive x
Weird, but ok. Glad it's working!
yeah, but not anymore
you dont gotta keep helping me it must be annoying
basically I added the script that moves it towards me while far away back in, and now it continually moves in and startes shooting sprays and duplicates after moving a bit
yeah when im in range, it shoots normally. When I move out of range it shoots a thousand projectiles before stopping
I think its something to do with going in and out of the range
ill try to fix it myself
yeah it sprays when you stay on the edge of its range
can be mitigated by lowering its speed
try making the second if an else if
im thinking I could just make a little gap between the shooting and following range
yeah, that could help too. Even just .1 difference
anyone know how im meant to write this?
GetPlayerByIndex TAKES an int, and RETURNS a PlayerInput
you would write something like this:
PlayerInput input = GetPlayerByIndex(1);
🙏
guys how would i make the cannon look at the block (lookat is not working as intended)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rotating : MonoBehaviour
{
[SerializeField] private Transform sphere;
[SerializeField] private Transform target;
private void Update()
{
Vector3 targetPostition = new Vector3(target.position.x, sphere.position.y,target.position.z);
sphere.LookAt(targetPostition);
}
}
looks upwards for no reason
One thing, you could just do sphere.LookAt(target.position); without making that new vector
Second, what IS sphere, you want THAT to just rotate around the y axis, right? And then the turret would move up and down separately
im locking the y axis
That only affects REACTIONS to force
Not your code
um wdym
If you tell it to rotate, it will on any axis, despite locking an axis on the rigidbody
Ahhh
bro there isnt any rigidbody
I see what you mean
Please don't call me bro.
There is a property on the rigidbody where you lock axes, so I thought you meant that
ah
Hard to say what's going wrong without seeing more. What is the rotation of the turret to begin with?
0,0,0
Well I'm trying to check the playerIndex for the current players number
Would
If (PlayerInput.playerIndex = PlayerInput.GetPlayerByIndex(1))
Work?
And that is the sphere, right? While the turret is a child of it?
= is an assignment
im rotating the sphere tho
Typo I meant ==
And no, as I said, it returns a PlayerInput
Not an index
yes the turret is seperate
How would you suggest I get the current playerIndex int assigned to the current instance of PlayerInput for my playercontroller script to use in an If statement
If possible
hey guys i need a bit of help
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class IntroAnimation : MonoBehaviour
{
public AudioSource introAudio;
public AudioClip introSound;
public TextMeshProUGUI welcomeText;
private bool continueToIntro = false;
void Start()
{
welcomeText.alpha = 0f;
welcomeText.characterSpacing = 60f;
introAudio.clip = introSound;
Invoke("introSequence", 1);
}
void Update()
{
if (continueToIntro && welcomeText.characterSpacing > 2)
{
welcomeText.characterSpacing = welcomeText.characterSpacing * 0.997f;
welcomeText.alpha += 0.001f;
float elapsedTime = Time.realtimeSinceStartup;
Debug.Log(elapsedTime);
if (elapsedTime > 6f)
{
Debug.Log("Fading out");
for (int i = 0; i < 2000; i++)
{
welcomeText.alpha -= 0.002f;
}
}
}
}
private void introSequence()
{
introAudio.Play();
continueToIntro = true;
}
}
here's my code, I want to fade the text out after elapsedTime has reached 6 seconds
but for some reason that just does not happen and idk why :/
Do your logs ever reach 6 or greater or does your condition become false before then
Also as soon as it hits 6 seconds it's just going to instantly blink out of existence, because your loop will run 2000 times in one frame. You might as well just set the alpha to 0
my log just
stops at around 4~5
OHHHHH
so how do I make it fade out?
Because your condition becomes false
Your spacing becomes 2 or less
Reduce the alpha once per update over several updates
ah ok
this good?
wait one correction, this:
will this work?
im sorry, what does that mean?
Your if condition
The code inside it will only run if that's true
And you're checking if spacing is greater than 2
Once it becomes 2 it stops running
How would I be able to get this to work with Lists instead of arrays?
{
return array[UnityEngine.Random.Range(0, array.Length - 1)];
}```
what would be different? it's the same . . .
I'm trying to call the function and its not showing up so i figure its not working for arrays
how and where are you trying to call it? where does the method exist at?
Its currently in a static class
{
public static T NextRandom<T>(this T[] array)
{
return array[Random.Range(0, array.Length - 1)]);
}
}```
I'm trying to call it from a list i generated called validTiles
validTiles[UnityEngine.Random.Range(0, validTiles.Count) This is where Iwould use it
also, you don't need Length - 1. for ints the max is exclusive . . .
alright
you call it from a list, but the method is an extension for an array. do you see the problem?
right so how can I change the function to support a list?
without converting the list to an array
you need to use/find a base collection type that accepts both a list and an array . . .
that'll work for a list because you changed the type to use a list . . .
you can look at List<T> and Array from the C# docs to check if they derive from a similar or matching type . . .
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-8.0
https://learn.microsoft.com/en-us/dotnet/api/system.array?view=net-8.0
ill try icollection
does the array class derive from that?
yea ```
Implements
ICollection IEnumerable IList IStructuralComparable IStructuralEquatable ICloneable
but it doesnt have count so I think IList is the right one
seems to work with both arrays and lists thanks!
nice, there you go . . .
thanks that helped because I learned something new from it never used that before
hi can i get some help
i want to change start of cat animation when it collide with a differnt platform
i will show you and a demo
private void Update() {
colliders = new Collider[1];
if (Physics.OverlapSphereNonAlloc(transform.position, radius, colliders, playerMask) > 0) {
if (!canHit) canHit = true;
else {
animate.Attack();
StartCoroutine(Waiter());
}
}
else {
if (!animate.GetComponent<Animator>().GetBool("isDying")) animate.Reset();
canHit = false;
}
}
private IEnumerator Waiter() {
canHit = true;
playerStats.Damage(enemyStats.stats[StatNames.Attack] - playerStats.stats[StatNames.Defense]);
yield return new WaitForSeconds(enemyStats.stats[StatNames.AttackInterval]);
canHit = false;
}```
trying to have an enemy attack function but how do i prevent it from attacking every frame instead of attacking according to attackInterval
private void Update() {
colliders = new Collider[1];
if (Physics.OverlapSphereNonAlloc(transform.position, radius, colliders, playerMask) > 0) {
if (!entered) {
entered = true;
canHit = true;
}
if (canHit) {
animate.Attack();
StartCoroutine(Waiter());
}
}
else {
if (!animate.GetComponent<Animator>().GetBool("isDying")) animate.Reset();
entered = false;
canHit = false;
}
}
private IEnumerator Waiter() {
canHit = false;
playerStats.Damage(enemyStats.stats[StatNames.Attack] - playerStats.stats[StatNames.Defense]);
yield return new WaitForSeconds(enemyStats.stats[StatNames.AttackInterval]);
canHit = true;
}```
i was able to stop it from hitting every frame but now it attacks once the first time, then twice, then three times, etc which i dont get at all
Guys I am not sure how to overcome this issue, I have a text mesh pro in one scene with a blue fill color and a dark blue outline. I have another scene with a text mesh pro but I want it to be only white no outline, but everytime I change that, the text in the first scene changes too. Can someone please tell me how to fix that? Sorry if this isn't the right place to ask.
Why is my class blank when added to a game object? I think its causing problems when play testing, i tried remaking the script as well.
using System.Collections.Generic;
using UnityEngine;
public class TileRow : MonoBehaviour
{
public List<RoomTile> Tiles;// { get; private set; }
public GameObject Root => gameObject;
public RoomSection Section;// { get; private set; }
public int TotalIndex;// { get; private set; }
public int SectionIndex;// { get; private set; }
public void Setup(RoomSection section, List<RoomTile> roomTiles, int sectionIndex, int totalIndex)
{
Section = section;
Tiles = roomTiles;
SectionIndex = sectionIndex;
TotalIndex = totalIndex;
for (int i = 0; i < roomTiles.Count; i++)
{
roomTiles[i].Set(this, i);
}
}
}``
what do you mean your class is blank?
The icon next to it is blank as well as the script field
Even though its a monobheavior
did you add the script in the editor?
you need to drag the gameobject with the script on it into that blank script box
ok ill try it once unity finishes reimporting
Do you have any errors probably?
well everything works fine but yes im encountering a strange error for a coroutine on startup
all the values are there from the debug logs
Something seems wrong with the TileRow script though, it's not supposed to look like that
there should be no Script at the top
Guess so, it was just not done with importing and handling the script for either error or meta issue
i think its because I converted it from a public class to a monobheavior and unity didnt update it
How would I be able to find whats missing from this?
Debug.Log(_totalTileRows.Count);
Debug.Log(tile.Row.TotalIndex);
return tile.Row.TotalIndex < _totalTileRows.Count - 1;```
Both are coming up with proper values but unity is saying the error starts here
NullReferenceException: Object reference not set to an instance of an object
Either use null propagating or log each field/property individually to figure out what is null
Your stacktrace would have told you the actuall line that it threw on so that's the line to check out
Or use proper debugging: https://unity.huh.how/debugging/debugger
alright
So you are saying, both debugs return a correct value?
I don't see the relevant code that sets tile
So basically, I generate a tilemap outside of play mode. When I run play it starts a coroutine that does stuff related to whats genereated. The first time works fine but if I edit test mode and try again I run into an error.
tile is being detected atm
edit test mode?
like clicking play on unity editor
So you hit play and it runs. You stop, hit play again and it breaks?
yep, it always works the first time
since the values arent persistent after exiting play i dont know why this is happening
So whats your full code doing. please use hastebin or something to show the full part.
alright , let me go through all the values in inspector first
the code is kind of messy atm
The most important parts will be, where you probably change a tile position or something. Are you doing anything like that?
Also, as fusedqyou said, where is the variable tile being set
{
public MonsterSpawnStats SpawnStats;
public RoomTile CurrentTile;// { get; private set; }
public void OccupyTile(RoomTile roomTile)
{
CurrentTile = roomTile;
roomTile.SetOccupant(this);
}
}```
So far its working now after I reduced a value to 1 so its related to one of my algorithms and not the script itself
im going to look further into it
and now everything works... idk anymore lol
So your code fixed itself by setting something to 1? I am scared of your code structure 😄
when i run into these things i restart unity
idk if this has anything to with it
(Experimental) might be prone to bugs 😉
yea its probably that
That stops recompiling when hitting play I guess, and as experimental, this might just miss some things to setup properly before entering playmode. Just do not use it, id say
its really good though when you press play its instant
there are some ocassional bugs but i usually restart unity
Dont know your project size and working environment, but for me, those 3 seconds reloading are not a big hit.
in my case it saves me alot of time since i restart alot however im starting to incorporate editortools to not have to do it in some case
https://docs.unity3d.com/Manual/ConfigurableEnterPlayMode.html this might explain whats going wrong. especially the recreate c# state as well as reloading the scene.
Why do you have to restart a lot?
Wait, you have to restart the whole editor when changing code?
no i mean i have to stop playmode in order to test new code
recompile > wait a few seocnds before playmode starts up again
how do i change the state of an animation if it collied with red block but return to is original state when it collide with a blue block
Ah okay, got it. Maybe correct the behaviour of trial and error debugging 😉 but sometimes its just the way it is
Did you write any code yet to checkout?
yah
you look up a tutorial on how to do animations in unity
So where is the code and what is not working
i dont think is a code problem
so why are you in code then asking for help?
is there link to show my 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 i have in the animator is "jumping" which is the main idle that has two blend tree "jump" and "fall"
Thanks
If you're doing small changes, look into a hot reload plugin. If you arent adding new methods, but are just changing like a value here and there then itll save a bit of time. Also consider trying to make things less hardcoded if you find yourself recompiling to change a number. If its exposed in inspector, you could save the time by just changing it there.
i actually bought one of those years ago but wasnt able to use it
most of the time im restarting play mode is related to debug logging
fast script reload is free on the asset store
hey i just have a simple question, if i have a list of gameobjects and i destroy one of them, is it now gone from the list or just a reference to a gameobject that is null
maybe a weird question
I think a null reference
Maybe try getting the game object, remove from list, destroy then
The list references the same gameobject but since it's been destroyed it acts like a null (for most practical purposes)
i see, thank u guys
This wouldnt be necessary, since you could just remove null objects from the list. This would also be hard to enforce because anything at all can call Destroy(someGameObject). Since you also would need to add events or additional code for when an object is destroyed, it's really just easier to check for null and remove those.
Fair
Ideally, you want the object remove itself from the list or tell someone higher up to remove it.
You should know what and when destroyes the object. Otherwise you're asking for bugs and difficulties in debugging them.
As far as I know, in Unity, the name of the script file containing a MonoBehaviour and the class name must be the same. If they are not, the script wouldn't be properly added in the Inspector and a warning message would appear. However, while using Unity version 2022.3.18f, I noticed that the script file and class names can be different without any issues.
Is it really safe to use different names for the script file and the class in this case? Previously, with ScriptableObjects, although there were no warnings when creating them with different file and class names, I experienced the script references becoming invalid and turning into corrupted data when reopening Unity.
I'm worried if the same might happen with MonoBehaviours in this case.
They changed it recently, but I'd still suggest to follow that rule.
It really depends on what you're doing. For example if you have an enemy AI that's storing a list of nearby targets. Your options there are either subscribe to an event, notify the object it's being watched, or just check for null when the ai goes through targets.
It's really a lot simpler in the 3rd option
I guess there might be some cases where it's fine. Depends on the complexity of the project/system.
Do you have link for that update? or on which version it comes in? Now even multiple MonoBehaviour class in one script does not make error. Just first appearing class is attached to inspector. I want to know the details
I don't have it. I just heard it from other people on discord. Try googling though.
Thanks dllich!
if i make array which holds multiple same audioclips it uses up resources as just one?
AudioClip is a class which is a reference type so your array does not 'hold audio clips' it holds references to audio clips
gameData = JsonUtility.FromJson<GameData>(fileContents);
what <> syntax means?
that means you are supplying a generic type parameter, in this case GameData
public static T FromJson<T>(string json)
This method allows you to specify the type T, which your string json is converted to. This is also the type of the returned value.
For example, having, in your case, the type GameData, the string fileContents is then parsed to this object.
public static object FromJson(string json, Type type)
This is called generics, and using it allows you avoid bad-looking 2nd parameter Type and object as the returned value, which, surely, should be parsed to the desired one, as it's done in the generic overload.
return (T)FromJson(json, typeof(T));
Without generics, your code looks like this:
gameData = (GameData)JsonUtility.FromJson(fileContents, typeof(GameData));
wow tysm for your very detailed information
i understand now
is there any way to add a component to a gameobject after starting play time?
yes . . .
i have a wave spawner script but after i kill the first wave the second one fails to begin
Define fail?
Or rather, show how you are starting the next wave
when i kill first wave it should say wave completed but it doesnt
So then one of your previous IF statements are not running successfully. You need to verify the code for what state you think you're in, and if EnemyIsAlive is correct.
You can start by debug logging both those things at the top of your update function to track their values.
is state set to SpawnState.Waiting? is EnemyIsAlive ever false?
does the ! before EnemyIsAlive mean is not alive
do you know what ! means? you placed it in your code . . .
i watched a brackey tutorial for it and from what i remember i think he said that but im not sure
so it gives the opposite value?
okok thank you
how would i write a debug log to check which state im in
Debug log should literally have been the first line of code you ever wrote
do you have a variable of type SpawnState? if so, log that variable to check its value . . .
Guys how can I force my game to run at a specific resolution at all times?
i am very new to code ive got a project to do for college for next week for been taught no code
not a problem. you should always try searching first. just search : "unity how to log a variable" . . .
doing that now
u have been very helpful
https://docs.unity3d.com/2022.3/Documentation/Manual/class-PlayerSettings.html Resolution and presentation
On debugging in Unity http://unity.huh.how/debugging
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I had missions panel in which I had two more panels named level 1 and 2 they are not being shown is this code correct ? Why missions.transform.GetChild(startingIndex).gameObject.SetActive(true) is not working
{
if (startingIndex < 0)
throw new Exception("Button is not initialized");
SequenceManager.Instance.SetStartingLevel(startingIndex);
Debug.Log("Value of currentLevelForMissions: " + startingIndex);
missions.transform.GetChild(startingIndex).gameObject.SetActive(true);
m_NextLevelEvent.Raise();
/* Debug.Log("hi " + startingIndex);*/
}
Probably debug log your getchild(index) thing and see if you targeting the correct child
FYI, pressing enter after the cs makes the block work with colours.
Yes I have checked that with separate script it's working but here this line doesn't works in on click method
Ok thx
!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.
im having a problem that makes the character unable to dash, i think its owing to the fact that i use forces, but i dont know exactly how to modify the force applied, and neither how to measure it, im using totalforce but i dont know if its the optimal way https://gdl.space/usaputilig.cpp
{
Debug.Log(state);
if(state == SpawnState.Waiting)
{
if(!EnemyIsAlive())
{
WaveCompleted();
Debug.Log("Wave Completed!");
}
else
{
return;
}
the state stays in waiting when all enemies are dead
could this be because it doesnt know if the enemies are dead
the improtant part is missing. Where do you set the state?
i debugged the EnemyIsAlive and when all enemies are dead the variable is still set to true
? Where do you set the state in your code? That is just a variable at the start of your script.
you think?
You should know. And still, where are you setting it to != Waiting? you spawn enemies, set it to waiting and then? where does it change after that?
once enemies are dead it changes back to spawning
but it doesnt detect when they die
Show EnemyIsAlive()
i changed it to rb2d.velocity and it still doesnt work, im using debug.log and it shows that when i save the velocity in the vector 2 it has a value, but whenever i dash its set to 0
where does it change back to spawning? this snippet does not show that . . .
Show the objects with the tag character
Well, I would throw some debug.logs in to check the values in EnemyIsAlive
I would also just store the enemies in a list when you instantiate them, and check the length of that list instead of using find. But find may work, just verify with some logs or the debugger
ty for reply, i debugged EnemyIsAlive and it the value stays true even when theyre all dead
could it possibly be the enemies script thats messing it up?
i forgot how do i make it so in a if statement i want it so it has to be two conditions that need to be met
How should I seperate loading and saving for 2 different things? Should I have 2 different save files for the 2 things I'm trying to save? Or is there a better way?
(trying to load/save player inventory independently of the player world)
&&
o ty
What sets EnemyIsAlive to false
or should I add a way to load some parts of my save file depending on what value is passed through my load function?
that would require a complex solution, so 2 files is probably your best option
No, it's not that. Likely something else is tagged character
Again, i would not use that find call. Even just an int that you subtract from when an enemy is killed would be better
could it be something thats not in the hierachy?
No
if i were to create an int for the enemies alive would i have to do it for each individual wave?
Depends on what you want. I was thinking one int called enemiesLivingCount
well i'm using unity action. so would something like image 1 make sense?
currently it looks like this
so i could always make a seperate one for the world
so something like when that int is <=0 start next wave?
not really unless you are using the same class to save both types of data which would make no sense
Use a generic make the saving more flexible
well, right now all the data is being saved to 1 file, so yes
also. Use Path.Combine don't be doing this stuff lol
is there any easy way to search for objects witha specific tag
You'd recommend I seperate the saving into 2 files. Isn't that just more code?
in the scene or code ?
scene
is 'more code' your priority? Or is better code more important?
try tag: "myTag" in the big search
in my if statement i need to make sure the object has a rigidbody 2d how do i do that?
depends
how do you get a RB 2D ?
var rb = GetComponent<Rigidbody2D>();
if(rb == null)
//no rigidbodyfound
thanks
spoon feeding, tut, tut
hi fellas im trying to follow a tutorial on how to do an fps controller in the new input system but either im stupid or something's up
true, didn't think thats what they asking for anyway lol
I'll paddle myself though paddles butt
anyone willing to help
you have not asked an answerable question yet
help with what
eh im checking if it helps
what are you trying to do with this anyway?
mb it's saying "PlayerInput does not contain a definition for "Player"
how do i condense the words
📃 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.
well my goal is to make a drag system but more specifaclly
use liinks @mint seal
check it from where though
how are you detecting it in the first place
though a raycast hit
what is the error?
ok so raycastHit give you the Collider etc.
do a TryGetComponent on that
did you configure the Input asset correctly ? this is more of a #🖱️┃input-system question
send the video tutorial
from the raycast restult
makes sense, thanks
Check out what Unity3D has done with the new Input System. This Tutorial will show you how to create a First Person Controller with the new System.
Discord - https://discord.gg/szfDAKgUPH
im assuming it's outdated but im not sure what is
did you create the input asset correctly
show the generated class you created
im still very confused so can i send the code?
use links to send
#💻┃code-beginner message
so hear me out i dont know what that is either
generated class of what?
its literally part of the video
the part they literally click "Generate C# class" around 7:50
the issue might be you calling the class PlayerInput
that is already a reserved name in Unity
looks fine except for this cs heldObject.transform.GetComponent<Rigidbody2D>().AddForce((mousePos - heldObject.position)*6f); heldObject.transform.GetComponent<Rigidbody2D>().velocity = ((mousePos - heldObject.position) * heldObject.transform.GetComponent<Rigidbody2D>().mass);
whats the issue there?
uh well if heldObject.transform has no Rigidbody you get a Null Reference Exception
its trying to access methods on a component that wasn't found
you gotta wrap those up inside an if statement
how are you checking on raycast if a collider even exists ?
look carefully at your own code yes
im not the greatest with code
you should at very least attempt to understand what you wrote so far..
ill look through it
look the the if statement with the collider
I'll spoon feed this time
Rigidbody2D rb2d = heldObject.transform.GetComponent<Rigidbody2D>();
if (rb2d != null) rb2d.AddForce((mousePos - heldObject.position)*6f);
or better yet TryGetComponent and skipp the null check
that may be a little too advanced
i hate to say it but im still pretty confused
two spoon and it did not stick
what dont you understand?
why do we have a if statement in a variable
in a variable?
wdym "in a variable?
what?
might be time for a c# crashcourse
yeah i think your right
i realized that there different lines
@queen adder Lets take this slow
Rigidbody2D rb2d = heldObject.transform.GetComponent<Rigidbody2D>();
Get the component Rigidbody2D if it exists and place it in a variable rb2d
if (rb2d != null) rb2d.AddForce((mousePos - heldObject.position)*6f);
if the rb2d variable is not null (i.e. the rigidbody2d was found) execute the AddForce method against it
Clearer now?
yeah i think so
did you understood how mousePos got.
huh?
probably not
its also very wrong looking now that you point it out
what is the mousePos in steve example?.
And mouse position is described in what coordinate system ?
right vector3 point.
wait shouldnt it be vector2?
if you are using Orthographic camera you should 0 out the Z
or wherever your world objects are on Z pos, ideally 0
Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouseWorldPos.z = 0```
📃 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.
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
mousePos.z = 0;
oh
like this?
I mean yeah..but writing one line like I did is also valid
i know
perfectly valid code and if it aids comprehension all well and good
all to move a loaf of bread
I guess so
yeah, but the point is, the same code could move a mountain
Just be mindful of "just cause you can, doesn't mean you should " lol
Hey, at least you're not teleporting the bread.
as long as you understand it though steve is correct
hope you know this wont be the last time i have an issue
we're not new to the channel
yeah we are not new.
as long as you try to understand and learn, we don't mind
i do have a issue but ill worry about it in a bit
^ people dont mind helping as long as person shows interesting in learning and put effort into it
hey so i have a weapon and it rotates around my player and when the player attacks i want it to like jurt out like a punch then come back how would i do it so it goes straight out the way it is pointed not just in the same direction no matter what
uhhh apparently i have another issue. there's no errors and everything looks fine but the character doesnt even move, neither does the mouse look even work. i would think the script is not accessing the input actions properly but there are no errors, and everything is named correctly so what the heck is going on
use local direction instead of global
how do i do that
well
hard to say , you've been around long enough to know you should probably start with showing what code you have so far
typically you would use transform.forward for example instead of Vector3.forward
ok but how would i make it go forward a little then come back
like what values would i use
depends how you want it to come back, just reverse the speed or dir
idk what the conditions should be to come back
Guys i have this now when the plant is suddenly deleted ie shoveled the animation goes back to walking only after it finishes the eating animation not immediately
holy flashbang
!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.
check your transition settings
my main poroblem is if i just increase the x position then it would go to the same direction no matter what the rotation is wouldnt it
then you're not setting properly the direction, not sure what position has to do with it
what type of weapon is this?
a fist
why do you have collision != null? the method is called only because there is a collision . . .
EDIT: my mistake. i thought that was inside the trigger method. your bright screen confuses my eyes . . . 😎
thats my current set up the weapon parent part gets rotated
so you're talking about an animation ?
My wave spawner spawns the first wave and once theyre all dead it starts the second wave but no enemies spawn and after a few seconds it starts the 3rd wave because there were no enemies alive
well i was thinking about just using a animation but if i used that then colliders wouldnt follow it so i thought it would make more sense to use code to actually change the position of the fist
but it would look like a animation
well check the condition you have to spawn more enemies and see if it still detecting the old ones or something
i have the fist set up so it rotates around the player acording to the mouse location
changing position would be the same thing as animation
they both move the transforms
but here you can probably just do a simple lerp in the transform.right of the fist
might have to move the localPosition since its child of parent
then comes back
use like an overlap or boxcast for damage
animation would probably be the easiest
oh ok thanks i didnt realise that the animation would actually work i thought it would ignore the rotation and go the same direction no matter the rotation
yeah it is thanks
hey, I just started learning Unity days back and I have an issue, I made a 3D fps character and he just keeps rotating without me doing anything. Does anyone have a solution ?
not without !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.
the code is probably messy, I took some parts of it from different sites, I tried writing some other parts myself
this
transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
is causing your rotation.
but there is so much wrong with that code I would recommend !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
many thanks
do I just delete that line of code or start all over the camera system ?
tbh It looks like you do not understand a single line of code there, so I would start again
What is this, why did it appear out of nowhere just today and how do I get rid of it? 😅 🫠
What dont you understand? It seems pretty self explanatory to me
I recommend reading messages/errors/etc. first before coming here, it can help a lot
nah, reading? pah!
Wait, are you guys serious?
yes
You have one thing enabled, but not another that helps the first thing. So the first thing will not work like it should
Hope that clarifies it
ahhh can someone please help me on a project rq pleaseeee
Try reading this Unity Answers thread, it can help in your error
Okay, what is profiler and what is stable power state? Because I don't remember touching these
Did you google each term?
The profiler is a way to check what's going on in the game
Whether it'd be memory, etc.
what is the difference between having your phone plugged in to the charger and not?
why everytime i use Thread.Wait() it crashes unity
!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.
because you don't know how to use multi threading correctly?
Try sending us your code, maybe it'll help you
It CRASHES? As in the program closes?
Or it FREEZES?
Hello, this is not active in my unity, anyone know how to make it active ?
What is "this"?
well, it says that its busy, and then after a few minute it crashes
for 2d game that's the camera
but i dont have it
using UnityEngine;
using System.Collections;
using System.Threading;
public class BalloonSpawner : MonoBehaviour
{
public GameObject balloonPrefab;
public float minX = -10f;
public float maxX = 10f;
public int spawnInterval = 2;
IEnumerator SpawnBalloons()
{
while (true)
{
float randomX = Random.Range(minX, maxX);
Vector3 spawnPosition = new Vector3(randomX, transform.position.y, transform.position.z);
GameObject newBalloon = Instantiate(balloonPrefab, spawnPosition, Quaternion.identity);
yield return new WaitForSeconds(spawnInterval);
}
}
void Start()
{
StartCoroutine(SpawnBalloons());
}
}
Then create a camera
i already have it
Then what is the issue?
Okay, I really don't get why you guys have to be ganging up on me like this. I am a student of Computer Science at my uni and I will do my thesis in a few months. Right now I'm designing a game in a group of four for a module. It might be that you guys immediately know what a profiler and stable power state is in Unity and what it does but I don't. And English isn't my first language either.
oh yeah so the picture i send from a tuto not from my unity
Doesn't seem like a code problem btw
it just goes crazy spawning a bunch of balloons at once
So you want it to be orthographic? You gotta explain what you have and what you want. It is too vague so far
Is this the reason it crashes?
No one ganged up on you
Just google the words. It is a rule that you need to research the issue before coming here
#📖┃code-of-conduct
the Thread.Wait() was the reason it crashes, this one makes unity freeze because there is too much going on at once
Dawg if you study computer science I genuinely expected you to read messages and research for yourself before coming here.
Ohh wait lemme check it real quick, mobile layout sicks with the code thingy
wym?
The ballonspawner component is not on a balloon prefab, right?
oh uhh im still reading code is what i meant sorry
Also, where is thread.wait?
i removed it and changed it for yield return new WaitForSeconds
Are you referring to yield return new WaitForSeconds(spawnInterval?
hey I deleted most of my code : https://gdl.space/onucoyoqok.cpp my character keeps rotating any reason for that ?
what do you mean?
Gotcha. Yeah it would not have worked there
Is that script on the balloon you are spawning 🤷♂️
yes
It should not be
It should stay one one GO only
Every time you spawn a ballon it spawns another ballon which spawns another ballon
Going on forever
Basically stacking the effects
Until the game crashes
it stops eventually.
Ok. Well it quite obviously should not be on the balloon
It should be on a SINGLE object
where should i put it then?
On a GameObject that handles the instantiation
And empty gameobject that you name balloon spawner
Completely separate, and only have one ever
ohh because when it spawns a new balloon it also has that script which executes, going on and on
how would i do that then
Create an empty gameobject?
Right click in the hierarchy, go to create, select empty, drag the script onto it
- Make an empty gameobject in the scene
- Attatch the component there
got itt, it works now, thank you very much
How do i get started with the unity engine?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Do the pathways
Essentials and junior programmer at least
Avoid youtube
Consider https://www.w3schools.com/cs/index.php for pure c# lessons
So as I've seen the profiler can't be disabled, how do I enable stable power state then? I've tried googling it. Is it changing the windows registry?
As said before, it is a log, not an error or warning. You CAN ignore it
Does it go away if you click clear?
oof got another problem, the balloons doesnt spawn quick enough for another gameObject to be spawned resulting in an error because i cant access it as its been destroyed, either if i get all of the balloons quick enough, or if it goes off the screen which deletes the balloon
but it says "GPU timing errors are expected."
In the profiler
and I wouldn't want to run into these later
so id probably need a single balloon that will never get removed?
You need to make a prefab asset
And it appears everytime i open the project
- Play your video game
- Are there errors?
- If yes, research before asking
- If no, then ignore
The thing you're spawning should not exist in the scene
i have a prefab
Then how is it disappearing?