#💻┃code-beginner

1 messages · Page 77 of 1

willow breach
#

im doing a course on Udemy and there is something that don't make sense to me.
we created a weapon script https://gdl.space/azovihujol.cpp
and added dropped weapons from dead enemies (cool) but they are also moving and shooting even before I picked them up (it make sense since we didn't check anywhere in the code if the are equipped)
am I missing something?

topaz mortar
#

the next code snippit also doesn't work:

languid spire
#

Sorry, I read again, yes I think it's a typo in the method code

rich adder
topaz mortar
#

this stuff is so frustrating, I have no experience with this, there's no explanation, just a random code snippet that doesn't work, dunno where to put it, what to do with it, why it doesn't work, what it's purpose is ...

topaz mortar
gaunt ice
#

upper one

topaz mortar
#

ah gues the first lol

#

well at least all the errors are gone, let's see if it works lol

quiet pasture
#

Yo guys,im. Creating a card game and im using horizontal layout group,how can i make the cards in hand to have that curvy while still using hlg

frosty hound
#

You're going to be fighting against the layout group if you want to keep it only for the horizontal position.

But anyway, if you do, then you need to move the card as a child object of the parent that is controlled by the layout group.

You would offset the child position (vertically) and rotate it. The amount you would, would be a lerp between default position (no movement) to max movement based on how far from the center of the layout group the card is.

quiet pasture
#

Will i win the fight?

rich adder
willow breach
quiet pasture
topaz mortar
north walrus
#

Is it good practice to split FSM for character controller state and animation?

timber tide
#

Usually all that logic runs in parallel

#

the blend tree is basically a FSM machine anyway, but it's still useful for when you need to blend stuff together

topaz mortar
novel shoal
#

it’s not working

#

!code

eternal falconBOT
rich adder
novel shoal
rich adder
#

its kind of obnoxious

novel shoal
#

@rich adder

rich adder
rich adder
topaz mortar
#

not 3x but this symbol: `
3 times before and after -_-

willow breach
#

hey, I'm generating a new weapon with
Instantiate(weapon, transform.position, transform.rotation, transform);
but it seem that the components are not active
why is that?

rich adder
novel shoal
rich adder
#

dont matter dont use code blocks for large code @novel shoal

novel shoal
rich adder
#

fades away? nothing here fades anything

novel shoal
rich adder
#

also you do not use != on float numbers

willow breach
novel shoal
rich adder
#

well its wrong

novel shoal
#

okok

rich adder
amber spruce
#

right how do i do that

rich adder
soft flume
#

Hi... A question for all those Math lovers.. I have a sphere droid with different cannons around it (a cannon is a a child transform that looks outwards). What is the right formula to rotate it so a random cannon will face front?

willow breach
#

oh and the var is a prefub

rich adder
amber spruce
#

this?

rich adder
amber spruce
#

not really

verbal dome
#

@zenith acorn Don't DM me randomly, it's against the rules. Ask your questions here

willow breach
rich adder
#

Destroy(gameObject, lifeTime)

amber spruce
rich adder
rich adder
willow breach
rich adder
#

which runs automagically when object is destroyed

amber spruce
willow breach
rich adder
#

nothing much changes

amber spruce
#

this is my jump code

 rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
 isGrounded = false;
 animator.SetTrigger("Jump");
topaz mortar
#

Can someone please help me set up Steam login? None of the code on the docs page is working for me ... Been at it for 2 hours now ... 😭 #1177962063503573053

willow scroll
rich adder
amber spruce
#
 private IEnumerator BounceTowardPlayer()
 {
     while (true)
     {
         // Wait for a random duration before jumping again
         yield return new WaitForSeconds(Random.Range(0.1f, 0.5f));

         // Jump if the enemy is grounded
         if (isGrounded)
         {
             Jump();
         }
     }
 }
#

my enemy is a slime thing so i have it look like its bouncing

rich adder
willow scroll
#

then just rotate using a coroutine with lerp

verbal dome
#

Quaternion.FromToRotation can be useful here

willow scroll
#

each cannon will have their own target rotation

#

like (0, 0, 0), (90, 0, 0), (180, 0, 0) and (270, 0, 0)

verbal dome
#

Something like this could workcs List<Vector3> directions = /* list of directions corresponding to the cannons, in local space */ int index = Random.Range(0, directions.Count); // Random direction idex Vector3 dir = directions[index]; Quaternion lookRotation = Quaternion.LookRotation(enemyPosition - myPosition); lookRotation = Quaternion.FromToRotation(Vector3.forward, dir) * lookRotation;

#

Untested, might need to flip the last line

#

And yeah, using rotations instead of directions is an alternative like password123 said

willow scroll
#

I wonder if they want to find the nearest cannon to the enemy

#

this way the target rotation should be lookRotation - nearestCannonRotation

#

I suppose

soft flume
#

Thanks. I don't mind it not being the nearest cannon. I just tried so many calculations and it doesn't work right

#

I will try to play with the @verbal dome code and see. Thank you!

verbal dome
#

And the left & right side of the last line might have to be flipped, I forget how Quaternion multiplication order goes

simple forge
#

I'm trying to Instantiate a prefab of enemies but all enemies share a healthpool and i cant interact through C# with any particular instance, just the prefab itself.

timber tide
#

don't interact with the prefab itself

simple forge
#

well yes, but how would i do that ?

timber tide
#

You actually get the reference to the object when you instantiate it

#

store it somewhere safe

simple forge
#

im REALLY a beginner, no clue how to do that either

timber tide
#

You've written anything, specifically for instantiating those prefabs?

simple forge
#

yes

timber tide
#

post it

simple forge
#
using System.Collections;
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEngine;

public class Gameplay : MonoBehaviour
{
    public GameObject enemy;
    public GameObject enemyContainer;
    
    void Start()
    {
        enemy.GetComponent<EnemyHealthTracking>().health = 100;
        CreateEnemies(3);
    }

    void CreateEnemies(int enemy_amount)
    {
        for (int i = 0; i < enemy_amount; i++)
        {
            GameObject enemyClone = Instantiate(enemy, new Vector3(i, enemy.transform.position.y, i), enemy.transform.rotation);
            enemyClone.transform.parent = enemyContainer.transform;
            enemyClone.name = "Enemy" + (i+1);
        }
    }
}
timber tide
#
GameObject enemyClone = Instantiate(enemy, new Vector3(i, enemy.transform.position.y, i), enemy.transform.rotation);

Alright, so you do get the reference to the gameobject here

simple forge
#

so i just replace everything with that ?

#

well, what is referencing the enemy

timber tide
#

You don't actually store the reference is the problem, unless you're accessing it from elsewhere

#

How are you doing damage to the enemy. Can you post that?

simple forge
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyHealthTracking : MonoBehaviour
{
    public int health = 100;
    public void TakeDamage(int damage_ammount)
    {
        health = health - damage_ammount;
        Debug.Log(health);
        if (health <= 0)
        {
            this.gameObject.SetActive(false);
        }
    }
    
}

#

it wouldnt let me delete it since i was trying to delete the prefab thats why its disabling it instead

timber tide
#

So, your prefab has this component on it, yeah?

simple forge
#

yes

timber tide
#

Now, what method are you using to grab that specific gameobject instance that's now on the scene.

#

collider detection, casting, ect

simple forge
#

raycasting yes

azure zenith
#

I have seen people use lerp speed for a health bar, is it necessary to use it?

timber tide
simple forge
#
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using StarterAssets;
using UnityEngine;
using UnityEngine.InputSystem;

public class Take_Damage_Enemy : MonoBehaviour
{
    
    public EnemyHealthTracking enemyHealthTracking;
    public StarterAssetsInputs starterAssetsInputs;
    void Start()
    {
        this.gameObject.SetActive(true);
    }
    public void DealDamage()
    {
        Debug.Log("yes");
        RaycastHit hit;
        Ray ray = Camera.main.ViewportPointToRay(new Vector3 (0.5f, 0.5f, 0));
        if (Physics.Raycast(ray, out hit))
        {
            Debug.Log("no");
            enemyHealthTracking.TakeDamage(20);
        }
    }
}

dry tendon
#

Heey, does anyone knows how can i export terrain textures on a jpg to apply them to a plane? 🧐

timber tide
simple forge
#

what should i implement instead ?

timber tide
#
if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
{
    if (hit.collider.CompareTag("Enemy"))
    {
        EnemyHealthTracking enemy = hit.collider.gameObject.GetComponent<EnemyHealthTracking>();

        Debug.Log("Enemy hit is: " + enemy.name);
    }
}```
#

something like that

#

I suggest layers instead of tags though

#

which you should watch tutorials of

#

But to clarify what I'm doing here is I grab info from the hit and check if these gameobjects of these colliders have this class type instance (their hp class)

simple forge
#

thank you for the help, while you were typing that up i found a solution on the forum since i knew what to look for

#

i found this on a forum

timber tide
#

yeah, there's a lot of info out there for this stuff

simple forge
#

yeah, ive been looking for a while but didnt know what to look for exactly

#

Thanks

timber tide
#

should remove this too:

public EnemyHealthTracking enemyHealthTracking;```
as you shouldnt need to store a 'single' instance of your enemy here
#

you'll get their instances/references on demand from the cast

lone sable
#

Is it possible to have a script run on a de-activated game object at all? As strange as that sounds.

timber tide
#

de-activated should just stop update and other unity methods

simple forge
lone sable
#

Yeah thats the problem I suppose.

#

Was hoping there was like a [AlwaysExecute] type thing.

#

Specifically, the problem I'm trying to solve is that, sometimes, when modifying the UI, I'll disable objects that need to be re-enabled.

#

And I'll forget lol. So, was hoping to just toss a script on them.

timber tide
#

if you need like coroutines to run, you can make like a singleton manager that re-enables the UI objects

#

I do something similar

willow scroll
timber tide
#

Oh, do coroutines still run? I thought they didn't.

willow scroll
timber tide
#

my coroutine manager too sweet to remove though ;)

steel pier
#

I have a script where when i left click a gameobjects follows my mous movement. but wenn the size is negativ you cant see the gameobject

timber tide
#

because you're flipping it

#

and it's backface culling the quad

steel pier
#

How could i fix it ?

willow scroll
#

so you don't have to remove your sweet coroutine manager

timber tide
willow scroll
#

could you, please, show your code?

#

basically you have to abs your GameObject's size

eternal falconBOT
steel pier
#
        Vector2 size = mousePos - initialMousePosition;
        selectionBorder.GetComponent<RectTransform>().sizeDelta = new Vector2(size.x, size.y);
        Vector2 checkScale = new Vector2(size.x, size.y);
        selectionBorder.GetComponent<RectTransform>().anchoredPosition = (mousePos + initialMousePosition) / 2f;
timber tide
#

"You can’t have a rectangle with negative dimensions.
What you need to do is create a rectangle that has positive dimensions starting from the point where your mouse is to the point where the drag operation started.
Basically, when your mouse X and / or Y are negative you will be redrawing the rectangle FROM CURRENT location of your mouse pointer to the START OF DRAG location.
In cases when they are positive then the logic stays as you have it since your are drawing the rectangle FROM START OF DRAG location TO CURRENT mouse position."

#
#

If I were to do it I'd just draw my own quad honestly

willow scroll
#

please, note that it'll work just if both of your pivot is exactly (.5, .5)

#

if you need to change your pivots for some reason, you'll have to implement additional logic

willow scroll
steel pier
#

yes

willow scroll
#

you should also store your RectTransform as a variable

#

and checkScale is redundant

willow scroll
#

"Just make your sizeDelta to be always positive and multiply the anchoredPosition according to the pivot"

#

That's how you change your anchoredPosition regardless of the pivot

offset.x *= _stretch.x == 0 ? 0 : pivot.x + (_stretch.x > 0 ? 0 : -1);
offset.y *= _stretch.y == 0 ? 0 : pivot.y + (_stretch.y > 0 ? 0 : -1);

rect.anchoredPosition += offset;
#

where offset if the difference between previous and new sizeDelta and _stretch the direction

#

@steel pier in case you want to change the pivot

steel pier
#

ok thanks

novel shoal
#

getaxis horizontal gets the arrows or the “a” and “d” keys

willow scroll
polar acorn
willow scroll
polar acorn
willow scroll
#

I see, nice

amber spruce
simple forge
#

Hey, having an issue where this hit.transform.SendMessage("Hit", weapon_Tracker.weaponDamage[weapon_Tracker.currentWeapon]); is supposed to return "Hit", int 20, but it returns 2[TKey,TValue].get_Item

#

when typing in "pistol" which is the key for the value 20, it works just fine

wintry quarry
high bronze
#

I was wondering if i could get some help with a small problem i am having, this script works great but the GameObject's in the Array are all being set to false when I press "E" on one of the objects which is not what i want to happen. Any help is greatly appriciated.

Thanks from Mplu3s. <33

simple forge
wintry quarry
wintry quarry
#

hit.transform is already the specific object you want

dry tendon
#

Heey, does anyone knows if is there any way to export terrain textures?

high bronze
wintry quarry
simple forge
wintry quarry
amber spruce
#

they just move on the x axis

wintry quarry
#

Use GetComponent

#

Then call the function on the component

simple forge
#

it wont let me, or im doing it wrong

wintry quarry
#

Definitely the latter

simple forge
#

how should i do it ?

wintry quarry
#

Call GetComponent on the object to get a reference to the component.
Then call your function on that reference

#

What does "it won't let me" mean

simple forge
#

my function is in another script

wintry quarry
#

Obviously

#

If you're having trouble with syntax you should share the code you tried and whatever errors you might be getting

simple forge
wintry quarry
#

Ok what's the issue here?

#

Looks alright so far

simple forge
#

the function in the other script wont show up

summer stump
wintry quarry
#

What function are you expecting to show up

#

show code

simple forge
tight cove
#

HeyHo;

simple forge
wintry quarry
#

Show what you mean

#

What you typed above made little sense

#

Just looked like the ToString output from the dictionary or something

simple forge
#
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.InputSystem.Interactions;

public class Weapon_Tracker : MonoBehaviour
{
    public Dictionary<string, int> weaponDamage = new Dictionary<string, int>()
    {
        {"pistol", 20},
        {"rifle", 35}
    };
    public string currentWeapon;
    void Start()
    {
        EquipPistol();
    }
    public void EquipPistol()
    {
        currentWeapon = "pistol";
    }
    public void EquipRifle()
    {
        currentWeapon = "rifle";
    }

}

tight cove
#

Is there a way to reference/set a fixed Sprite in an Scriptable Object?
so that I don´t need to referenc it by draging the sprite in the field, when ever I create a new "instanc" of that SO?

wintry quarry
wintry quarry
simple forge
tight cove
simple forge
#

im telling it to go to the dictionary and input "pistol"

wintry quarry
#

Where are you seeing a weird result

wintry quarry
simple forge
#

one second

#

then it throws this

wintry quarry
#

The key "" isn't in the dictionary

#

Looks like you tried to pass an empty string in

wintry quarry
#

Start happens very late

tight cove
simple forge
#

still the same thing happens

wintry quarry
#

Do what I said

#

Put it in Awake

#

It will work

#

BTW this whole question was very confusing. You should have just shared this code and your error message from the start

#

Likewise you can set it in the inspector and it will work too

simple forge
wintry quarry
#

Why did you move the variable declaration

#

All you had to do was rename Start to Awake

wintry quarry
simple forge
#

ok

#

alright

#

thank you

#

sorry for the trouble

#

well nevermind, i had manually put in "pistol" to test it, putting the dictionary back, it throws the same error

willow scroll
# simple forge

you cannot access a local varible (a variable that's created in the method) outside of this method

simple forge
#

yeah i fixed thta

willow scroll
#

also you cannot use an unassigned local string

tough lagoon
#

I'm just going to say, some beginner C# is really a must

#

But show the error

willow scroll
simple forge
#

well, this isnt a passion project i can put down for 2 months

simple forge
tough lagoon
#

Well getting other people to write it for you isn't teaching you either #justsaying

willow scroll
tough lagoon
#

Ok, can you just show the whole thing?

simple forge
#
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.InputSystem.Interactions;

public class Weapon_Tracker : MonoBehaviour
{
    public Dictionary<string, int> weaponDamage = new Dictionary<string, int>()
    {
        {"pistol", 20},
        {"rifle", 35}
    };
    public string currentWeapon;
    void Awake()
    {
        EquipPistol();
    }
    public void EquipPistol()
    {
        currentWeapon = "pistol";
    }
    public void EquipRifle()
    {
        currentWeapon = "rifle";
    }

}

#
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using StarterAssets;
using UnityEditor;
using UnityEngine;
using UnityEngine.InputSystem;

public class Take_Damage_Enemy : MonoBehaviour
{
    public Weapon_Tracker weapon_Tracker;
    void Start()
    {
        this.gameObject.SetActive(true);
        Debug.Log(weapon_Tracker.weaponDamage[weapon_Tracker.currentWeapon]);
    }
    public void DealDamage()
    {
        RaycastHit hit;
        Ray ray = Camera.main.ViewportPointToRay(new Vector3 (0.5f, 0.5f, 0));
        if (Physics.Raycast(ray, out hit))
        {
            hit.transform.GetComponent<EnemyHealthTracking>().Hit(weapon_Tracker.weaponDamage[weapon_Tracker.currentWeapon]);
        }
    }
}

tough lagoon
#

Although that error would happen at runtime, and is caused by whatever is requesting it

willow scroll
#

I'm not sure if you've written it by yourself, actually

simple forge
#

it does also happen at runtime

sterile radish
#

how do i reference a script from a scriptable object?

willow scroll
simple forge
#

cus i dont know how to do a raycast

sterile radish
simple forge
#

or.. i didnt

languid gate
#

Not sure if this a code question but does anyone know why my tilemap might be bugging out and causing these lines?

willow scroll
# sterile radish wdym

the referecing in ScriptableObjects should happen the same way as in normal scripts, I suppose

tough lagoon
high bronze
eternal falconBOT
tough lagoon
sterile radish
high bronze
tough lagoon
willow scroll
#

the problem isn't in ScriptableObjects

high bronze
sterile radish
#

ohhh right

simple forge
#

its set to pistol by default

#

as its supposed to be

tough lagoon
#

Right now it's just a script just whenever you press E it disables them all

sterile radish
high bronze
#

yeh so when the cameras box collider is in the object it puts them all to false

languid gate
#

does anyone know where i could get help with fixing my camera

tough lagoon
#

I'd start by writing down exactly what you expect to happen.

I.e. click on X
X is highlighted
Press E to disable etc

And then break it down from there.

#

Right now I have no real idea how your project is structured or how you want it to work, so I can't really advise. If this is one script, or many scripts, attached to the doorknob, or all doorknobs. Why is there an array? Etc

willow scroll
willow scroll
high bronze
languid gate
#

and they issue persists across diffrent cameras engines

tough lagoon
sterile radish
languid gate
#

5 i think

sterile radish
#

try making it -10

#

i thinm that's what causing the issue

tough lagoon
#

If it's a shared script, you need to tell it what was clicked on. If it's a singular script on each doorknob, an array isn't needed and it could just directly disable whatever itself. But then pressing E is running on all copies of the script anyway, so you keep a bool to tell which one is active

languid gate
#

thats not the issue ill send a pic

#

if u open pic up u can see render lines

willow scroll
high bronze
#

the script is on the player, i thought an array would be an easier way of managing things then having each doorbell having its own script

willow scroll
languid gate
#

yeah

#

i can send tile map but they shouldnt apear

willow scroll
languid gate
unreal imp
#

Guyssssss, does anyone know what the code is like for the typical fps movement? Is it that I deleted it by mistake and I don't remember what it was like?

tough lagoon
#

Ideally you'll probably want something more generic and reusable, so it checks not just doorbells but all intractable objects within reach

willow scroll
languid gate
#

how could tilemap cause issues tho and its only upon chaning the camera postion

#

like when camera is static they dont apear

unreal imp
willow scroll
languid gate
cinder plover
willow scroll
unreal imp
#

Also don't they have a clearer code on how to grab Half Life 2 style objects? 😫

willow scroll
willow scroll
#

Do you want to switch the weapons?

languid spire
lament silo
#

could anyone help?

cinder plover
unreal imp
#

the fps movement

willow scroll
willow scroll
cinder plover
willow scroll
eager elm
cinder plover
#

I tried that, but when i after i insantiate it, it doesnt become a child correctly, the rigid body doesnt want to get disabled, and it always spawns in the wrong position

lament silo
willow scroll
cinder plover
willow scroll
#

you should either use Transform.SetParent(Transform parent) or the the last Instantiate() parameter

cinder plover
#

cuz that went horribly wrong

willow scroll
eager elm
# lament silo yea im seeking better ways of doing this

a better way would probably to not destroy the viewer each time, and instead change the sprite or model or whatever and disable it when no item is selected. If you don't want to do that you pull the stuff inside your if statement outside and Destroy the viewer inside the if statement

cinder plover
willow scroll
cinder plover
willow scroll
unreal phoenix
#

Does anyone know the max float size of a Keyframe tangent?

slender nymph
cinder plover
#

Made it work ty <3

#

SpawnedRocket.GetComponent<Rigidbody>().isKinematic = true; btw

languid spire
#

!code @unreal imp

eternal falconBOT
unreal imp
#

oh i forget it,sorry

#

Guys I have a problem and it is that when I want to apply my jump code the player not only can't jump but he can't walk, any solution? Here the link: https://gdl.space/otiwaxehey.cs

willow scroll
unreal imp
willow scroll
unreal imp
#

😫

cinder plover
#

This may be a dumb question, but can i add a script to the prefab, which will be spawned later (Rocket)

languid spire
#

yes, of course

cinder plover
#

Ok ty

wintry quarry
languid spire
# unreal imp you too?

looks to me that you should be debugging verticalVelocity and seeing what you set it to

#

tbh, when I see scripts posted and there is not a single Debug.Log in them it makes me think 'this person has done nothing to solve the problem themselves'

unreal imp
#

I always forget that I can do Debug.log

languid spire
#

you forget too much and too often

unreal imp
#

I think you gave me an idea 😉

vast vessel
#

Heavy weapons guy tf2?!?!

languid gate
#

does anyone know why this code allows players to clip though walls slightly ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
public Rigidbody2D rb;
public float moveSpeed;
public Vector2 forceToApply;
public Vector2 PlayerInput;
public float forceDamping;

void Update()
{
    PlayerInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized;
}

void FixedUpdate()
{
    MovePlayer();
}

void MovePlayer()
{
    Vector2 moveForce = PlayerInput * moveSpeed;
    moveForce += forceToApply;
    forceToApply /= forceDamping;

    if (Mathf.Abs(forceToApply.x) <= 0.01f && Mathf.Abs(forceToApply.y) <= 0.01f)
    {
        forceToApply = Vector2.zero;
    }

    rb.velocity = moveForce;
}

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.collider.CompareTag("Wall"))
    {
        // Reverse the player's velocity to prevent passing through the wall
        rb.velocity = -rb.velocity;
    }

    //        if (collision.collider.CompareTag("Bullet"))
    //       {
    //            forceToApply += new Vector2(-20, 0);
    //            Destroy(collision.gameObject);
    //        }
}

}

unreal imp
languid spire
#

another one !code

eternal falconBOT
cinder plover
#

Another dumb question like before, is it possible to reference a already existing game object in a prefab

languid spire
#

no

vast vessel
#

Nope

languid spire
#

only another prefab

cinder plover
#

Shit

vast vessel
#

Maybe set up a game manager that has the refrance to that object

#

Then get it in the Start method on your prefab

#

So basically when the prefab is created it asks for the game manager for the refrence

cinder plover
#

Ill try it ty

frosty lantern
#

So I am importing 2dgamekit into my project and I need to know what each of these settings do so I know whether or not to let them override my project settings.
When i don't give them override permission, the textures of moving background objects and perticle effects get reduced to pink polygons. when i give them full access, i lose access to the layer dropdown in my inspector. do you guys have a brief overview of what each asset does so I can figure out if i want to import it? even like a link to the documentation or something?

amber spruce
#

hey so im still struggaling with this how do i have my enemy ai move only on the x axis because i have them able to jump and i want them to be able to move when they jump but right now if the player is above them they start flying to the player i dont want that but they still should be able to jump so i cant just lock the y axis
here is my enemyai script https://pastebin.com/QvYibAfP

eager elm
cinder plover
vast vessel
#

Yes

cinder plover
# vast vessel Yes

But if the rocket cant reference the rpg, why would it be able to reference game manager

eager elm
vast vessel
cinder plover
#

So i want to disable the colision betwen them

vast vessel
#

Well i dont see why that would need a refrance

eager elm
vast vessel
#

Use physics collision layers

#

Put your rpg on one layer, like "player", put the rocket on another layer like "projectile". Then disable the collision between them in project settings>physics

amber spruce
#

well right now they dont but they cant jump

quick ruin
#

Is there code for 2D to determine if a sprite is in game view

wintry quarry
eager elm
amber spruce
quick ruin
unreal imp
quick ruin
#

ill try onbecomeinvisible ty 🙂

amber spruce
eager elm
amber spruce
unreal imp
eager elm
eager elm
amber spruce
#

which line is that?

eager elm
#

in the code you posted, you need to remove line 38 and uncomment the next 4 lines, then it should work

amber spruce
#

yeah with that the enemy cant jump

#

it will play the jump animation but if they are moving they dont jump

eager elm
#

ye, but thats the problem of your Move() and Jump() functions

amber spruce
#

it is?

languid gate
lament silo
#

what is happening ```cs
[SerializeField] private GameObject[] items;

private void Start()
{
foreach (GameObject item in items)
{
GameObject newItem = Instantiate(item, itemHolder);
newItem.SetActive(false);
}
}

eager elm
# amber spruce it is?

I think so. I think the problem is that your enemy isn't grounded and thats why he doesn't jump? Try adding a Debug.Log("Jump"); inside your jump method

languid gate
#

also samething happens with this code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody2D rb;
    public float moveSpeed;
    public Vector2 PlayerInput;

    void Update()
    {
        PlayerInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized;
    }

    void FixedUpdate()
    {
        Vector2 moveForce = PlayerInput * moveSpeed;

        rb.velocity = moveForce;
    }

}

``` and its like super simple so idk how the wall pushes back
#

could it have anything todo with the type of collider i am using?

eager elm
languid gate
#

its not very noticeable but i can send video if u want

#

it just triggers me cause i cant un see it now

amber spruce
languid gate
eager elm
amber spruce
#

yep they jump now

bitter canyon
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class startGameEasy : MonoBehaviour
{
    public string LevelName;

    public void LoadLevel()
    {
        SceneManager.LoadScene(LevelName);
    }
}```
anybody know why the only option im getting is monoscript here?
eager elm
eager elm
# languid gate

ye that shouldn't be happening, I would also recommend changing your collider to multiple box colliders

amber spruce
languid spire
young pine
#

does anyone have a good starter game idea for well beginners?

languid gate
#

still happens with box collider

languid spire
#

there was a question there

bitter canyon
#

oh im blind

#

sorry

bitter canyon
#

i dragged the script onto a button

eager elm
languid spire
#

need to drag a gameobject containing the script

bitter canyon
#

oh ok ty

languid gate
#

should i just re do my movement or smt

bitter canyon
#

yeah that worked thx

eager elm
frosty lantern
#

why doesn't unity have a copy paste system? like I can't copy paste scenes or assets without going back into the file explorer

eager elm
frosty lantern
#

oh so they use ctrl d instead of c and v

young pine
#

im at a loss of ideas atm

frosty lantern
#

mildly annoying but much better than what i was doing tysm

frosty lantern
bitter canyon
young pine
#

ooo ty

eager elm
# languid gate bounce

mhh that is strange, do you need physics for your player other then colliding with walls?

languid gate
#

i use triggers for collisions but other then that no

eager elm
languid gate
#

isnt that bad practice tho

#

i might just re write the movement script or smt

lament silo
eager elm
languid gate
#

ok ill try it

eager elm
lament silo
#

works as intended

#

oh wait i think i know why

wintry quarry
lament silo
#

yeah it was ondisable method

#
foreach (Transform item in itemHolder)
        {
            ResourceItem resourceItem = item.GetComponent<ResourceItem>();
            IEquippable tool = item.GetComponent<IEquippable>();

            if (selectedItem != null && selectedItem.id == resourceItem.item.id)
            {
                item.gameObject.SetActive(true);
                tool.Equip(itemHolder);
            }
            else
            {
                item.gameObject.SetActive(false);
                tool.Unequip();
            }
        }
```does this seem good enough
frosty lantern
eager elm
#

Assets -> Export Project, or manually by using File explorer

languid spire
#

ffs !code

eternal falconBOT
simple forge
#

i dont know why, but it wont pass the currentWeapon == "pistol" check

languid spire
simple forge
#

the inspector says pistol

#

the code seems to disagree

eager elm
#

do you ever call getDamageValue()?

languid spire
#

screenshot inspector

simple forge
simple forge
#

i see my console outputting damageValue and enemy health, but not "pistol"

#

even though it should

languid spire
simple forge
eager elm
#

well, you learn a lot of valueable things here, one of which is that string comparisons are error prone.

simple forge
#

well i tried with a dictionary, that went even worse

languid spire
#

yes, try changing it to an enum, much better

eager elm
simple forge
#

rn all i want is for this to work

languid spire
#
public enum WeaponType {
pistol, rifle
}
bitter canyon
#

how do i make the easy mode method not be overrid by the defonition at the start

eager elm
#

write: Debug.Log(currentWeapon + " - " + "pistol" + " - " + (currentWeapon == "pistol");

#

and paste the result here

eager elm
simple forge
bitter canyon
#

when i run it im getting it as 1 so ill check the method

rare basin
#

it's such a bad idea

simple forge
#

ill probably restart tmrw to fix it all

#

just learning rn

eager elm
# simple forge

looks like currentWeapon is null. Do you maybe have two of the scripts in your scene?

bitter canyon
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class startGameEasy : MonoBehaviour
{
    public EnemySpawner EnemySpawnerReference;
    public string LevelName;

    public void LoadLevel()
    {
        SceneManager.LoadScene(LevelName);
        EnemySpawnerReference.EasyMode();
    }
}``` this should be calling the method when loading the scene  right
rare basin
rare basin
#

it will be called

simple forge
bitter canyon
#

then i dont know why the value isnt changing to 1.5

rare basin
simple forge
eager elm
bitter canyon
#

i have it in a "loader"

#

i think thats what you call it

rare basin
#

show me

#

where do you call this function

bitter canyon
rare basin
#

again, show me where do you call this function

eager elm
#

he posted it above

rare basin
#

thats function definition

#

but where do you call it

#

it has 0 references

bitter canyon
rare basin
#

you made a function, but you are not using it anywhere

vast vessel
bitter canyon
rare basin
eager elm
# bitter canyon i have it in a "loader"

I don't know what a "loader" is? If you want to change a value from one scene to another you can use static variables:

public static spawnRate;

Then you can change it from any script without needing a reference:

EnemySpawner.spawnRate = 1.5f;

rare basin
#

that is not a good approach

bitter canyon
#

oh

vast vessel
#

What about a game manager?

rare basin
#

use a singleton, or store the spawnRate data in scriptable objects for example

eager elm
#

that's a fine approach for something like that

rare basin
#

so you can have different spawn Rate for each level

#

easily

bitter canyon
#

well theres only one level

#

i need to rename those

rare basin
#

sure but what if you want to add more levels in the future

bitter canyon
#

i dont

rare basin
#

ok xd

bitter canyon
#

its not that type of game

rare basin
#

make a DifficultyManager (singleton), set the difficulty whenever you want (store it as enum for example EASY, HARD) then in the spawner in Start() set the spawnRate based on the difficulty from the manager

vast vessel
#

Just use a singleton. Plus, you will probably need a game manager singleton script later down the road for other things

bitter canyon
#

whats a singleton?

#

i just see that it means it only creates one instance of itself

rare basin
eternal needle
eager elm
#

Singletons stink, just make the spawnRate static

rare basin
#

i've worked on many AA projects

#

in every we've used a singleton

eager elm
#

Singletons are just static variables with extra steps

vast vessel
#

Bruv didnt even know what a singleton was a second ago and is now saying singletons stink

simple forge
#

ok, ive figured something out, the currentWeapon becomes null every click

#

i dont know why

#

i never set the currentWeapon value because of a click

rare basin
#

they have 2 different use cases you cant really compare them

elder dove
#

am i dense? why does this fire 3 times instead of one? assuming the error is with my input, im using default button input mapped to left click

rare basin
elder dove
rare basin
#

probably all 3 states triggered

#

started, performed, canceled

elder dove
#

ah i see so should I put it on started or performed?

rare basin
#

you might need to check only for started for example

#

if(context.started) ...

elder dove
#

cool cool

#

thank yu

simple forge
rare basin
#

well, for now you just need to learn basics of C# before you start learning the API

simple forge
#

i dont really have the time for that

elder dove
#

im at the point where i can't type C# because I don't know the specifics of the syntax but can read and understand it bc i know python and C lmaooo

rare basin
elder dove
#

making for a miserable experience

elder dove
#

not knowing C# or basic programming will make making anything of any consequence impossible

simple forge
#

oh ik a good bit of Lua, im not coming into this blind

#

atleast not fully

rare basin
#

still, don't throw yourself in the deep waters

#

learn C# basics

#

then learn Unity API in depth

elder dove
simple forge
#

no

elder dove
#

hmm whyd you learn lua?

eager elm
#

DotA, maybe

rich adder
#

Gmod

vast vessel
#

Garrysmod? Teardown? GtaSa?

simple forge
elder dove
rare basin
#

lol scripts

rich adder
vast vessel
#

Uses of lua(out side of modding games):

.

elder dove
#

world of warcraft addons

simple forge
elder dove
simple forge
#

i learned python before lua

elder dove
#

lua syntax is wack af too

languid spire
#

enough off topic guys

elder dove
#

isnt string concatination like .. instead of +

#

my b

eternal needle
dense root
#

What's an example of a time you would not set a box collider to a trigger but still use a collider?

frosty hound
#

A wall

dense root
#

How about a wall in pong? Same deal?

rich adder
#

anything solid

frosty hound
#

Yes? If you want it to be solid

rare basin
#

if you set to trigger, the ball will just dont collide with the collider

eager elm
dense root
#

@rare basin Huh? I thought it would still collide

rare basin
rich adder
#

triggers aren't solid

rich adder
#

you only get OnTriggerEnter/Exit etc. callbacks

languid spire
dense root
#

Ahh

#

That makes sense

#

So report something back to me if you get hit

#

So if we use the Pong example then the wall without a trigger would just collide but not report back

languid spire
#

no, a collider which is not a trigger will report and stop

vast vessel
#

Whenever something hits your collider, this runs

dense root
#

So in the case of pong I would want the player and ball to be triggers but not the walls, right?

rich adder
simple forge
#

alright i found out where my currentWeapon gets deleted, idk what to do with that info tbh

rich adder
#

the only thing that would be a trigger in pong would be the Goal scoring area

dense root
#

Ahh gotcha

simple forge
vast vessel
#

Via script

rich adder
#

i usually use Vector3.Reflect for pong clones

dense root
#

How many times have you remade pong? 😲

vast vessel
rich adder
dense root
#

Woah

#

So I guess when learning you're going to remake the same game over and over

rich adder
#

sometimes I do it for jams

dense root
#

Like drawing, re-draw the same thing till it's right, come back to it

#

Ohhh

rich adder
#

with different mechanics to add variation

languid spire
#

Yes and even worse, there is literally only a handful of people whos advice is actually useful instead of complete nonsense

languid gate
quiet pasture
#

Any way a changing the y value of child within a horizontal layout group by script?

bitter canyon
#

How do i make a button run a method?

languid gate
rich adder
bitter canyon
#

oh

#

that makes a lot of sense

rich adder
#

Inspector or code, either one

bitter canyon
#

what do i put under here tho

rich adder
#

it would show up

bitter canyon
#

oh

quiet pasture
rich adder
quiet pasture
#

When u sayd inspector or code i thought You were talkin to me,my baad

bitter canyon
#

oh wait how do i choose what scene is opened first

dense root
#

What's the advantage of using Visual Studio of VS Code for scripting in Unity?

#

It's sooo slow to load up

rich adder
bitter canyon
#

ty

rich adder
dense root
#

Oh gotcha

languid spire
rich adder
#

Debugger alone is worth 100%

#

although vscode is slowly catching up. maybe in 2 years its caught up

dense root
#

I've heard some controversial statements about debuggers, like they don't work in larger projects sometimes

eternal needle
#

Lots of people have asked in here why their vscode suddenly stopped working, while for VS I've rarely seen it asked

eternal needle
# dense root It's sooo slow to load up

As for the load time, if your computer is really old then I can see this being an issue... but it's a one time issue. You arent opening and closing it multiple times per coding session

dense root
#

I've got a new machine, it's just compared VS code is what I meant

rich adder
#

I mean yea a text editor is always gonna startup faster than an IDE 😆

dense root
#

right

#

thank you

elder dove
azure zenith
#

Need help

#

Tag me if you can help

dense root
#

Do any of you use a "library" of scripts? Like you keep old scripts for reference in later projects.

wintry quarry
#

Lots of them

dense root
#

What's your best tip/tool for organizing them? Gist?

rich adder
dense root
#

Gotcha

dense root
#

Me too

rich adder
#

thats unhelpful to anyone

#

whats wrong with it

#

so where is the code part of this

eager elm
dense root
#

For some reason my paddle is moving both left and right players... any thought?

public class Paddle : MonoBehaviour
{
    public bool isPlayer1;

    public float speed;
    public Rigidbody2D rb;

    private float movement;

    // Update is called once per frame
    void Update()
    {
        if (isPlayer1)
        {
            movement = Input.GetAxisRaw("Vertical");
        }
        else
        {
            movement = Input.GetAxisRaw("Vertical2");
        }

        rb.velocity = new Vector2(rb.velocity.x, movement * speed);
    }
}
#

Player2 moves individually when I just press up and down but when I just move Player1 with the W and S keys it moves both players

#

I found it

slender nymph
#

sounds like your Vertical2 axis also uses W and S

dense root
#

Yeah

#

Funny how typing out the problem exactly you can sometimes findd the answer yourself hahahaha

wintry quarry
dense root
#

How come my headers aren't displaying in my GameManager?

#

Oh whoops I have errors

#

So my ball is just dropping here upon play... any thoughts on where I went wrong?

#

Physics material seems set correctly

#

Gravity scale is set to 0

keen dew
#

The rigidbody's X position is frozen

dense root
#

Right... any idea what's causing the freeze?

keen dew
#

The tick you've applied to it

dense root
#

Oh

#

Hmm it moves in the X direction but then sticks to the floor

gilded flame
#

!vscode

eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

keen dew
dense root
#

Now the issue is that it bounces the paddle.. weird

#

RigidBodies seems correctly set

gilded flame
keen dew
#

For the paddles you do need to freeze the rotation and X position

gilded flame
#

Yes that too 😄

dense root
#

That did the trick thank you @keen dew

eternal needle
#

You may want kinematic instead of freeze position. Freezing the position can kinda mess with the collision, at least I've had issues with it. Objects think they can go further than they should into a frozen object

gilded flame
dense root
#

@eternal needle with kinematic the paddles then go through the upper and lower walls

gilded flame
#

Do those walls have static rigid bodies?

dense root
#

No, just box colliders

#

Do I add a static rigid body?

gilded flame
#

Yes, add static rigid bodies and the paddles should not go through. Fingers crossed

dense root
#

Added rigidbodies and no dice

#

And the player Inspector for reference

gilded flame
#

The docs say "Enabling Full Kinematic Contacts enables a Kinematic Rigidbody 2D to collide with all Rigidbody 2D Body Types. This is similar to the behavior of a Dynamic Rigidbody 2D, except the Kinematic Rigidbody 2D is not moved by the physics system when contacting another Rigidbody 2D. Instead, it behaves like an immovable object with infinite mass."

dense root
#

Even with full kinematic contacts it still goes through

gilded flame
#

Let's see... how you are moving the paddles in your script? Are you adding/removing velocity? Or directly translating the position? Were the paddles being prevented from going outside the walls when its body was dynamic?

dense root
#

rb.velocity = new Vector2(rb.velocity.x, movement * speed);

#

Yes, velocity

#

I'm gonna stick with Dynamic for now

gilded flame
#

Okay... at the very least freeze the Z rotation

formal escarp
#

I have an odd error when i collect coins guys. not sure how to fix it. when i collect coin number 1, it sounds correctly. I have a different empty object with an audio source for coin 2, but when you grab coin 2 it sounds both the sound of coin 1 and coin 2.

abstract finch
#

How would you be able to deal with the list being modified while this loop is running?

   {
       while (Receivers.Count > 0 )
       {
           yield return new WaitForSeconds(_attackInterval);
           var receiver = transform.GetClosestReceiver(Receivers.ToArray());
           _actionHandler.Shoot(_shotOrigin.position, receiver.GetTransform().position - _shotOrigin.position);
       }
   }```
Its erroring out when receivers turn to 0
i tried adding a null check on Receiver[0] as well still same issue
formal escarp
#

nvm i cant fix shit

#

When i click to change the animation, it does. but when i play the game it goes back to the animation i dont want em to do. Not sure what im doing wrong

gilded flame
formal escarp
#

So they all play the same up and down, rotation animation.

icy panther
#

is there any way to change my materials texture from urp to built-in

lament silo
wanton canyon
verbal dome
#

And rotating it with transform

wanton canyon
#

What should I do instead?

verbal dome
#

Show the inspector of your rigidbody?

wanton canyon
verbal dome
#

Constraints too

wanton canyon
verbal dome
#

In any case, you shouldn't mix transform and rigidbody

#

Try rb.rotation instead

dense root
#

What's causing this Object reference not set to an instance of an object error?

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.CompareTag("Ball"))
    {
        if (!isPlayer1Goal)
        {
            Debug.Log("Player 2 Scored...");
            GameObject.Find("GameManager").GetComponent<GameManager>().Player2Scored();
        }
        else
        {
            Debug.Log("Player 1 Scored...");
            GameObject.Find("GameManager").GetComponent<GameManager>().Player1Scored();
        }
    }
}
#

Did I incorrectly tag something?

#

if tag look for player 1 or player 2 goal, if goal set game manager component to 1 or 2 score

keen dew
#

The object's name is Game Manager, not GameManager

#

shouldn't use Find anyway

dense root
#

What's the better method?

keen dew
#

Typically the game manager is a singleton so that you can refer to it directly

#

or in simple cases, make a serialized field and drag the object there like with everything else

dense root
#

Out of curiosity what's wrong with .Find?

keen dew
#

Well for one, you can very easily typo the name as you found out

dense root
#

lol

keen dew
#

it's slow, unreliable and you've now committed to never changing the object's name

dense root
#

Alright let me see what I can do

frosty lantern
#

I'm trying to add actions to my condition script but they aren't given as options

#

drag and drop won't work either

cosmic dagger
frosty lantern
#

how do i do that?

#

i can't drop it in the scene

cosmic dagger
#

Is Action an SO or MonoBehaviour?

frosty lantern
#

idk what an so is, the action script is built in the playground urp package

verbal dome
#

Or am I looking at it the wrong way

frosty lantern
verbal dome
cosmic dagger
frosty lantern
#

i'm testing moving unitytech to directly sub assets folder

verbal dome
#

Looks like it tries to find UnityTechnologies in the assets folder, so yeah make sure it's there

frosty lantern
#

always the stupidly obvious solutions that i can't seem to figure out that just happen to work

#

thanks

formal escarp
#

hey guys is to too hard to put credits on the game?

#

or a video?

verbal dome
cosmic dagger
slender nymph
cosmic dagger
frosty lantern
#

it's hard to understand half of the console errors an they usually bring me to the scripts that i know nada about

formal escarp
red prairie
#

i have 2 problems. 1 is making the gun not point to the the mouse while moving, prolly camera. the other one is that when i go in bewtween gun and the player it will go the opposite way. these two combined make this game practically unplayable.

#

wait

#

got more images

#

click on the image and press left or right

#

idk what went wrong

verbal dome
#

Lol why aren't the other embeds showing

#

The PointTo script seems fine to me

red prairie
#

exactly

#

look at the video

#

like i said. click on the image. and then the arrows

verbal dome
#

I understand, just wondering why the thumbnails don't show

red prairie
#

dunno. doesnt matter currently.

dense root
#

Alright! Got it going thank you all for the debugging help :)

verbal dome
#

I'm unfamiliar with cinemachine, but try changing that Update to LateUpdate in case it's an execution order issue @red prairie

#

Or make sure that your code runs after cinemachine in the execution order settings

red prairie
#

its even worse. idk

slender nymph
red prairie
#

which problem?

slender nymph
#

when i go in bewtween gun and the player it will go the opposite way

red prairie
verbal dome
#

Yep, better use the character's position in the direction calculation instead of the gun's position

red prairie
#

r u reffering to this line of code?

verbal dome
#

Yes

#

Use player's transform, not gun's transform

red prairie
#

that works.

#

just spawns from the player which is kinda wierd.

#

what about the other problem. i tried setting one to eairly update. and cinamchine to late

verbal dome
dense root
#

Anyone know what is causing the following error?

UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
red prairie
#

yes i used the players transform

verbal dome
dense root
#

Oh alright, thank you

verbal dome
red prairie
#

yes but how do i use the players transform for the bullet?

#

they r the exact same for both transforms

verbal dome
#

Or do the logic on the player object and reference the gun

#

Maybe it's best if you show what you just changed

red prairie
#

that still doesnt solve the issue of it not pointing to the mouse

#

all i changed was the position of the transform

verbal dome
#

Show your current PointTo script

red prairie
#

late update makes it worse

verbal dome
#

I just told you to use the player's transform instead of the PointTo object's transform here

#

Isn't the PointTo object on the child object?

red prairie
#

yes.

verbal dome
#

@red prairie Vector2 direction = mousePosition - playerTransform.position

red prairie
verbal dome
red prairie
#

kk

verbal dome
red prairie
#

mb.

weary moss
#

so, i have a player object, it has a sliding() coroutine, in which it deactivates the main hitbox and activates the lower body object, which has its own, adjusted hitbox. I tried using a normal sliding() function, but making a timer for it doesn't work, as it will run entirely in the frame it was called. Is it a good idea to make a separate script for the lower body?

summer stump
eternal falconBOT
weary moss
# summer stump There is a lot to unpack. Probably best to just show your !code
public IEnumerator escorregar()
{
   //setting everything for the slide
    escorregando = true;
    hitbox.enabled = false;
    corpobaixo.SetActive(true);
    animador.SetBool("Escorregar", true);
  //duration of the slide
    yield return new WaitForSeconds(2);
  //deactivating the animation, starting a transition in the           animator window
    animador.SetBool("Escorregar", false);
  //duration the transition should be
    yield return new WaitForSeconds(0.5f);

    corpobaixo.SetActive(false);
    escorregando = false;
    nada();
}

the variables may be a little weird bc they aren't in english
nada() is a function that sets everything back to normal

summer stump
weary moss
#

no, what runs immediatly is if i make it a function, the problem with this one is that there is a period of time after everything ends that the player doesn't do anything, like it doesn't accept any input

verbal dome
#

Also make sure to start the coroutine with StartCoroutine(escorregar())

#

Instead of escorregar()

weary moss
#

i'm calling it correctly

summer stump
rare basin
#

i absolutely hate writing code in native language

#

why not just english, especially when you are sharing this code in public discord

weary moss
#

i didn't plan to share it here, i'm together with another guy writing this, making the variables in native language helps me, and the other guy understand it better

summer stump
weary moss
#

i know it's hard for other people to understand the code without the whole context, so don't stress over it, i'll try a bunch of possible solutions here and report back if any of them worked

eternal needle
# weary moss i know it's hard for other people to understand the code without the whole conte...

I dont think its an issue of not understanding the code (ideally use a code site and paste more context so we can see what type each thing is), but that what you're describing doesnt make a whole lot of sense. if you called the coroutine properly, it shouldnt be running all in the same frame. I think maybe you have more code which is causing issues instead, you should add Debug.Log in your coroutine to see all of this doesnt happen right away

summer stump
rare basin
#

english is the most common to write in code, if he ever wants to find a job he will need to adapt, i doubt there is a single company (serious company) in the world writing code in native language

summer stump
unreal imp
#

Guys, does anyone know why my bullets don't have the same rotation as the gun or the muzzle? var bullet1 = Instantiate(bullet, muzzle.transform.position, Quaternion.identity); bullet1.GetComponent<Rigidbody>().velocity = (targetPoint - muzzle.transform.position).normalized * shootForce;

slender nymph
#

pass the rotation of the object you want it to have the same rotation as instead of Quaternion.identity which is no rotation

unreal imp
#

ahhhhh

#

i know

#

thx

twin bolt
#

How would i go by checking whether the player is using controller or keyboard. Would i have to add every controller and keyboard binding to their own scheme in the input system?

quasi rose
twin bolt
quasi rose
# twin bolt Okay, i'll try searching for that.

I recall it was in one of their example scenes like when you create a new project and they come with a controller. There was a ternary line in there that checked if it was a keyboard or not. Might have been Keyboard.current

twin bolt
quasi rose
#

yup

twin bolt
#

Okay i'll try that

quasi rose
#

Looks like it's Keyboard.current and Gamepad.current

#

Could probably create some Action with that for when switching between controller/keyboard too.

twin bolt
#

I think, if the keyboard and gamepad is connected at all, then both bools will be true, i want to check what input device is sending input currently. @quasi rose

quasi rose
#

But I think current would work if you got creative with the bools and events, idk. You could track which one last had input and then update your UI or whatever you need based on an event.

amber spruce
#

how do i assign player to this in code

#

would i do smth like this ```csharp
target = GameObject.FindGameObjectWithTag("Player").transform;

quasi rose
amber spruce
#

i am

subtle kelp
#

hey guys

amber spruce
subtle kelp
#

Im new with unity and I need some help

eternal needle
subtle kelp
#

Im tryna make a game for our class project and I cant seem to activate my key

#

im stuck here

eternal needle
subtle kelp
#

okay sorry, Im new here bro

amber spruce
eternal needle
amber spruce
#

so could you explain how to have it set to it

#

not sure how to do either of the things you are talking about

twin bolt
#

Why does this work when i'm navigating through my scene, but if i pause my game, it flickers back and forth between the two bools? https://hastebin.com/share/samiqujixi.rust

timber tide
#

nothing here shows you're pausing the game

twin bolt
#

I know, this is the only code in my game that sets the bools.

#

Everything else, checks those bools.

timber tide
#

Yes but I don't know where these methods statements are located in. Methods? Update? Events?

eternal needle
# amber spruce so could you explain how to have it set to it

It all depends on how the player exists in the first place. If it's just in the scene already then dragging it in is fine. If something is spawning it, you get the object returned from instantiate and plug that into any object that wants the player. Or you use the singleton pattern (google it for unity) and access it via a static field

amber spruce
#

so the enemy is spawned in

twin bolt
# timber tide nothing here shows you're pausing the game

I think i found the culprit, In the Gamecontrols.GamePlay.Mouse.WasPressedThisFrame() it checks for input from a mouse, but i have a virtual mouse in my game, which i think is triggering it. WHich is why its flickering. How can i fix this?

timber tide
#

Still haven't answered the question

#

Are you checking through update or through events

twin bolt
#

Update

timber tide
#

If you're pausing the game, your timescale should prevent these types of updates, no?

twin bolt
#

Oh, i didnt know that.

#

Where should i move it then?

timber tide
#

I mean, there's a few ways about pausing. One is using timescale, and the other is separating game logical updates from input.

#

Actually, I don't think the event system does pause. You may be correct if you're using timescale

#

In that case you may want to add a boolean in your update (if paused then skip this input)

twin bolt
#

I ended up fixing it by using Input.getAxis instead of the new inputsystem, that detects even virtual mice. Also Time.deltaTime isnt affecting my code.

amber spruce
#

anyone know how i can check if there are no objects with a tag (trying to check if there are no enemys left before new wave)

timber tide
#

I'm just not a fan of using timescale, but if you're using rigidbodies I'd assume you are required to use it.

#

otherwise just manually disabling updates on the game logic is my solution

twin bolt
#

Thank you

rich adder
#

only on removal of enemy from list is check how many left in list

amber spruce
#

cant a list not be emtpy though

#

bro im so mad rn i just lost so much progress cause unity crashed

rich adder
amber spruce
#

aight thanks

#

bro my unity crashed again

#

it keeps crashing

rich adder
#

what kind of crash? file a bug report

amber spruce
#

it just starts not responding i dont get a error message

rich adder
#

so is it after you hit play?

amber spruce
#

yeah it plays for a few then crahses

#

it seems to happen once 5 of my enemies spawn

rich adder
#

infinite loop probably

#

what did you do to your code

amber spruce
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemySpawner : MonoBehaviour
{
    public GameObject enemyPrefab; // Reference to your enemy prefab
    public Transform[] spawnPoints; // Array of spawn points
    public float numberofenemies;
    public int numberOfEnemiesInWave = 5;
    public float timeBetweenEnemies = 1.0f;
    public float timeBetweenWaves = 5.0f;

    private void Start()
    {
        // Start spawning waves
        StartCoroutine(SpawnWaves());
    }
    

    IEnumerator SpawnWaves()
    {
        while (true) // Infinite loop for continuous spawning
        {
            if (numberofenemies == 0f)
            {
            yield return new WaitForSeconds(timeBetweenWaves); // Wait between waves

            for (int i = 0; i < numberOfEnemiesInWave; i++)
            {
                SpawnEnemy();
                yield return new WaitForSeconds(timeBetweenEnemies); // Wait between enemies in the wave
            }
        }
        }
    }

    void SpawnEnemy()
    {
        // Randomly choose a spawn point
        Transform spawnPoint = spawnPoints[Random.Range(0, spawnPoints.Length)];

        // Instantiate the enemy at the chosen spawn point
        Instantiate(enemyPrefab, spawnPoint.position, spawnPoint.rotation);
        numberofenemies++;
    }
}

thats the code i changed i believe

#

i dont think i changed anything else

rich adder
#

also this is a bad way to do this anyway

#

again you should just keep track wit a list

#

Instantiate returns the enemy spawned

amber spruce
rich adder
amber spruce
#

anywhere or at the end or smth

rich adder
amber spruce
#

works now thanks

rocky basalt
#

Does x > 0 returning false imply x <= 0, or ONLY x < 0?

#

x is a float

tacit estuary
rocky basalt
#

Thanks

amber spruce
# rich adder inside the while loop

also any idea why this barely launches the enemy but when they are above me it launches them super high

void LaunchTargets()
{
    // Find all objects with the specified tags within the specified radius
    foreach (string tag in targetTags)
    {
        Collider2D[] targets = Physics2D.OverlapCircleAll(transform.position, affectRadius, LayerMask.GetMask(tag));

        // Launch each target that is not the current object
        foreach (Collider2D target in targets)
        {
            if (target.gameObject != gameObject)
            {
                Rigidbody2D targetRb = target.GetComponent<Rigidbody2D>();

                if (targetRb != null)
                {
                    // Calculate the direction from the launcher to the target
                    Vector2 launchDirection = target.transform.position - transform.position;

                    // Apply force to launch the target
                    targetRb.AddForce(launchDirection.normalized * launchForce, ForceMode2D.Impulse);
                }
            }
        }
    }
}
#

i have tried setting launch fordce higher doesnt fix much

thin carbon
#

Hi friends!
I'm using this line in attempt to basically find the net angle of input if that makes any sense:

Mathf.Atan2((Input.GetAxis("Vertical"),Input.GetAxis("Horizontal"))) * Mathf.Rad2Deg

But unity disallows me stating:
" CS7036 There is no argument given that corresponds to the required formal parameter 'x' of 'Mathf.Atan2(float, float)" "
Does anyone know how to make it accept my values?

verbal dome
#

So it thinks you are giving it just one variable, more specifically a tuple (float, float)

thin carbon
#

All that time wasted to such a silly mistake!

#

I never would of caught it myself, thx a lot for the help 🫶

dense root
#

How do I measure something in Unity? For example if I wanted to replace the paddles how would I know what size?

#

Like if I wanted to replace them with custom sprites I made in Aseprite, how would I know what size?

slender sinew
#

Go to the scene view and turn on the grid. Each unit grid cell is one unit, and you can decide how many pixels that should be.

#

If those are just squares that you scaled, you can also just check the scale

dense root
#

Oh I see so just judge based on the scale