#💻┃code-beginner

1 messages · Page 262 of 1

tender stag
#

and maxForce is 50

#

ideally i want him to maybe bounce like 2 or 3 times

#

before hes just still

rocky canyon
#

now swimming?

#

jeez 😄

tender stag
#

yeah its coming along pretty good

#

almost finished

rich adder
#

🤿

tender stag
#

also i need to seperate my movement script into smaller scripts for each function like leaning crawling etc

#

cause its at 2032 lines

#

and im like 2/3 done

tulip hill
#

help, i'm doing a movement script and i tried making jumping possible, but when i press space the boolean for "isJumping" doesn't mark as true, help: ```csharp
using JetBrains.Annotations;
using System;
using System.Collections;
using System.Collections.Generic;
using TreeEditor;
using Unity.VisualScripting;
using UnityEditor.UI;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
public CharacterController control;
public Transform groundCheck;

public float speed = 12;
public float gravity = -9.81f;
public float checkDistance = 0.4f;
public float jumpForce;
public LayerMask groundMask;

Vector3 velocity;
public bool isGrounded;
public bool isJumping;

// Start is called before the first frame update
void Start()
{
    
}

// Update is called once per frame
void Update()
{
    isGrounded = Physics.CheckSphere(groundCheck.position, checkDistance, groundMask);
    
    if (isGrounded)
    {
        isJumping = false;
        Debug.Log("Grounded.");
    }

    if (isJumping)
    {
        isGrounded = false;
        velocity.y = jumpForce;
        isJumping = false;
    }

    

    if (isGrounded && velocity.y < 0)
    {
        velocity.y = -2f;
    }

    if (isGrounded && Input.GetKeyDown(KeyCode.Space))
    {
        isJumping = true;
    }

  

    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");

    Vector3 move = transform.right * x + transform.forward * z;

    control.Move(move*speed*Time.deltaTime);

    velocity.y += gravity * Time.deltaTime;
    control.Move(velocity * Time.deltaTime);

}

}

cosmic dagger
tender stag
#

its really advanced

#

at least for my current ability

tulip hill
#

nvm i think i see what happens

austere monolith
#

how can i*

tulip hill
#

how can i achieve goldensrc's movement mistakes in such a way to get bhopping?

#

like on hl1

rich adder
#

sure

tulip hill
#

nvm

cosmic dagger
low robin
tulip hill
#

thats where bunnyhopping comes from too

rich adder
#

bunnyhopping is well explained phenomenon

#

if you understand it you can replicate it

tulip hill
#

i dont understand it

rich adder
#

there are videos on this subject

#

also a few premade ones that floating around github

tulip hill
#

yeah i didnt think about that

#

also how do i check if a key is held?

#

not pressed

rich adder
#

Input.GetKey

tulip hill
#

damn

rich adder
# tulip hill yeah i didnt think about that

Explanation of how the player movement code in Quake gives rise to these three different player movement "bugs", with a quick look at TAS movement mechanics at the end.

Big thanks to the Quake Speedrunning Discord for helping me out with getting TASQuake running on my machine, and for clarifying terminology.

Here are the original C versions of...

▶ Play video
silk night
# tender stag its really advanced

hmm i cant really find a good solution out of the top of my head other than hard-setting the y velocity once you reach the top + hold the up key 😄

thorn tapir
#
heldItem = Instantiate(slots[currentSlot].GetComponent<InventorySlot>().slotItem.GetComponent<Item>().heldItemPrefab, heldItemLocation);

why is this line throwing this error? It looks fine to me, but it seemingly has an issue with how I'm using GetComponent

silk night
#

what is slotItem?

thorn tapir
#

a gameobject

silk night
#

make sure its not null or destroyed

#

oh wait, it looks like your usings at the top import the wrong stuff

#

is there anything in there about visual scripting?

thorn tapir
#

yeah, which I'm not using

silk night
#

then throw it out

thorn tapir
#

idk why that's in there

silk night
#

its overriding your GetComponent

thorn tapir
#

I was wondering why it wouldn't let me directly reference my prefab

#

ty

violet topaz
#

How would i be able to assign more then one gameobject to this script ```cs
public class PlayerInteractUI : MonoBehaviour
{
[SerializeField] private GameObject containerGameObject;
[SerializeField] private PlayerInteract playerInteract;
[SerializeField] private TextMeshProUGUI interactTextProUGUI;

[SerializeField] private Transform playerCameraTransform;
[SerializeField] private LayerMask pickUpLayerMask;
public ObjectGrabbable objectGrabbable;


private void Update()
{
    float pickUpDistance = 2f;
    if (playerInteract.GetInteractableObject() != null && (Physics.Raycast(playerCameraTransform.position, playerCameraTransform.forward, out RaycastHit raycastHit, pickUpDistance, pickUpLayerMask)) && objectGrabbable.Grabbed == false)
    {
        Show(playerInteract.GetInteractableObject());
    }
    else
    {
        hide(); 
    }
}
private void Show(IInteractable interactable)
{

    containerGameObject.SetActive(true);
    interactTextProUGUI.text = interactable.GetInteractText();
}
private void hide()
{
    containerGameObject.SetActive(false);
}

}

timber tide
#

make another game object variable

violet topaz
timber tide
#

well that's a bit more work

violet topaz
#

😦

timber tide
#

you seem to have the layers and raycast going so I assume you've the idea, no?

violet topaz
#

yea i tried using a tag on the objects that can be picked up but i couldn't seem to figure it out

#

not layers tho

timber tide
#

your video shows you using two cubes

violet topaz
#

nvm i have a layer called pickup/down

polar wasp
#

damn that first person view is SEXY

#

what do you do for it? just rotate the camera according to the horizontal input?

tender stag
#

u mean the side rotation?

polar wasp
#

yeah

tender stag
#

yeah i just smoothdamp the rotation

#

according to the horizontal input

polar wasp
#

i've been meaning to learn smoothdamp operations but i haven't gotten around to it yet :/

#

trying to get all the math in my brain

tender stag
#

but the closer he gets to the surface

#

to add more force down

#

and less up

#

and vice versa

silk night
#

well you already have the 9.81 gravity downforce constant that you are basically diminishing by adding an up force

#

if you add 9.81 up every frame you end up with 0 acceleration

tender stag
polar wasp
tulip hill
#

how do i change the height of my character inside the scripts?

silk night
#

inside which scripts

polar wasp
tulip hill
#

like on code

polar wasp
#

or the actual physical height

tulip hill
#

accesing the scale of the transform thing

#

the physical height

#

i thought transform.scale existed

polar wasp
#

take my advice with a grain of salt

tender stag
#

and people use drag for it

#

which is cant modify

#

cause it messes with other things

polar wasp
#

but i would make a variable that saves my character's height in the void Start() section

tender stag
polar wasp
#

then a transform.Scale() function with the parameters of your height variable

tulip hill
#

man idk i dont really like using the void start() section

#

all i need is to modify the height for crouching

polar wasp
#

its not that hard lol

polar wasp
#

its where you store all of your variables

#

the values of all your variables mb

tulip hill
#

i store them after the public class thing

#

oh values

polar wasp
#

are you trying to adjust the height of your collision box?

tulip hill
#

no, like the player body height

polar wasp
#

or if someone smarter than me could help me out, would you have to adjust the collision box or the size of the Rigidbody

tender stag
tender stag
#

just for y velocity

#

which is really easy to do

#

from what im seeing

#

its literally just this

polar wasp
#

yeah what are you thinking for the math?

tender stag
tender stag
#

because it worked before

dim bridge
#
        Vector3 target = Vector3.Scale(transform.forward,new Vector3(0,0,-1));
        Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);

Is someone able to explain why this doesn't work and point me to an appropriate method of handling this. This is in an empty gameObject script and just needs to move the gameObject backwards on the z axis

tender stag
#

but it also messed with horizontal movement

#

thats why i’ll just make my own just for vertical

#

anyway im about to hit the sack

#

so i’ll do it tmr

dim bridge
#

oh wait I need to do transform.postion = dont I

polar wasp
gaunt ice
#

Vec3 Move towards return a vec3

dim bridge
#

yeah ok its moving (in the wrong direction)

gaunt ice
#

It doesn’t change your transform

dim bridge
#

but its moving now

dim bridge
#

lemme try smth

tulip hill
dim bridge
#

ok well its moving in a diagonal in the oppsite dir than I want

swift crag
#

then it tries to move your position towards this vector

#

which will be a very short vector between [0, 0, -1] and [0, 0, 1]

#

then you throw the result out

#

if you assign that to your position, you'll move towards that vector

dim bridge
#

h so Im moving towards the world

#

0,0,-1

swift crag
#

but that still doesn't make much sense

polar wasp
dim bridge
#

wait

gaunt ice
#

You are moving to a direction not position

swift crag
dim bridge
#

yes

swift crag
#

add that direction vector to your position to get a target

dim bridge
#

i want the position behind the gameObject

swift crag
#

well, just do transform.position -= someVector * Time.deltaTime * speed;

swift crag
#

scaling it by [0, 0, -1] is throwing out the X and Y components

#

so it only moves in the world Z direction

#

transform.forward is a world-space vector that indicates what "forwards" is for you

#

you can't get rid of the X and Y components from that and expect it to still be "forwards"

#

Scaling it by [1, 1, -1] would also be wrong

patent garden
#

can u guys help me

dim bridge
swift crag
#

instead of writing code that only happens to work in a very specific scenario

swift crag
#

it's harder to write the wrong thing here

#

-transform.forward; that's it.

dim bridge
#

i find it weird it lets me use a negative on a vector 3 like that

swift crag
#

- is the unary minus operator

#

it's used to negate a value

#

there's no transform.back, hence the need for this

near wadi
patent garden
#

i was getting ss

dim bridge
#

yeah but I mean like in a practical situation using a negative in front of what is essentialy an array is just sorta not smth I'd think of naturally

#

is what I mean

patent garden
#

idk whats up witht he code

near wadi
#

just making sure 🙂

summer stump
swift crag
patent garden
#

it was working fine about a while ago, now the camear is ahead of the character

dim bridge
swift crag
#

you do lots of vector math in games

#
target.position - transform.position
#

surely that isn't weird

dim bridge
#

im aware

patent garden
#

what i want to happen is the camera follows the player as it moves, the issue is that the camera is ahead of the character and moves in the direction where the player is going

#

i dedeuced that its obv just coordinates off but idk whats up in the code

summer stump
eternal falconBOT
summer stump
#

And also, obligatory "use cinemachine"

patent garden
#

is this right?

#

the way i used the link

#

good

dim bridge
# dim bridge im aware

I'm gonna be brutually honest ik I'm doing stuff wrong but I feel I'm getting some simple concepts explained to me like I have 2 iq and it doesn't feel nice

summer stump
patent garden
#

ok

swift crag
patent garden
#

wdym

#

there is no late update

summer stump
dim bridge
#

Sorry

#

I wasn't trying to come off agressive

#

I just felt a bit attacked for a second

patent garden
#

like this?

swift crag
#

amusingly, there's also a unary + operator

gaunt ice
#

It calls operator overloading and you can find the operators of vec3 in docu

summer stump
dim bridge
patent garden
#

we stiull have the bug

swift crag
#

anyway, yeah, -transform.forward will give you the direction that's "backwards" for transform

dim bridge
swift crag
#

(you could also do transform.TransformDirection(Vector3.back) if you wanted)

swift crag
#

In this case, we're interpreting Vector3.back as a local-space direction

#

and using TransformDirection to turn that into world-space

dim bridge
#
        Vector3 target = -transform.forward + transform.position;
        transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);

I did this

swift crag
#

(that's what transform.forward is doing, just with Vector3.forward!)

#

Also, rather than creating a target, it'd be better to just do

#
transform.position -= transform.forward * speed * Time.deltaTime;
summer stump
swift crag
#

since target will only be 1 meter away from transform.position

rocky canyon
#

1 m/ frame is hauling ass

#

lol

swift crag
#

vroom

#

or it means your computer is doing the opposite of hauling ass

patent garden
#

i just did

#

cinemachine?

rocky canyon
#

camera on easy-mode

#

has tons of built in functionallity

#

and comes built-in to unity

dim bridge
#

@swift crag Thanks

patent garden
#

how do i access cinemachine

#

i looked through package manager

#

ill do this tmrw ig

north kiln
pulsar creek
#

Can I set up an OnTriggerEnter2D to only work with for example CircleCollider2Ds and no other type of colliders?

timber tide
#

when you get a callback check if the collider is of type circle

pulsar creek
#

Nevermind, there's actually an option to exclude certain things on layers in the collider option

rocky canyon
#

yup, but remember there's only so many layers

#

i've never ran out.. but ive gotten close lol

cobalt creek
#
public void fireRay()
{
    Ray ray = new Ray(transform.position, transform.forward);
    RaycastHit rh;
    if (Physics.Raycast(ray, out rh))
    {      
      Debug.Log($"hit:{Time.time},{rh.transform.gameObject.name}");
    }
}

So the code above works when I use apply it to the 2D non-UI pink diagonal square that is in front of the white square. However, when it is applied to the UI version of the two squares, it does not work. How can I make that work for the UI objects?

timber tide
#

you need to use a raycast specifically for the UI

#

Physics raycasts are for the scene

#

or well, the non-ui part of the scene ;)

cobalt creek
#

thank.. i think i will find something that it for nonui

timber tide
#

there's a few ways you can grab what's over the mouse on the UI, usually through the event system interfaces or calls

grizzled zealot
#

Is Unity ECS and Unity DOTS the same thing? Can you use one without the other?

cobalt creek
#

a lot of examples i found deal with the mouse position, but i see your point. my application is for games that move an object, for ex a square so it does not necessarily a point and click

#

I can substitue the mouse position with the position of the square in that case i guess

timber tide
#

well, you must be doing input somehow

teal viper
cobalt creek
#

keyboard keys.. u,l,r,d

teal viper
#

Data Oriented Tech Stack iirc

timber tide
cobalt creek
#

maybe something like getting the canvas, and since it cover every gameobject in view, maybe i can launch rays all within canvas bounds

acoustic sun
#

When I try to play my game, it would load to 90%. Is it an issue with the WebGL? It has ever done that with me before when I publish games

rocky canyon
#

try a different browser..

#

a lot of webGL games i try to play stall at 90%

#

and then they'll work in some other browser.. not sure why tbh maybe someone knows

#

i see alot of people mention trying to change the compression

acoustic sun
#

I have tried a different brower and its still happening. I have shared my Web link with my professor and my classmates and they are saying that the load is still suck on 90%

rocky canyon
acoustic sun
rocky canyon
#

np, changing the compression usually works for me

brisk escarp
#

Hi all, I am wondering why i have this pink line when i am creating my drawing mechanic for my game.

#

is it to do with the code or should i ask the ui page

#

(Forget about it fixed it..)

teal viper
brisk escarp
#

I relised that the line was too big when it is saved and that i need to have the line renderer keep the same size as well as having the material copy to the new object.

#

(I am not the best writer sorry)

cobalt creek
#

Mao, I solved the graphics raycast problem by converting the GO position to canvas coordinates, eg RectTransformUtility.WorldToScreenPoint(), so thank again. it replaced the mouse position

covert sinew
#

Are there any situations where Screen.width and Screen.height will not match the current resolution of the window/screen?

#

I'm currently using Screen.width/height to get the resolution, using it as a variable in UI adjustment calculations, and it seems to be working perfectly in editor, but I understand some things behave... Incorrectly, in runtime, as compared to editor.

sonic dome
#

Can anyone give me a brief answer to when should I use mono behaviour and when not and when I don't use mono behaviour how does it work please
Ping me on reply

teal viper
sonic dome
#

Will I find any documentation bout this with examples and details of working with normal classes and mono behaviour

teal viper
#

You can lookup MonoBehaviour in the documentation, but there isn't really anything on plane classes. You'd use them the same as in any other C# app.

sonic dome
#

Oh okk thanks so much ❤️

agile hornet
#

Hello,
So I have these rockets and I want them to chase and hit the enemy(which is an array of multiple gameobjects), the rockets chase the enemy but not directly it like hovers the enemy instead of hitting it directly.
Any help is appreciated

``public class Rockets : MonoBehaviour
{
private Rigidbody RocketRb;
// Start is called before the first frame update
void Start()
{
RocketRb = GetComponent<Rigidbody>();
}

// Update is called once per frame
void Update()
{
    GameObject[] enemy = GameObject.FindGameObjectsWithTag("Enemy");
           
    foreach(GameObject adui in enemy)
    {
        Vector3 enemyDirection = adui.transform.position - transform.position;
        RocketRb.AddForce(enemyDirection.normalized*10);
    }   

    if(transform.position.y <-1.5f || transform.position.y > 1.5f || transform.position.z > 15 || transform.position.z <-15) 
    {
        Destroy(gameObject);
    }

}    

}

``

teal viper
agile hornet
teal viper
agile hornet
teal viper
#

Anything else beyond that you'd need to code

agile hornet
teal viper
agile hornet
radiant frigate
#

hi! how can i make a gameobject go to a certain side depending on its rotation? i´ve tried with transform.up but idk if im making a strange approach to the problem

#

the switchs makes it so that depending on which bullet it is, it either goes left or right

queen adder
#

omg.. today i learn playerprefs dont have getbool.. blushie

#

how's this for an autosaving setting system?

#

good enough?

#

oh i can edit the getter to have default value

teal viper
dawn kestrel
#

how reliable is using transform.lossyScale? At what point will it usually start to skew?

sour ruin
#

Hi, is it possible to expose the constructor of a class to the inspector like you would for a standard field? See the constructor where I would like to have the option of specifying an f, z, and r from the inspector of a PlayerController class which are private fields inside SecondOrderDynamics.

north kiln
#

No

summer stump
north kiln
sour ruin
teal viper
agile hornet
teal viper
modest quarry
#

first time encoutnering this

#

which one am i supposd to use

keen dew
#

Remove the using System.Numerics line

modest quarry
#

oh okay thanks

agile hornet
# teal viper Does it work correctly with only 1 enemy?

Using
RocketRb.velocity = enemyDirection.normalized*20;
instead of
RocketRb.AddForce(enemyDirection.normalized*20);

Fixes the issue of hovering and the rocket chases the enemy and hits it directly without hovering.
Thanks.

modest quarry
#

!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

buoyant horizon
#

I have no clue what I am missing

#

This error is tied to a script / series of scripts from what I can tell( Inventory System, Item PickUp System and the Item itself ). This error appears everytime I intereact with my interactable object. The scripts are meant to pickup the object, delete it from the scene and make the itemcount go up ( +1 for each item picked up )

teal viper
buoyant horizon
#

Not quite, did I not drag something onto a asset in the inspector tab?

teal viper
#

Perhaps.
Do you understand what a reference and null are?

buoyant horizon
#

Isn't a "reference" refering to a method that calls a certain script within it?

#

I'm guessing null has it's general meaning of a nonexistent value / object ?

teal viper
teal viper
spiral folio
#

im making a game thats pretty much just a dropper map, but the players speed increases as they fall, is there a way to 1.control the rate at which said speed increases and 2.make “power” that lets them break momentum

buoyant horizon
teal viper
teal viper
eternal falconBOT
#

:teacher: Unity Learn ↗

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

buoyant horizon
spiral folio
narrow girder
#

Hello, uhmm are there any video guides to properly learn how to use unity and proceed to asprite -> unity interface etc.

teal viper
languid spire
# narrow girder Ohhh thank youuuu
Unity Learn

In development at Unity is a 2D Animation package that allows you to rig Sprites as one might rig a 3D model for animation. In this tutorial, you will go through the process of importing the 2D Animation package and rig a sprite ready to be animated. You will learn about all the features of the 2D Animation package, including Bones, Weights and ...

spiral narwhal
#

What would be the proper class to use so I can simply pick an action from my input master?

#

Ah found it: InputActionReference

hidden sleet
#

I'm about to start working on ai for a stealth game, so they'll do the classic patrol, investigate, search etc. I've been looking into finite state machines and have just heard about behaviour trees. They both seem to have ups and downs but I'm not too sure when you'd use either one. What are the pros and cons of each and how would I go about deciding which to use?

foggy crypt
#

My character can phase through walls if you walk into them for long enough
I use transform.Translate for movement
How can I prevent him from doing that?

languid spire
#

Don't use transform.Translate, it does not respect physics

dawn wharf
#
{

    // Create fireball at the character's position
    Vector3 bulletSpawnPosition = transform.position + new Vector3(0f, 1.5f, 0f);
    GameObject bullet = Instantiate(bulletPrefab, bulletSpawnPosition, Quaternion.identity);

    // Calculate the direction towards the mouse pointer
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
    {
        Debug.Log("Hit point: " + hit.point);
        Vector3 bulletDirection = hit.point - transform.position;
        bulletDirection.y = 0;

        // Apply the direction to the fireball
        bullet.GetComponent<Rigidbody>().velocity = bulletDirection.normalized * bulletSpeed;
    }
}```
the bullet is not moving, any fixes?
burnt vapor
#

Then log bulletSpeed and notice it's probably 0 because you did not set it

languid spire
#

Vector3 bulletDirection = hit.point - transform.position;
should be
Vector3 bulletDirection = hit.point - bulletSpawnPosition;
?

dawn wharf
burnt vapor
languid spire
#

Don't tell me, AI fucking code, again

dawn wharf
burnt vapor
#

Did you write this code or did you let ChatGPT write it?

dawn wharf
#

this is a doubt from junior and even i am unable to fix it

#

T_T

burnt vapor
#

Whatever it casts to is clearly not what you'd expect

languid spire
dawn wharf
languid spire
dawn wharf
#

gotcha

fringe plover
#

!code

eternal falconBOT
fringe plover
#

Sup! im trying to make random generator (cubes only, but it doesnt work properly (see image), can someone help?

    void Generate()
    {
        float spaceBetweenSections = 3f;
        Vector3 spawnPosition = Vector3.zero;

        Vector3 prevSize = Vector3.zero;
        for (int i = 0; i < numberOfSections; i++)
        {
            System.Random random = new System.Random(seed.GetHashCode() + i);

            GameObject selectedPrefab = sectionPrefabs[random.Next(0, sectionPrefabs.Length)];

            Instantiate(selectedPrefab, spawnPosition, Quaternion.identity);

            spawnPosition = Vector3.right * (prevSize.x / 2 + spaceBetweenSections + prevSize.x / 2);

            prevSize = selectedPrefab.transform.localScale;
        }
    }
#

Fixed rn by destroying first instantiated object

#

No i didnt fix..

#

alr, i fixed by asking chan gpt..

languid spire
fringe plover
#

actually learn something
I would not even learn code if i didnt used tutorials and gpt

languid spire
fringe plover
rare basin
noble coral
#

hi guys! I`m doing a coop game, I put animations on characters, but when moving them shakes. I added a virtual camera and its gone, but in the second player it just goes off. Can someone help pls?)

rare basin
#

cant understand anything from the sentence

quiet scaffold
#

So i want the cyan circle to rotate around my player, but it does some weird stuff instead?

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

public class TEMP_WEP : MonoBehaviour
{
    public GameObject weaponPrefab;
    public GameObject player;

    void Update()
    {
        weaponPrefab.transform.RotateAround(player.transform.position, Vector3.up, 150 * Time.deltaTime);
    }
}
noble coral
#

virtual camera just off when in session spawning second player

quiet scaffold
swift crag
#

Right. You're telling it to rotate around a moving point

#

That's different from following a moving point and then rotating around that

#

Imagine a circle centered on the player and that touches the item

#

If you move further away from the item, the circle gets larger.

#

If you want the circle to spin around the player, I'd suggest first moving it so that it's the correct distance away from the player, then using RotateAround

#

also, if you want it to spin around the player in a circle, use Vector3.forward

#

Vector3.up means it's rotating into and out of your screen

quiet scaffold
#

yeah i got the vector3.forward

swift crag
#

To get the correct position, consider doing this

#
Vector3.MoveTowards(player.transform.position, transform.position, desiredRadius);
#

MoveTowards is useful for more than steady movement!

#

Although, actually, I guess it's not the best choice here...

#

since it won't move the item further away from the player, right.

#
(transform.position - player.transform.position).normalized * desiredRadius + player.transform.position;
#

that would be more appropriate

visual hedge
#

could not hold myself from ranting: Could scrollbar be more bugged?

swift crag
#

the Unity UI scrollbar?

#

ScrollRect is decently complicated; it's easy to set it up wrongly if you don't just use the template from the GameObject menu

timid hinge
#

i guys can someone help me to find a good programmer to make me a 2d game roguelike?

swift crag
#

!collab

eternal falconBOT
timid hinge
#

thanks

visual hedge
swift crag
#

The GameObject > UI > Scroll View template works well. I did have to add a couple of things to Content:

  • A ContentSizeFitter set to "preferred size" on both axes
  • A VerticalLayoutGroup set to control child size on both axes (and to not force-expand children)
#

If you're having problems with Unity UI, you should ask about it in #📲┃ui-ux

noble coral
#

when the second player appears in the session, the virtual camera is destroy in all clients, help plsssssss

narrow girder
#

How do i save an asprite file then transfer to unity?

rare basin
rare basin
cosmic dagger
sour yew
#

hey guys. im working on the NPC dialogues, and i have this piece of code:

public class PlayerInteract : MonoBehaviour
{
    // Start is called before the first frame update
    void Start(){ 
        
    }

    // Update is called once per frame
    void Update(){
        if (Input.GetKeyDown(KeyCode.E)) 
        {
            float interactRange = 2f;
            Collider[] colliderArray = Physics.OverlapSphere(transform.position, interactRange);
            foreach (Collider collider in colliderArray)
            {
                if (collider.TryGetComponent(out NPCInteractable npcInteractable))
                {
                    npcInteractable.Interact();
                }
            }
        }
    }
}

and i was wondering, how to implement a functionality, where a dialogue window disappears after the player walks away from the NPC. can smb help me out? thx

noble coral
# rare basin ask your question with more details, noone is going to help you if you dont even...

I have a camera in the character that’s attached to the character’s head. The animation causes character to start shaking. I decided to use the Virtual Camera (it follows the empty "zxc" object in the character’s head model) from Cinemachine.When I run the game alone, everything works fine.But when I enter the game with 2 clients,then the script CinemachineVirtualCamera disappears in VirtualCamera and creates a child element cm.

frosty hound
sour yew
frosty hound
#

Okay, if you say so

quiet scaffold
ivory bobcat
quiet scaffold
#

how can I make the enemy have randomized moveemnt and etc.? i currently just have

transform.position = Vector2.MoveTowards(transform.position, playerPrefab.transform.position, moveSpeed * Time.deltaTime);

and I was wondering how to add something like it randomly dashing towards you and etc?

sour yew
ivory bobcat
#

You'd cache them... and release them when necessary.

ivory bobcat
rare basin
#

without caching it?

#

do you know what cache means?

sour yew
rare basin
#

doesn't look like it

sour yew
#

tf is ur problem?

polar acorn
# sour yew yes

Caching can mean many things. Which caching do you think people are talking about?

polar acorn
sour yew
burnt vapor
errant canopy
#

Ok perfect 👍 Thanks

polar acorn
queen adder
#

hey i got a problem with saving data https://hastebin.com/share/quyojehihu.csharp
i posted each of my 3 scripts there and error at the end

polar acorn
#

Caching is the programming term for "storing something for easier access later" and applies to a lot more than just the memory cache

noble coral
#

I have a camera in the character that’s attached to the character’s head. The animation causes character to start shaking. I decided to use the Virtual Camera (it follows the empty "zxc" object in the character’s head model) from Cinemachine.When I run the game alone, everything works fine.But when I enter the game with 2 clients,then the script CinemachineVirtualCamera disappears in VirtualCamera and creates a child element cm. what can i do?

final kestrel
#

Is the best way to restrict character movement completely enabling and disabling the script?

sour yew
polar acorn
#

Nobody is saying "idk why" they were very clear about the why

final kestrel
# noble coral sorry, didnt understand

I want to take the controls from player at specific points lets say. Do i completely disable the script that is responsible for movement or is there any other way?

swift crag
#

I do that with a "brain" system. I have a PlayerBrain that uses player input to send commands, and I have an AIBrain that makes up its own commands.

frosty hound
swift crag
#

So I could take control from the player by turning off the player brain and turning on another brain

#

I'd still be using the same movement logic.

final kestrel
#

Ah okay

frosty hound
#

If you're talking to an NPC, you need to keep track (cache) what NPC you're talking to. There's nothing more to it than that. When you're out of that NPC's range, tell it to stop talking. When your want it to be your ConversationManager that does so, or the player's Interact script is entirely up to you. Both will work.

swift crag
#

I originally had completely distinct movement logic for players and non-players (a CharacterController vs. a NavMeshAgent) and it was a mess

#

I still have a NavMeshAgent, but it's used to figure out where to go; it does not actually move the character

final kestrel
#

Ah okay I see. Thanks

#

and uh I believe its not recommended for beginners to use the ready assets right? For movement lets say. I dont understand most of the stuff. Which actually made me realize I dont know how the input script and the actual movement script links.

sour yew
polar acorn
#

Basically, right now you are asking "Why would I need your phone number, you're right in front of me?"

The reference is so you can contact it later, when it's no longer directly involved in the collision or whatever starts your dialogue

glad sundial
#

How to remove camera shake due to character animation? The camera is located in the character's head model

exotic hazel
#

need help

#

how i add a layer to a terrain

exotic hazel
#

i checked online but the options they have and i have are different

buoyant knot
#

game logic should never be tied to graphics

#

if your camera targets the head, and head is moved by animation, then animation now changes your camera, which is wrong

#

camera should target a different object, probably the actual physics shape.

#

blue capsule collider, for red character animation. Camera should target a position based on the blue capsule collider

sour yew
tender stag
#

@polar wasp i used the buoyancy u suggested

#

i think it looks alright

#

just gotta increase the force a tiny bit so that the camera doesnt go below the water surface

burnt vapor
eternal falconBOT
lapis lance
#

@swift crag @polar acorn thanks for yalls help yesterday, learned more about canvas and event system. problem ended up being a player cam locked the cursor

timber tide
#

Doing a secondary overlapsphere with a smaller radius vs calculating the previous overlap operation and comparing distances with each collider?

buoyant knot
#

i don’t understand

#

are you asking which is better?

timber tide
#

yeah

#

assuming I'm grabbing like 1000+ colliders per overlap operation

buoyant knot
#

that kind of depends on how much crap is near/on the sphere

buoyant knot
timber tide
#

yes, basically I've difference ranges for what I need to compare against

buoyant knot
#

Note; My knowledge is primarily for 2D.
Collider2D.Distance is generally faster. Imagine how fast you can cache and do all sorts of gymnastics to calculate the distance. Collider2D.Distance is slightly faster than that, but less headache.

#

and .Distance is substantially faster than any Physics query

#

in my own depenetration for my physics engine, I call OverlapCollider, get a giant list, create structs with results of .Distance, then I sort and work with that.

timber tide
#

Ah, ok sounds reasonable enough, but getting to the point where my targeting script is becoming the bulk of my operations

buoyant knot
#

second query will get expensive

#

you can always benchmark doing it 10000 times

timber tide
#

ive so much to benchmark already x_x

swift crag
#

i do some crude benchmarking by turning off my camera and cranking up the timescale

buoyant knot
#

just call OverlapSphere 10k times, and .Distance 10k times. That’s all you need

swift crag
#

it simulates running the game at 10 FPS in real-time (so if it can do 100 FPS, i run it at 10x speed)

#

pretty handy for quickly spotting problems

#

as well as for looking for weird edge cases

buoyant knot
#

and you should have your own benchmarking helper functions to help you do this faster

#

if you can wait, I have something like this, and I can send you my benchmark (for 2D) to you over lunch

timber tide
#

Ah, appreciate it, but mostly dealing with 3D and 3D physic queries atm

buoyant knot
#

i mean i send code, and you change it to the corresponding 3D queries to test

timber tide
#

oh, sure ill take a look at it. Throw it up on a repo and ill take a look

buoyant knot
#

ok. i’ll be able to do that in like 1-2 hr

#

if not, tonightj

timber tide
#

no rush, I'm debugging a lot of other things ;p

buoyant knot
#

if you have a massive number of enemies (like a bullet hell), you might need a non-physics solution

#

it might need a data-based solution

#

where you store shit in a data structure, do your own updates, do your own rendering, etc

#

eg vampire survivors

timber tide
#

there's probably a lot I can cut down on using jobs, but I am offloading a lot to the GPU

#

as rendering right now is pretty cheap (mostly primitives or sprites)

buoyant knot
#

you can also go the game design route, to restrict what you can spam

#

mario maker can only handle 200 goombas at once.

#

well, it can handle a lot more, but you are limitted to 100, then with an extra limit to actually allow 200

#

point being, you can restrict the number of goombas

timber tide
#

honestly, rendering and stuff like pathfinding ive gotten pretty cheap

#

it's just the collisional and targeting stuff that eats away at my frames

#

hitting 1000+ enemies with a fireball in a single frame usually a big oof

buoyant knot
#

you can also make the targetting dumber

timber tide
#

I've done that with the pathfinding haha

#

was too smart for its own good

quiet scaffold
timber tide
#

that's not the same component as the script

tawny cave
#

does OnTriggerEnter function necessarily needs to be in the script attached to the trigger GameObject ?
I'd like to have the script attached to an other game object (not the trigger), but call OnTriggerEnter in that script for an other GameObject set as trigger.

queen adder
#

yeah you asigned player script instead of player xp manager i think?

quiet scaffold
#

but I can't drag the PlayerXPManager script on? all I can do is drag the player prefab

timber tide
#

both need a colliders, one needs IsTrigger, and one needs a rigidbody (can be kinematic)

tawny cave
queen adder
quiet scaffold
# queen adder

so what am I supposed to put there? I can't drag anything except the player

summer stump
#

You want the object WITH the script, not the script itself of course

timber tide
quiet scaffold
tawny cave
timber tide
#

usually I keep my parents as the managers, but for the more active in scene stuff would be child to that container

summer stump
#

Is that a prefab image you are showing. And is player a scene object?

quiet scaffold
#

im extremely bad at explaining sorry

#

i feel like this has something to do with prefabs though, idk if im correct tho

wintry quarry
summer stump
#

It is enemy

#

So that component is something different

#

I see mao said that a while ago

queen adder
quiet scaffold
queen adder
quiet scaffold
#

@summer stump i see you reacted to evevemue's msg, is that not the corrcet way to do it? it works, but is there a more simple way or?

queen adder
#

sure its not the best way

summer stump
#

A singleton would be better for manager types, but in this case what praetor said is inportant

hexed terrace
#

FindObjectOfType<T> is fine to use, sparingly

polar acorn
#

Find is the one you should never use. FindObjectOfType is one you should try not to use

summer stump
polar acorn
#

The only times you should use it are when there is exactly one instance in the scene so you know what you're getting, which is also the conditions under which that object is a good candidate for a Singleton

quiet scaffold
#

okay, thank you all

timber tide
#

Id more likely to abuse statics and singletons before I ever touch Find. No reason not to know where the things I instantiate are at.

#

the scene itself is just a large container

polar wasp
tender stag
#

thanks for helping

polar wasp
#

any time

tender stag
#

now im moving onto adding parachutes

#

which is gonna be quite easy

polar wasp
tender stag
#

yeah

#

hardest bit is gonna be the animation of the parachute deploying

#

and the model

rocky canyon
#

bro.. u doing a battle-royale?

tender stag
#

lmao

#

nah the walking dead themed game

polar wasp
#

why did no one tell me linear algebra was so hard

swift crag
#

I just let Unity do it (:

austere hedge
#

I don't understand the use-case of having an Audiomanager play clips versus just playing audioclips at a source. It doesn't seem like AudioManagers have any managing methods that make them worth it to use. Can someone please explain to me when it would be best to use an Audiomanager?

swift crag
#

well, you'd have to write some "managing methods" to get any use out of it (:

#

Notably, an "audio manager" could rate-limit sound effects

#

by only allowing three of a certain kind of sound to be played at once, for example

rocky canyon
swift crag
#

It could also be responsible for controlling the volume of the one-shot sounds

#

so that individual sound makers don't have to go look up the current volume setting

rocky canyon
#

^ that too.. audiomanager's are OP

#

all of ur stuff right there in 1 place

summer stump
#

It doesn't seem like AudioManagers have any managing methods that make them worth it to use.

I don't underatand this

#

You would of course MAKE those methods yourself

austere hedge
# rocky canyon so u dont need dozens of audiosources?

I can use this method to use only a single audio source.

    public void Play2DClipAtPoint(AudioClip clip, float pitch)
    {
        //  Create a temporary audio source object
        GameObject tempAudioSource = new GameObject("TempAudio");
        tempAudioSource.transform.position = Camera.main.transform.position;

        //  Add an audio source
        AudioSource audioSource = tempAudioSource.AddComponent<AudioSource>();

        //  Add the clip to the audio source
        audioSource.clip = clip;

        audioSource.pitch = pitch;
        //  Set the volume
        //audioSource.volume = this.sfxVolume;

        //  Set properties so it's 2D sound
        audioSource.spatialBlend = 0.0f;

        //  Play the audio
        audioSource.Play();

        //  Set it to self destroy
        Destroy(tempAudioSource, clip.length);

    }
rocky canyon
#

thats basically an audiomanager..

#

i misunderstood what u meant..

#

i thought u meant having ur clips already loaded up in ur sources.. and just calling sources for w/e thing u want

#

but see here ur already managing an audiosource.. (setting a clip, modifying params, then playing it)

austere hedge
#

I didn't know this method was comparable to an AudioManager, so just trying to see if there's any reason for me to use that class if I have this method.

rocky canyon
#

an audiomanager would just be a robust version of something like this.. (i personally keep around a few audiosources (as children of the manager) 1 for gfx, 1 for music, 1 for player sounds..

summer stump
rocky canyon
#

i pass in the clip thru the function and it just plays it..

rocky canyon
#

its just a script u wrote that manages audio/audiosources

austere hedge
#

I understand now. Thanks guys.

rocky canyon
#

Single principle part of SOLID

#

its sole purpose is to handle audio

#

nothing more nothing less

#

heres mine.. pretty newbie version.. but thats all it does

#

although.. seems like somethign that could very well be a built-in component some-day

#

i'd use it lol

tawny cave
#

How do I change a bool variable upon finishing an animation of a GameObject ? (variable would be in script attached to object)

rocky canyon
#

could use an animation event to call a function that flips it off for ya

#

would just put it on the last keyframe

sour yew
#

hey guys. i have this piece of code and i want to check the distance between the player and the NPC. can smb help me out with this? thx

public class PlayerInteract : MonoBehaviour
{
    // Start is called before the first frame update
    void Start(){ 
        
    }

    // Update is called once per frame
    void Update(){
        float interactRange = 2f;
        Collider[] colliderArray = Physics.OverlapSphere(transform.position, interactRange);
        if (Input.GetKeyDown(KeyCode.E)) 
        {
            
            NPCInteractable npc = new NPCInteractable();
                        foreach (Collider collider in colliderArray)
                        {
                            if (collider.TryGetComponent(out npc))
                            {
                                npc.Interact();
                            }
                        }
        }
        if(distance between the NPC and player > interactRange)
        {
            npc.EndConversation();
        }
    }
}
sour yew
modest dust
#

I feel like people forgot how to read

swift crag
#

it's not Vector3.GetDistanceBetweenNPCAndPlayer

modest dust
swift crag
#

it's Vector3.Distance

modest dust
#

It's even formulated nearly the same

swift crag
#

the page won't explain how to use this for your dialogue system

#

of course it won't

swift crag
#

I'm not sure what kind of explanation beyond that you were expecting.

sour yew
swift crag
#

...which is the other transform

swift crag
#

You don't need to write an entire class that has a public field called other to use Vector3.Distance

#

That code is an example of how to use Vector3.Distance

#

other is not a an argument to Vector3.Distance. It is part of the example code.

#

You seem incredibly confused about the concept of an example...

modest dust
#

Sometimes I feel like there should be a level below beginner

#

Basic logic and reading skills are kind of necessary

tall delta
swift crag
#

Stop ?-reacting everything and start giving this an ounce of critical thought.

#

This is ridiculous.

queen adder
#

is playerprefs the easiest method to store data?

swift crag
#

It requires the least effort to start using, yes.

modest dust
swift crag
#

It's fine for small amounts of data.

summer stump
swift crag
#

But it's not appropriate for large amounts of structured data.

queen adder
#

okay, i dont need a lot of data and also dont need to secure them for now

swift crag
#

Use it if all you need to do is write "player level is 10 and player money is 3000"

tall delta
swift crag
#

it should really just go to a file in the persistent data path or something

#

KSP2 had a great bug where it'd write huge amounts of data to PlayerPrefs (it was a malfunctioning editor tool that also wound up in the build, iirc)

swift crag
sour yew
polar acorn
polar acorn
sour yew
polar acorn
summer stump
#

And hariedos apt response

"What's the distance between point A and point B? Distance(???,B)"

summer stump
#

How is that possible

#

That makes no sense

#

Is the NPC not a gameobject?

#

All gameobjects have a position

polar acorn
summer stump
#

As I said before:
npc.transform.position
I dunno your code, so of course replace npc with your reference

#

Right?

#

You have the npc, so get its transform, and from there get its position

sour yew
#

idk how and why. its some strange $hiet. look, my NPC class looks like this:

public class NPCInteractable : MonoBehaviour
{
    [SerializeField] private NPCConversation npcConversation;

    public void Interact()
    {
        ConversationManager.Instance.StartConversation(npcConversation);
    }
    public void EndConversation()
    {
        ConversationManager.Instance.EndConversation();
    }
}

it obv inherits MonoBehavior. Idk what methods and fields it has. But if i serach the 'documentation' for vector, it doesnt have any results:

polar acorn
#

So get the position of it

sour yew
summer stump
#

Just write what I told you...

polar acorn
queen adder
#

Whats wrong here? im confused

summer stump
polar acorn
#

If you want the NPCs position, call it on the NPCs transform

sour yew
queen adder
summer stump
queen adder
eternal falconBOT
#

:teacher: Unity Learn ↗

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

polar acorn
summer stump
#

You need to go back to the extreme basics @sour yew
This is crazy
Understanding dot notation is a requirement to code

swift crag
#

Always start with the error.

queen adder
#

Assets\Scripts\DataGroup.cs(11,35): error CS0236: A field initializer cannot reference the non-static field, method, or property 'DataGroup.valueablePieces'

polar acorn
#

Just please do a little bit of logical processing. Apply knowledge from scenario A to scenario B

polar acorn
queen adder
#

okay thanks

swift crag
lunar fern
#

so im having a problem (and please tell me if this is an of-topic question) with vscode. when im coding i dont get any "suggestions" or "Intellisense". ive tried a bunch of things like re-choosing the external editor and instaling a bunch of extentions to vscode and even chat gpt isnt any help to fixing the problem. please tell me if there is a solution please (thanks in advance)

swift crag
#

You can't initialize a field with another (non-static) field, basically

eternal falconBOT
swift crag
#
public class Whatever {
  public static int staticVariable = 123;
  public int foo = staticVariable;
  public int bar = baz;
  public int baz = bar;
}

foo is fine because it uses a static variable. bar and baz are not

lunar fern
swift crag
#

And it should be kinda clear why this isn't allowed -- how would you even resolve that?

lunar fern
swift crag
#

The compiler doesn't want to have to figure out an order that it makes sense to initialize the fields in, so it just says no

queen adder
#

can you also let me know if this is a good way to store data? first i gather all data i want to save in data script

public BuyButtonManager buyButtonManager;
public MoneyManager moneyManager;

public int piecesValueMulti;
public float priceVal;
public float spawnSpeed;
public float priceChessboard;
public int money;

private void Start()
{
    piecesValueMulti = valueablePieces.piecesValueMulti;
    priceVal = valueablePieces.priceVal;
    spawnSpeed = buyButtonManager.spawnSpeed;
    priceChessboard = buyButtonManager.priceChessboard;
    money = moneyManager.money;
}

and then just gonna use PlayerPrefs in another script to save and set them all

swift crag
#

I wouldn't copy the variables into this class.

#

I would just directly get the values when I'm saving

#

(and directly set the values when loading)

sour yew
queen adder
#

but is it gonna work?

swift crag
#

so if valueablePieces.piecesValueMulti changes between when Start() is called and when you save your own piecesValueMulti field, you'll have a stale value

lunar fern
polar acorn
queen adder
#

and what if i change script execution order?

polar acorn
#

Which is what the dot operator does

swift crag
summer stump
summer stump
lunar fern
polar acorn
summer stump
#

Fair

swift crag
#

i'd just restart the machine and see if it clears up

swift crag
#

you have to be able to join the dots here...

  • every monobehaviour has a transform
  • every transform has a position
  • i have a monobehaviour that represents the NPC
  • i can calculate the distance between two positions
#

If you refuse to do this, you will fail miserably.

summer stump
#

And it literally is just joining the dots 😭

sour yew
# summer stump Oof. It's how you access the npc's position. It is the crux of your misunderstan...

ffs. ive been told that transform.position give you players position. and now suddenly, if i apply the same thing for an npc, now i magically can get npc's position :DDDD. so if i have this:

Dog dog=new Dog();
dog.name;//gives me dog's name

but then if i follow ur logic, i can do this:

Dog dog=new Dog();
dog.name;//gives me dog's name

Cat cat=new Cat();
cat.dog.name;

this doesnt make any sense, and you keep telling me that it does 😄 😄 😄

swift crag
lunar fern
swift crag
#

in C#, if you don't qualify a name, it's implicitly accessing something on this

#

this is a reference to your own object

summer stump
sour yew
swift crag
#
transform.position

in reality, this is

#
this.transform.position
#

this.transform.position is the player's position because this is an object attached to the player's game object

polar acorn
swift crag
#

someoneElse.transform.position is someone else's position because someoneElse is a reference to a component atached to their game object

summer stump
sour yew
swift crag
summer stump
swift crag
#

Correct your attitude or you won't be getting any help here.

polar acorn
summer stump
# sour yew ffs. finally someone knows some stuff. thanks!

They said the same thing I was saying

You have absolutely no clue what is going on and it is embarrassing

And this happens every time you ask for help

Next time please understand that you know NOTHING, and we are trying to help, so just work with us instead of against us like some 12 year old kid that thinks they know everything

lunar fern
polar acorn
lunar fern
summer stump
frosty hound
lunar fern
# summer stump Yes. Check the first two checkboxes there and click regenerate project files

um i relised i hadnt downloaded .net v6 so i did and now i have this error: 2024-03-19 18:17:11.727 [info] The .NET SDK installed on the machine is targeting a different platform (win10-x86) with the C# Dev Kit (visualstudio-projectsystem-buildhost.win32-x64), and are incompatible. 2024-03-19 18:17:11.730 [info] Project system initialization finished. 0 project(s) are loaded, and 1 failed to load.

lunar fern
summer stump
summer stump
#

Should they do it again?

rich adder
#

oh dang

#

ater install SDK yeah usually

summer stump
#

Ok yeah, that's what I was thinking

#

@queen adder
What is confusing you about what osteel said?

rich adder
#

usually "The .NET SDK installed " says too me its installed but project .csproj files might be associated with another thing

summer stump
tawny cave
#

I created a StateMachine behavior script in the animator of my GameObject.
How can I change a bool parameter when the animation ends ? The animation keeps looping and the function is never called.....

wintry quarry
rich adder
#

thought they were talking to bradyaga

tawny cave
wintry quarry
summer stump
# queen adder cause i dont get it

Bradyaga has a long history of being aggressive and not listening to people, so they got warned
Why do you even need to get it, it wasn't directed to you

wintry quarry
#

What's the question?

#

Did you mean to say exits? You said "exists"

#

the state exits when the animator moves to a different state

#

it does that through transitions

tawny cave
#

ah ok

#

but how do I stop "Victory" from looping with a bool parameter then ?

queen adder
rich adder
summer stump
tawny cave
wintry quarry
rich adder
tawny cave
broken nest
#

Hey, I'm adding a value to an object's position to set it, but that doesn't work well when changing resolutions. I suppose I should multiply by some value but I don't know what it is. Any idea?

#

Don't know if that's clear

ivory bobcat
#

Maybe show what you've tried so far

wary dagger
broken nest
wintry quarry
wary dagger
broken nest
#

My guess would have been 1920/Screen.height but it's not that I checked already

wintry quarry
#

!code

eternal falconBOT
broken nest
#

cos I set it at 1920*1080

wintry quarry
ivory bobcat
wary dagger
# wintry quarry share your code in a way I can copy paste
if (Input.GetButtonUp("Fire1"))
        {
            if (highlight != null)
            {
                int shellCount = 14;
                float spread = 1;
                Quaternion offSet = Quaternion.Euler(0, 0, 90);
                Quaternion newRot = highlight.transform.rotation ;

                for (int i = 0; i < shellCount; i++)
                {
                    float addOffset = (i - (shellCount / 2)) * spread;

                    newRot = Quaternion.Euler(0,0, highlight.transform.eulerAngles.z + addOffset + 90);

                    Shell = Instantiate(Bullet, highlight.transform.position, newRot);
                }
            }

            Destroy(highlight);
        }
wary dagger
wary dagger
wintry quarry
# wary dagger found it easier and faster to do

Something like this:

if (Input.GetButtonUp("Fire1"))
{
    if (highlight != null)
    {
        int shellCount = 14;
        float angleOfSpread = 20; // 20 degrees for the whole cone. Set to whatever oyu want
        float degreesPerShell = shellCount / angleOfSpread;

        Quaternion offset = Quaternion.Euler(0, 0, 90); // correcting for up vs right I guess?
        Quaternion startRot = highlight.transform.rotation * Quaternion.Euler(0, 0, -angleOfSpread / 2f);

        for (int i = 0; i < shellCount; i++)
        {
            Quaternion shellRotation = startRot * offset * Quaternion.Euler(0, 0, degreesPerShell * i);
            Shell = Instantiate(Bullet, highlight.transform.position, shellRotation);
        }
    }

    Destroy(highlight);
}```
ivory bobcat
wary dagger
ivory bobcat
#

I'm assuming their placements isn't the issue but that the orientation has something to do with the direction they travel

wintry quarry
wary dagger
wintry quarry
#

probably a bug in how you're setting the highlight up or how you're firing.moving the projectiles

wintry quarry
wary dagger
#

or all of the code?

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

public class CombatSystem : MonoBehaviour
{
    [SerializeField] private GameObject AOE;
    [SerializeField] private GameObject Bullet;
    private GameObject highlight;
    private GameObject Shell;
    void Update()
    {
        if (Input.GetButton("Fire1"))
        {
            if (Input.GetButtonDown("Fire1"))
            {
                highlight = Instantiate(AOE);
            }

            if (highlight != null)
            {
                Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                Vector2 Dir = (mousePos - (Vector2)transform.position).normalized;

                highlight.transform.up = Dir;
                highlight.transform.position = transform.position;

            }
        }

        if (Input.GetButtonUp("Fire1"))
        {
            if (highlight != null)
            {
                int shellCount = 14;
                float angleOfSpread = 20; // 20 degrees for the whole cone. Set to whatever oyu want
                float degreesPerShell = shellCount / angleOfSpread;

                Quaternion offset = Quaternion.Euler(0, 0, 90);
                Quaternion startRot = highlight.transform.rotation * Quaternion.Euler(0, 0, -angleOfSpread / 2f);

                for (int i = 0; i < shellCount; i++)
                {
                    Quaternion shellRotation = startRot * offset * Quaternion.Euler(0, 0, degreesPerShell * i);
                    Shell = Instantiate(Bullet, highlight.transform.position, shellRotation);
                }
            }

            Destroy(highlight);
        }
    }
}

this is the whole class

wintry quarry
#

yeah show the bullet code too

wary dagger
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BulletScript : MonoBehaviour
{
    public float speed = 20f;
    public Rigidbody2D rb;

    // Start is called before the first frame update
    void Start()
    {
        rb.velocity = transform.right * speed;
    }

    void OnTriggerEnter2D(Collider2D hitInfo)
    {
        Destroy(gameObject);
    }
}
wintry quarry
#

and the player

wintry quarry
#

this is everything except the inspector

wary dagger
#

oh yea mb

ivory bobcat
wary dagger
wintry quarry
# wary dagger

your bullets are problaby just colliding with the player square TBH

wary dagger
#

i'll try to disable the player collision

obtuse axle
#

Hello, I have a question, I have a timer that starts at the beginning of the game and i want it to stop when my character hits that cubic hitbox

#

I'd like to know what I have to put inside the OnTriggerEnter

languid spire
#

!code

eternal falconBOT
obtuse axle
languid spire
obtuse axle
#

Im really not familiar with all those methods

rocky canyon
languid spire
#

you need to be before even thinking about multi player

fading rapids
#

do you need code for text not to be affected by post processing

eternal needle
fading rapids
#

i have and could only find 3d tuts and a 2d one using code

#

maybe im just bad at googling

stone nimbus
#

Hey I'm making a racing game for unity in school and I am not able to do a scoreboard at all

pallid verge
#

i have this instance of a script and i wanna call a method whenever the player respawns. problem is that whenever the player respawns it tells me that the instance is null. what might the problem be?

stone nimbus
eternal needle
pallid verge
slender nymph
fading rapids
last shore
#

is there someone just starting out trying to create something, as i am just starting out and have no idea on what to create so ill just help in your project

fading rapids
pallid verge
eternal falconBOT
slender nymph
last shore
stone nimbus
pallid verge
#

dont mind the comments

stone nimbus
slender nymph
#

that one method is the only place you seem to use that object. are you certain that the GameObject with the PlayerLife component also has a SwitchGravity component attached?

pallid verge
#

the PlayerLife script is on the player but the player does not have the SwitchGravity script attached

slender nymph
#

well that's why

pallid verge
#

but the script wouldnt make sense if it was on the player

slender nymph
#

then why are you checking the player's GameObject for that component?

pallid verge
#

oops

slender nymph
#

get a reference to the existing SwitchGravity object

pallid verge
#

thank you

stone nimbus
# stone nimbus

I tried it by making the button to start the race switching the bool to true

#

but still no feedback, not even in the console

#

the script is assigned to a gameobject

rich bluff
#

right click isRacing > find all references

#

look at everything that modifies it and if there are any errors

stone nimbus
#

ok nvm

#

got it

#

the gameobject was not in the scene somehow

ionic zephyr
#

what if I want to reuse a component in an enemy but methods require this "context"?

rich bluff
#

pass it down?

ionic zephyr
#

but enemies dont have inputs

rich bluff
#

pass null, handle it, or

slender nymph
#

separate the input from the behavior

rich bluff
#

wrap methods like that into an input receiver and the method that actually does something

static bay
ionic zephyr
dense monolith
#

struggling to make my camera not inverted :/ can someone help?

ionic zephyr
#

which doesnt need the context

rich bluff
#
void OnShootInput(context) => Shoot();
static bay
#

You should make a class that handles Input, which then calls stuff on your Player component.

slender nymph
eternal falconBOT
static bay
#

Now what your player can do is separated from input.

short hazel
#

Or yeah just make an overload, a method which has the same name, but no parameters. This is allowed in C#

ionic zephyr
short hazel
#

And one calls the other

ionic zephyr
#

but events need context right?

#

ooooooh I see

#

I should create methods in the InputScript that call the Shoot Method in other script, right?

static bay
#

yes

ionic zephyr
static bay
#

Think of the player like a puppet. Your Input is just the one pulling the strings.

#

Theoretically, you can have anything "pulling the strings".

#

Whether that be input from the player, or some AI.

#

I notice that you have a Coroutine there. Keep in mind that the player should still handle the management of its state. Your Input script can keep hammering the Shoot method every time the user presses a button. The player should just know that it's already shooting, and shouldn't do so again until ready.

dense monolith
slender nymph
#

have you gotten your IDE configured yet?

dense monolith
proven junco
#

yo

#

how do I have an UI pop up when I am close to an object

#

like an interaction ui

rich adder
proven junco
#

no

#

haha

rich adder
#

oh.. always best to check there first, you'd be surpised how many people wanting to do this for years

wintry quarry
proven junco
#

yeah found an reddit post with description on kinda what to do

#

so imma take that to ai

rare basin
#

jezus dont please

proven junco
#

--

rare basin
#

do you want to learn anything

#

or blidnly copy&paste bad chat gpt code

proven junco
#

yeah I really do want to learn

polar acorn
rare basin
#

then why are you using ai

#

instead of trying it yourself

proven junco
#

but rn I have around 9 days to complete an game alone with slim very slim experience with coding

rich adder
#

lets face it calling it AI is a bit of an overstatement..

#

its a fancy search engine..nothing "intelligent" about it

eternal needle
#

Next we'll see "why doesnt this work"

//use this function to detect when close to an object
void OnTriggerEnter(...) 
{ 
// make the object you want visible
}
proven junco
#

so I am really tight with time

#

but I will deff learn coding after these days when I have time

uncut wolf
#

Sorry if i'm interrupting. I've got i simple question why don't i get proper typehints?

proven junco
#

cuz rn I just need to complete it

eternal falconBOT
short hazel
#

9 days for a game from scratch? No, you had a few months and panicked when you realized the assignment is due very soon

proven junco
#

I had maybe 2 months

rocky canyon
#

and u waited until a week and a half?

proven junco
#

bro it is complicated

short hazel
#

Yup, it may be way too late now

rocky canyon
#

2 months is enough time to make a smal game

proven junco
#

no it aint too late

#

i'

eternal needle
#

It is

proven junco
#

ive done a whole map and a lot of models in just some days

slender nymph
#

no prior experience or knowledge of how to make a game? 9 days is way too low

rocky canyon
uncut wolf
eternal needle
#

I (someone who has been coding for 10 years) couldnt even be paid to make a game in 9 days.

rocky canyon
#

games take time

rich adder
polar acorn
#

Well, with nine days you'd better hit the books and start a deep dive of the documentation

short hazel
#

Learn the basics, do a simple game, get an average grade and let this be a lesson for the next one

proven junco
#

yeah I know

slender nymph
proven junco
#

I'm making a horror game alr

#

with task thingy

#

and I have an interaction and walk system

#

but I need more comlicated

dense monolith
proven junco
#

and ofc make it a little better for the end prod

rocky canyon
#

watch a youtube tutorial..

proven junco
#

yeah I have found some that has been helpful

eternal needle
slender nymph
rocky canyon
#

copying and pasting EXACTLY and using pre-made assets from the unity store is probably ur only solution considering the circumnstances

polar acorn
proven junco
#

like actual game making scripts

#

and not just mov

eternal needle
#

There was an AI system that went on sale, got it as part of a bundle and it was absolutely unusable

proven junco
#

yeah rn I'm using perplexity

rocky canyon
#

yap, AI is whats gonna screw you over

proven junco
austere hedge
#

I have a method called PlaySound.

public static void PlaySound(Sound sound, float volume, float pitch)

"Sound" is an enum. From a different class, I'm trying to call that method.

SfxController.PlaySound(Sound.AttackFlesh1, 1f, 1f);

Sound.AttackFlesh1-4 works. But I have 4 different AttackFlesh sound effects, so what I want to do is this:

int i = Random.Range(1, 5);
SfxController.PlaySound(Sound.AttackFlesh[i], 1f, 1f);

However, I get an error. Does anyone know what I'm missing?

proven junco
#

or ai in gen