#💻┃code-beginner

1 messages · Page 362 of 1

swift crag
#

in that case, putting the yield first means that stunRemaining will stay at length until the next fixed update

#

doing it the other way around would mean taht stunRemaining immediately drops to length - 1

timid oriole
#

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

swift crag
#

i just suggested a method name

#

instead of asking the spam machine to generate code for you, consider using the material on !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

timid oriole
#

also did ws school too on top of my electrical theory class my brain is kinda fried atm LOL

stuck palm
#

how do i sort this out?

polar acorn
stuck palm
#

thanks

slender nymph
#

or just make the length parameter a float instead of an int

deft grail
stuck palm
swift crag
#

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

young fossil
#

are the C# keywords such as async and await supported?

torpid snow
#

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

swift crag
#

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

open locust
#

Hey all! God some rather odd questions that have been driving me crazy!

swift crag
#

I do not know much about that library, though

open locust
#

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.

swift crag
#

this is not a server for discussing game modding

timid oriole
#

why lmao

open locust
#

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.

swift crag
#

you're asking how to run code without being able to run code

#

this is challenging

open locust
#

I wouldn't have come to ask if I wasn't stumped.

young fossil
timid oriole
#

aint no way that's begginer thats some nex tgenius shit

#

how to code without coding god damn yall smart

swift crag
swift crag
#

hey, it's point #2!

open locust
#

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

swift crag
#

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.

young fossil
swift crag
open locust
#

I'd go to the game modding specific forum but this question has been consistently referred over to unity experts

timid oriole
#

wait

#

are u creating a hack engine

#

fun

open locust
#

No, I can explain exactly what Im doing actually

timid oriole
#

its something dirty aint it

#

yuck

open locust
#

So, its for a game unturned(bully me all you'd like) but specifically to create Air to air missiles

young fossil
# open locust This is all I need

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

torpid snow
open locust
swift crag
#

call it isFacingLeft, maybe

torpid snow
#

right, but how would i actually change the animation loop?

swift crag
timid oriole
#

does unity have a vc channel

swift crag
#

there would be some duplicated work, though

young fossil
swift crag
#

you'd have two states for each of your original states

open locust
#

Basically I have:

  1. The missile which is just a projectile that has a trigger, trigger enters colider, boom. Hardcoded
  2. 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

torpid snow
#

Please explain it stupider :C

open locust
#

I'd be easier anyways

swift crag
#

the problem simply does not exist when you are developing a game. you write code to do what you need to do.

open locust
#

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.

young fossil
timid oriole
#

I mean it really ain't that deep to be such a stickler of rules tbh

fickle plume
timid oriole
#

if someone wants to help the guy just dm him

#

cuz apparently u can get banned here

open locust
#

If anyone would call or just take a look I'd be massively appreciative.

summer stump
open locust
#

But my question is purely unity specific

fickle plume
#

@open locust Enough already.

torpid snow
timid oriole
open locust
#

Okay just let me know where to take it then.

summer stump
summer stump
young fossil
#

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

timid oriole
#

Burning bubbles they gonna get the discord mod meeting on u!?!?!

#

What will you do!

open locust
#

Same thing as before? I literally just need someone who knows unitys ins and outs more than I do.

young fossil
open locust
#

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

fickle plume
#

!mute 227255921561174018 1d Ignoring warnings.

eternal falconBOT
#

dynoSuccess burning_bubbles was muted.

timid oriole
#

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

fickle plume
timid oriole
#

You are right I can

#

and

#

I will

#

I'm mr respctful

fickle plume
#

!mute 1126560790028238848 3d Off-topic, trolling

eternal falconBOT
#

dynoSuccess nicholas_004 was muted.

polar acorn
#

Hey now they got three days to figure out which part of the if statement goes inside the parenthesis at least

young fossil
#

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?

slender nymph
#

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

torpid snow
#

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

deft grail
#

then just make the bool true or false

#

based on direction

#

thats it

torpid snow
#

Let me look some stuff up, thanks

young fossil
swift crag
slender nymph
#

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

swift crag
young fossil
#

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

slender nymph
slender nymph
young fossil
#

Trying to think of a use-case that takes advantage of the async aspect and more control of the task cancellation

bold saffron
#

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.

young fossil
#

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?)

slender nymph
#

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

young fossil
#

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

young fossil
young fossil
#

(ping me if you respond to any of my messages anyone, just brb)

bold saffron
teal viper
bold saffron
#

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...

teal viper
bold saffron
teal viper
#

Never remove the debug related code when asking for help. It could help a lot to understand the issue.

bold saffron
#

oooooh wait

#

I just realised

#

When I did this:
if (_SettingsTab.transform.position.x == 0) { Debug.Log("Settings0"); }
It never send a message

teal viper
#

Okay, then it never arrives at 0

rich adder
bold saffron
#

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

rich adder
rich adder
bold saffron
teal viper
#

A very small number

rich adder
bold saffron
#

oh ok

#

👍

stuck palm
#

why cant i use MoveVector.x?

#

i know it says why

#

but like

#

what can i change to fix this?

teal viper
stuck palm
summer stump
#

Ah, yeah the screenshot says it is. So yes

stuck palm
#

okay

#

thanks

#

MoveVector = new Vector2(launchSpeed * curveMultiplier, MoveVector.y);

doing this seems to multiply it massively and idk why

real falcon
#

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"

teal viper
#

Just store the position of the last several frames and find the average.🤷‍♂️

real falcon
#

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?

teal viper
#

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.

teal viper
#

A measure of how much the object is moving

real falcon
real falcon
#

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

real falcon
#

compared to moving in a straight line

teal viper
real falcon
real falcon
#

going in a cirlce would have high average velocity

#

even though your average position over a few seconds isnt moving at all

teal viper
teal viper
teal viper
#

In ideal situation it would be 0

real falcon
#

ok so you mean the actual vector not just the average "speed"

teal viper
#

Yes, velocity != Speed

real falcon
#

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?

teal viper
#

Sure, you can

real falcon
#

like each group of components

teal viper
#

That's the same thing

#

In the end you get an average velocity vector

real falcon
#

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

teal viper
#

Yep

#

Though it depends on how often you sample it and how many samples you average.

real falcon
#

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

teal viper
#

This kind of stuff really needs to be tested and backed up with visual debug info to adjust it properly.

real falcon
#

I suppose

#

I think I was overthinking it though, thanks

wide rivet
#

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;
    }

}
deft grail
#

do you want it to press w > move up the amount that you hold w for or press w > move up + 1 or something

wide rivet
deft grail
#

basically like any normal movement

wide rivet
#

yes

deft grail
#

then scrap all this code

wide rivet
#

it only moves when holding down key

deft grail
#

and move it via the Rigidbody2D which you probably need to add and reference

tacit sand
#

my camera code is not working because in 'Physics.Linecast' have a error idk what is that error and idk how solve he

summer stump
eternal falconBOT
velvet mango
#

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)

summer stump
#

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

eternal needle
tacit sand
#

The only problem i having is that in Physics.Linecast it is giving an error, not finding anything, this error here CS0117

eternal needle
#

you should show the error, no one remembers the codes

summer stump
#

That is the most crucial thing to tell us

velvet mango
# eternal needle what do you mean use the ID outside and inside the prefab? this part doesnt real...

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

ivory bobcat
#

Create a public or private-serialized field and drag the other object into that field from the inspector.

velvet mango
#

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?

ivory bobcat
#

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.

velvet mango
#

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

ivory bobcat
#

Where do you call instantiate?

eternal needle
#

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

velvet mango
#

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

eternal needle
#

They likely have some list of current players then

velvet mango
#

not sure if this is doing it but

eternal needle
velvet mango
#

i think i found it

eternal needle
#

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

velvet mango
#

looks like there is a Param called playerIndex

#

found the JoinPlayer Function

summer stump
amber spruce
#

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

amber spruce
#

aight bet thanks

summer stump
#

What happens if you want an enemy that has health?

summer stump
#

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

amber spruce
#

also whats the thing for serializing a private variable again its [SerializeField] right

amber spruce
#

aight thanks

velvet mango
#

So i found where i can see the reference in inspector

gentle stratus
#
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
pallid kite
#

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?

rich adder
#

hope that made sense

gentle stratus
#

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

rich adder
gentle stratus
#

how do i adapt the current code from overlapsphere to overlapspherenonalloc

#

cause it wants a collider[] results

rich adder
#

yeah you need to make the array at the class level and assign a quantity

#

you want to pre-allocate

gentle stratus
#

ic

#

wait if its a dictionary what would the values be for the keys

rich adder
#

the original material, though you might not even need that now

gentle stratus
#

yeah i was thinking it could just be a list

rich adder
#

if they have the same materials

gentle stratus
#

they do

#

giving an error fsr

rich adder
#

use a Hashset instead of list

rich adder
gentle stratus
#

oh

#

only an int?

#

i forgot to read that part

rich adder
#

yeah since now they are stored in a colliders array you made

gentle stratus
#

oh ok i see now

#

it stores in colliders and returns that int

rich adder
#

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];
}```
velvet mango
#

i really need help trying to figure out how i would access playerInput in pic2 and where the instantiation happens is pic1

gentle stratus
#

do i loop through the hashset every time i update to check the colliders

rich adder
gentle stratus
#

two loops in hashset?

rich adder
#

one for hashset and other for adding the new colliders hit

gentle stratus
#

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
inner gulch
#

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

summer stump
#

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)

inner gulch
inner gulch
#

ill try a firing bool tho, might make more sense for some reason

summer stump
#

You probably want to set coStart to false at the end of the coroutine itself.

#

After the loop ends

inner gulch
#

is there a way to do that

gentle stratus
#

yeah the changing material works but the changing back doesnt

inner gulch
#

huh

#

im not following

gentle stratus
#

i was responding to navarone

inner gulch
#

oh ok

summer stump
rich adder
# gentle stratus yeah the changing material works but the changing back doesnt

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;
}```
summer stump
#

Set firing true in update

gentle stratus
#

i see

inner gulch
#

ive tried stuff like that

summer stump
#

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

inner gulch
#

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

inner gulch
summer stump
#
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;
  }
}
summer stump
#

But this is how you would stop a specific coroutine instance 👆

inner gulch
#

oh ok so that makes it so you can call it in all the methods and it carries between methods

gentle stratus
#

oh wait i can just check for null ig

inner gulch
#

my current problem is it starting about 1000 coroutines

#

ill look into a firing bool

summer stump
inner gulch
#

but couldnt I kinda do the same thing wiht my coStary

summer stump
inner gulch
#

yeah I did

#

what is fireWait

#

sorry im just trying to understand your code so I learn rather than just copying

summer stump
# inner gulch what is fireWait

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

gentle stratus
rich adder
#

I use GetComponent for writing quick in dc but you should ofc use TryGetComponent etc.

gentle stratus
#

i did cs if(t == null) { transforms.Remove(t); break; } before the if (!newColls.Contains(t)) {

inner gulch
inner gulch
#

because while true never ends

summer stump
#

Oh, I see

#

true true, the stop coroutine doesn't let the code finish iirc

#

Then yeah, one sec

summer stump
#

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);

inner gulch
#

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

inner gulch
summer stump
inner gulch
#

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

summer stump
inner gulch
#

its on the enemy itself yes

#

all the code

summer stump
#

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)

amber spruce
#

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

inner gulch
#

so I changed it to while(!coStart) (which is the same as coStart == false right) and now I get no output from the enemy

summer stump
inner gulch
#

but I can just change that

summer stump
#

that is why it needs to be while (coStart)

inner gulch
#

wouldnt that set off the loop while its not supposed to tho

#

also still no output from the enemy

summer stump
inner gulch
#

oh

#

that makes sense

summer stump
#

Still no output? Show the current code again

inner gulch
summer stump
#

you should add some debug logs. Log the values of distance in AI, and do one in the if(coStart == false) condition

dense root
#

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;
}
inner gulch
#

found it

#

miraculously one I removed the debug log from a completely unrelated script it started working

amber spruce
summer stump
inner gulch
#

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

summer stump
inner gulch
#

im thinking I could just make a little gap between the shooting and following range

summer stump
#

yeah, that could help too. Even just .1 difference

inner gulch
#

yeah thats what imma do

#

that fixed it

#

thanks for all the help you just saved me

velvet mango
#

anyone know how im meant to write this?

summer stump
#

you would write something like this:
PlayerInput input = GetPlayerByIndex(1);

velvet mango
#

🙏

stuck crest
#

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

summer stump
#

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

summer stump
#

Not your code

stuck crest
summer stump
# stuck crest um wdym

If you tell it to rotate, it will on any axis, despite locking an axis on the rigidbody

#

Ahhh

summer stump
#

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

stuck crest
#

ah

summer stump
#

Hard to say what's going wrong without seeing more. What is the rotation of the turret to begin with?

stuck crest
#

0,0,0

velvet mango
summer stump
stuck crest
#

im rotating the sphere tho

velvet mango
#

Typo I meant ==

summer stump
velvet mango
#

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

viral shadow
#

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 :/

polar acorn
#

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

viral shadow
#

stops at around 4~5

viral shadow
#

so how do I make it fade out?

polar acorn
#

Your spacing becomes 2 or less

polar acorn
viral shadow
#

this good?

#

wait one correction, this:
will this work?

viral shadow
polar acorn
#

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

viral shadow
#

OH I FORGOT THAT WAS THERE

#

thanks a lot

abstract finch
#

How would I be able to get this to work with Lists instead of arrays?

    {
        return array[UnityEngine.Random.Range(0, array.Length - 1)];
    }```
cosmic dagger
abstract finch
#

I'm trying to call the function and its not showing up so i figure its not working for arrays

cosmic dagger
#

how and where are you trying to call it? where does the method exist at?

abstract finch
#

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

cosmic dagger
#

also, you don't need Length - 1. for ints the max is exclusive . . .

abstract finch
#

alright

cosmic dagger
#

you call it from a list, but the method is an extension for an array. do you see the problem?

abstract finch
#

right so how can I change the function to support a list?

#

without converting the list to an array

cosmic dagger
#

you need to use/find a base collection type that accepts both a list and an array . . .

abstract finch
#
    {
        return list[Random.Range(0, list.Count)];
    }```
#

seems to be working now thanks

cosmic dagger
abstract finch
#

ill try icollection

cosmic dagger
#

does the array class derive from that?

abstract finch
#

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!

cosmic dagger
#

nice, there you go . . .

abstract finch
#

thanks that helped because I learned something new from it never used that before

flint thicket
#

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

gentle stratus
#
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
viral shadow
#

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.

abstract finch
#

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);
        }

    }
}``
topaz mortar
abstract finch
#

The icon next to it is blank as well as the script field

#

Even though its a monobheavior

topaz mortar
#

did you add the script in the editor?

#

you need to drag the gameobject with the script on it into that blank script box

abstract finch
#

ok ill try it once unity finishes reimporting

astral falcon
#

Do you have any errors probably?

abstract finch
#

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

topaz mortar
#

Something seems wrong with the TileRow script though, it's not supposed to look like that
there should be no Script at the top

abstract finch
#

yea

#

ok i did Reimport All and its gone now

astral falcon
#

Guess so, it was just not done with importing and handling the script for either error or meta issue

abstract finch
#

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

burnt vapor
#

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

abstract finch
#

alright

astral falcon
abstract finch
#

actually this is coming up as null

burnt vapor
#

I don't see the relevant code that sets tile

abstract finch
#

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.

abstract finch
astral falcon
#

edit test mode?

abstract finch
#

like clicking play on unity editor

astral falcon
#

So you hit play and it runs. You stop, hit play again and it breaks?

abstract finch
#

yep, it always works the first time

#

since the values arent persistent after exiting play i dont know why this is happening

astral falcon
#

So whats your full code doing. please use hastebin or something to show the full part.

abstract finch
#

alright , let me go through all the values in inspector first

#

the code is kind of messy atm

astral falcon
#

Also, as fusedqyou said, where is the variable tile being set

abstract finch
#
{
    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

astral falcon
#

So your code fixed itself by setting something to 1? I am scared of your code structure 😄

abstract finch
#

when i run into these things i restart unity

#

idk if this has anything to with it

astral falcon
#

(Experimental) might be prone to bugs 😉

abstract finch
#

yea its probably that

astral falcon
#

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

abstract finch
#

its really good though when you press play its instant

#

there are some ocassional bugs but i usually restart unity

astral falcon
#

Dont know your project size and working environment, but for me, those 3 seconds reloading are not a big hit.

abstract finch
#

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

astral falcon
ivory bobcat
abstract finch
#

small changes in code

#

debug logs

astral falcon
abstract finch
#

no i mean i have to stop playmode in order to test new code

#

recompile > wait a few seocnds before playmode starts up again

flint thicket
#

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

astral falcon
astral falcon
flint thicket
#

yah

topaz mortar
flint thicket
#

i did

#

i stuck now

astral falcon
#

So where is the code and what is not working

flint thicket
#

i dont think is a code problem

astral falcon
#

so why are you in code then asking for help?

flint thicket
#

is there link to show my code

astral falcon
#

!code

eternal falconBOT
flint thicket
#

what i have in the animator is "jumping" which is the main idle that has two blend tree "jump" and "fall"

viral shadow
eternal needle
# abstract finch no i mean i have to stop playmode in order to test new code

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.

abstract finch
#

most of the time im restarting play mode is related to debug logging

eternal needle
neon marlin
#

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

viral shadow
#

Maybe try getting the game object, remove from list, destroy then

keen dew
#

The list references the same gameobject but since it's been destroyed it acts like a null (for most practical purposes)

neon marlin
#

i see, thank u guys

eternal needle
# viral shadow Maybe try getting the game object, remove from list, destroy then

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.

teal viper
#

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.

hexed yoke
#

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.

teal viper
eternal needle
#

It's really a lot simpler in the 3rd option

teal viper
#

I guess there might be some cases where it's fine. Depends on the complexity of the project/system.

hexed yoke
teal viper
late burrow
#

if i make array which holds multiple same audioclips it uses up resources as just one?

languid spire
#

AudioClip is a class which is a reference type so your array does not 'hold audio clips' it holds references to audio clips

solar arrow
#

gameData = JsonUtility.FromJson<GameData>(fileContents);

what <> syntax means?

languid spire
#

that means you are supplying a generic type parameter, in this case GameData

willow scroll
# solar arrow gameData = JsonUtility.FromJson<GameData>(fileContents); what <> syntax means?
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));
solar arrow
#

i understand now

radiant frigate
#

is there any way to add a component to a gameobject after starting play time?

tough abyss
#

i have a wave spawner script but after i kill the first wave the second one fails to begin

frosty hound
#

Define fail?

tough abyss
frosty hound
#

Or rather, show how you are starting the next wave

tough abyss
#

when i kill first wave it should say wave completed but it doesnt

frosty hound
#

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.

cosmic dagger
#

is state set to SpawnState.Waiting? is EnemyIsAlive ever false?

tough abyss
#

does the ! before EnemyIsAlive mean is not alive

cosmic dagger
#

do you know what ! means? you placed it in your code . . .

tough abyss
#

i watched a brackey tutorial for it and from what i remember i think he said that but im not sure

tough abyss
#

so it gives the opposite value?

#

okok thank you

#

how would i write a debug log to check which state im in

polar acorn
cosmic dagger
errant pilot
#

Guys how can I force my game to run at a specific resolution at all times?

tough abyss
#

i am very new to code ive got a project to do for college for next week for been taught no code

cosmic dagger
tough abyss
#

u have been very helpful

cosmic dagger
#

!code

eternal falconBOT
orchid oyster
#

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);*/
     
  }
astral falcon
fossil drum
orchid oyster
radiant frigate
#

!code

eternal falconBOT
radiant frigate
#

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

tough abyss
#
    {
        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

astral falcon
tough abyss
#

i debugged the EnemyIsAlive and when all enemies are dead the variable is still set to true

astral falcon
# tough abyss

? Where do you set the state in your code? That is just a variable at the start of your script.

tough abyss
#

this i think

astral falcon
#

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?

tough abyss
#

once enemies are dead it changes back to spawning

#

but it doesnt detect when they die

summer stump
#

Show EnemyIsAlive()

radiant frigate
cosmic dagger
tough abyss
summer stump
tough abyss
summer stump
# tough abyss

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

tough abyss
#

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?

queen adder
#

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

eager wolf
#

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)

languid spire
#

&&

queen adder
#

o ty

polar acorn
eager wolf
languid spire
summer stump
tough abyss
tough abyss
summer stump
eager wolf
#

currently it looks like this

#

so i could always make a seperate one for the world

tough abyss
languid spire
rich adder
#

Use a generic make the saving more flexible

eager wolf
rich adder
#

also. Use Path.Combine don't be doing this stuff lol

tough abyss
#

is there any easy way to search for objects witha specific tag

eager wolf
rich adder
tough abyss
#

scene

languid spire
rich adder
queen adder
#

in my if statement i need to make sure the object has a rigidbody 2d how do i do that?

rich adder
#

var rb = GetComponent<Rigidbody2D>();
if(rb == null)
//no rigidbodyfound

queen adder
#

thanks

languid spire
mint seal
#

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

rich adder
mint seal
#

anyone willing to help

languid spire
rich adder
queen adder
#

eh im checking if it helps

rich adder
mint seal
#

how do i condense the words

eternal falconBOT
queen adder
rich adder
#

use liinks @mint seal

queen adder
#

i need the grabbed object to have a rb2d

#

but im figuring out how to check it

mint seal
#

does it work im dense

rich adder
#

how are you detecting it in the first place

queen adder
#

though a raycast hit

rich adder
mint seal
rich adder
#

do a TryGetComponent on that

queen adder
#

oh ok

#

hold on im a bit confused

#

where should i use that?

rich adder
#

send the video tutorial

rich adder
eager wolf
mint seal
#

im assuming it's outdated but im not sure what is

rich adder
mint seal
#

i have no idea what that is

#

input actions?

#

i did that correctly yes

rich adder
#

show the generated class you created

queen adder
mint seal
#

generated class of what?

rich adder
#

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

queen adder
#

i think i did that wrong

mint seal
#

oh my gosh

#

bro im so sorry im just really stupid...

rich adder
# queen adder https://gdl.space/okowehegup.cs

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);

mint seal
#

thanks so much dude didnt even know of that

#

youre a real one

queen adder
#

whats the issue there?

rich adder
#

its trying to access methods on a component that wasn't found

#

you gotta wrap those up inside an if statement

queen adder
#

thats what ive been trying to do

#

i just dont understand how

rich adder
#

what do you mean how ?

#

the same way you did it for the previous two

queen adder
#

im not sure what to put in the if statement

#

its given me errors

rich adder
#

how are you checking on raycast if a collider even exists ?

#

look carefully at your own code yes

queen adder
#

im not the greatest with code

rich adder
#

you should at very least attempt to understand what you wrote so far..

queen adder
#

ill look through it

rich adder
#

look the the if statement with the collider

languid spire
rich adder
#

or better yet TryGetComponent and skipp the null check

languid spire
queen adder
#

i hate to say it but im still pretty confused

rich adder
#

two spoon and it did not stick

languid spire
queen adder
#

why do we have a if statement in a variable

languid spire
#

in a variable?

rich adder
#

wdym "in a variable?

polar acorn
queen adder
#

hold on wait a minute

#

i think i figured it out

rich adder
#

might be time for a c# crashcourse

queen adder
queen adder
languid spire
#

@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?

queen adder
#

yeah i think so

glossy turtle
queen adder
#

huh?

rich adder
#

its also very wrong looking now that you point it out

glossy turtle
queen adder
#

the mouseposition?

#

its a point

#

right?

languid spire
glossy turtle
queen adder
#

wait shouldnt it be vector2?

rich adder
#

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```
queen adder
#

hold on how are you making it look like its from vs

#

!code

eternal falconBOT
deft grail
#

your using the wrong symbol thats all

#

` not '

queen adder
#
        mousePos = Input.mousePosition;
        mousePos = Camera.main.ScreenToWorldPoint(mousePos);
        mousePos.z = 0;
#

oh

rich adder
queen adder
#

i know

rich adder
#

what is even the point here lol mousePos = Input.mousePosition;

#

just use it directly

queen adder
#

dunno

#

okay

languid spire
#

perfectly valid code and if it aids comprehension all well and good

queen adder
#

all to move a loaf of bread

rich adder
#

I guess so

languid spire
rich adder
#

Just be mindful of "just cause you can, doesn't mean you should " lol

polar acorn
#

Hey, at least you're not teleporting the bread.

rich adder
#

as long as you understand it though steve is correct

queen adder
#

hope you know this wont be the last time i have an issue

rich adder
#

we're not new to the channel

glossy turtle
#

yeah we are not new.

languid spire
queen adder
#

i do have a issue but ill worry about it in a bit

rich adder
#

^ people dont mind helping as long as person shows interesting in learning and put effort into it

amber spruce
#

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

mint seal
#

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

rich adder
amber spruce
#

how do i do that

rich adder
#

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

amber spruce
#

ok but how would i make it go forward a little then come back

#

like what values would i use

rich adder
#

depends how you want it to come back, just reverse the speed or dir

#

idk what the conditions should be to come back

errant pilot
#

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

rich adder
#

holy flashbang

eternal falconBOT
slender nymph
amber spruce
rich adder
#

what type of weapon is this?

amber spruce
#

a fist

cosmic dagger
amber spruce
#

thats my current set up the weapon parent part gets rotated

rich adder
tough abyss
#

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

amber spruce
#

but it would look like a animation

rich adder
amber spruce
rich adder
#

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

amber spruce
#

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

dire trellis
#

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 ?

eternal falconBOT
dire trellis
#

the code is probably messy, I took some parts of it from different sites, I tried writing some other parts myself

languid spire
#

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

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

dire trellis
#

many thanks

#

do I just delete that line of code or start all over the camera system ?

languid spire
#

tbh It looks like you do not understand a single line of code there, so I would start again

dire trellis
#

true

#

👍

next vapor
#

What is this, why did it appear out of nowhere just today and how do I get rid of it? 😅 🫠

languid spire
#

What dont you understand? It seems pretty self explanatory to me

graceful crescent
#

I recommend reading messages/errors/etc. first before coming here, it can help a lot

languid spire
#

nah, reading? pah!

next vapor
#

Wait, are you guys serious?

languid spire
#

yes

summer stump
upper forge
#

ahhh can someone please help me on a project rq pleaseeee

summer stump
#

Note, it is a log, not an error

#

Not even a warning

next vapor
graceful crescent
languid spire
upper forge
#

why everytime i use Thread.Wait() it crashes unity

graceful crescent
#

!code

eternal falconBOT
languid spire
graceful crescent
summer stump
solemn dragon
#

Hello, this is not active in my unity, anyone know how to make it active ?

upper forge
solemn dragon
#

for 2d game that's the camera

solemn dragon
upper forge
# graceful crescent Try sending us your code, maybe it'll help you
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());
    }
}
summer stump
solemn dragon
#

i already have it

summer stump
next vapor
#

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.

solemn dragon
#

oh yeah so the picture i send from a tuto not from my unity

summer stump
#

Doesn't seem like a code problem btw

upper forge
summer stump
solemn dragon
#

yeah fr sorry

graceful crescent
summer stump
upper forge
graceful crescent
graceful crescent
summer stump
graceful crescent
summer stump
#

Also, where is thread.wait?

upper forge
graceful crescent
#

Are you referring to yield return new WaitForSeconds(spawnInterval?

dire trellis
upper forge
summer stump
summer stump
summer stump
upper forge
#

should it not be?

#

oh why

graceful crescent
#

It should stay one one GO only

summer stump
#

Every time you spawn a ballon it spawns another ballon which spawns another ballon

#

Going on forever

graceful crescent
#

Basically stacking the effects

summer stump
#

Until the game crashes

upper forge
#

it stops eventually.

summer stump
#

It should be on a SINGLE object

upper forge
graceful crescent
summer stump
upper forge
#

ohh because when it spawns a new balloon it also has that script which executes, going on and on

summer stump
#

Right click in the hierarchy, go to create, select empty, drag the script onto it

graceful crescent
upper forge
#

got itt, it works now, thank you very much

graceful crescent
#

No probs man

#

I hope your game goes amazingly

twin bloom
#

How do i get started with the unity engine?

summer stump
eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

summer stump
#

Do the pathways

#

Essentials and junior programmer at least

#

Avoid youtube

next vapor
summer stump
upper forge
#

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

next vapor
summer stump
next vapor
#

and I wouldn't want to run into these later

upper forge
summer stump
next vapor
#

And it appears everytime i open the project

graceful crescent
summer stump
#

The thing you're spawning should not exist in the scene

upper forge
summer stump