#💻┃code-beginner

1 messages · Page 515 of 1

rich adder
#

because if nothing is showing up as expected, I'm willing to bet you named your InputActions PlayerInput so now its probably trying to grab the wrong thng

frozen burrow
#

oh yeah I did that

#

I renamed the InputActions to something else and deleted the previous code that was generated as PlayerInput, however I still can't acess the props/funcs from PlayerInput

frozen burrow
#

oh nevermind, the script I deleted had a clone, I deleted it and it worked. Thank you for your help! ✨

severe onyx
#

when using this sort of code to rotate my camera around (0,0,0) based on mouse movement how do I keep the rotation up and down absolute to the world space instead of having my rotation angle change after the camera has rotated to the left or right?

                    transform.RotateAround (Vector3.zero,Vector3.up,mouseX * rotateSpeed * Time.deltaTime);
                else
                    transform.RotateAround(Vector3.zero, Vector3.right, mouseY * rotateSpeed * Time.deltaTime);```
rocky canyon
#

i tend to use a container within a container. and rotate each seperately.

fierce shuttle
#

I would suggest W3schools c# course: https://www.w3schools.com/cs/index.php - they have interactive lessons that let you experiment with the code you learn in a sandbox-like environment, and I think once you have a good understanding of C# in general (outside the context of engine terminology like "Game Objects"), then trying the Unity Learn tutorials the bot linked will be easier to follow, but everyone learns differently so pick what is most effective for how you personally learn best, there are also blogs, books and YouTube tutorials covering the basics of C# as well, if you prefer other forms of learning

#

The course I linked specifically focus on learning C# as a language on its own, once you have that understanding, Unity Learn will teach you the basics of how to use the engine in general, from there, sure you can make anything youd like, 2D, 3D, 2.5D or anything you want, but I think youll first want a good understanding of C# and the engine separately before diving into any specific project

rich adder
#

3d/2d will be irrelevant the code more or less is the same in unity

#

if you learn c# you can read any API. Including unity

rocky canyon
#

typically taht takes some experience of knowing what not to do

severe onyx
rocky canyon
#

wouldnt be that hard.. keep ur flying stuff on the gameobject ur rotating now..
rotate that only 1 direction (up and down for example).. then create a new container within that one that would only control left and rightfor example

#

itd just require splitting up the rotation stuff.. but theres other ways to do it as well..

#

its normally just a difference of using local and global directions

severe onyx
#

yeah I saw the transform.Rotate function has a way of specifying rotation relative the self or relative to world space

#

but that does not seem to be an option for transform.RotateAround for some reason

rocky canyon
#

might try fiddling that that first before refactoring anything

severe onyx
#

unsure how to use the Rotate to achieve what RotateAround does tbqh

rocky canyon
severe onyx
#

I looked at it and I understand how it should work in theory and that the math itself isn't exactly complicated but my brain is kinda jamming up trying to write the actual code here

tiny grove
#

i am making a menu for which i have added a button component to my start game image on the canvas, in the button, in the on click section i am giving the object i attached the start game image to but the function is not showing up

rocky canyon
#
            // rotate the camera on its X axis (up and down)
            transform.localRotation = Quaternion.AngleAxis(-currentLookingPos.y,Vector3.right);

            // rotate the player on its Y axis (left and right)
            controller.transform.localRotation = Quaternion.AngleAxis(currentLookingPos.x,controller.transform.up);```
tiny grove
#

what am i doing wrong?

rocky canyon
#

angle axis is a good one to use

#

u can kinda see here (im using two objects to rotate) to keep them seperate.

#

on the camera UP and DOWN im using Vector3.right (a global rotation)

#

for the player LEFT and RIGHT im using transform.up (a local direction)

rich adder
rocky canyon
#

well atleast 2..

severe onyx
#

the camera

#

using it's own transform.right to rotate around instead of the global vector3.right for up and down actually solved it I think?

#

let me test a bit more but looks promising right now

proven matrix
#

Guys why can't i add conditions in my transitions?

wintry quarry
proven matrix
#

Ah 🤦

summer shard
#

is there a way to get dictionary capacity?

rich adder
summer shard
rich adder
#

Dictionary doesnt store anything but just the references

summer shard
#

wdym?

rich adder
#

also for Dictionary easier to use a foreach loop

summer shard
rich adder
summer shard
rich adder
#

yes

summer shard
#

and the inventory max capacity is 4

zenith cypress
#

You can't get the capacity without reflection, as you aren't meant to really need it. Sounds like you want Count instead. It doesn't even look like you need a dictionary either. Just use an array if you just have 4?

rich adder
#

yeah just go with array

#

what is the point of using dictionary if you have indexes anyway

#

generally the List/array is faster

summer shard
#

can't arrays be infinite?

zenith cypress
#

Arrays are always a constant size, so no

summer shard
#

okay, so how can i get the array's capacity?

stone pilot
#
public float destroyDelay = 2f;

Vector2 startPos;

[SerializeField] private Rigidbody2D rb;

private void Start()
{
    startPos = transform.position;
}

private void OnCollisionEnter2D(Collision2D collision)
{
    if(collision.gameObject.CompareTag("Player"))
    {
        StartCoroutine(Fall());
    }
}

IEnumerator Fall()
{
    yield return new WaitForSeconds(fallDelay);
    rb.bodyType = RigidbodyType2D.Dynamic;
}

public void Reset()
{
    transform.position = startPos;
    rb.bodyType = RigidbodyType2D.Kinematic;

    // Reset velocity and rotation
    rb.velocity = Vector2.zero;
    rb.angularVelocity = 0;
    transform.rotation = Quaternion.identity;

    Debug.Log("FallingPlatform has been reset.");
}```

**even the debugging is working**
rich adder
#

.Count is for anything that can Add/Remove entries (expandable collections)

#

eg a List, Dictionary etc

languid spire
summer shard
#

so something like this?

    private int getInventoryAvailableIndex() {
        for (int i = 0; i < inventory.Length; i++) {
            if (inventory[i] == null) return i;
        }
        return -1;
    }
``` and does it error if im trying to index a null value?
rich adder
verbal kiln
#

Hi guys, I would like to ask you to help me, if you help me, I will be glad. In general, there is such a problem, I want to create a code in which the doors will open like phasmaphobia, please help. Here is the code using UnityEngine;

public class Door : MonoBehaviour, IInteractable
{
public float openAngle = 90f; // Угол открытия двери
public float openSpeed = 2f; // Скорость открытия двери
private bool isOpen = false; // Состояние двери (открыта/закрыта)
private Quaternion closedRotation; // Начальная позиция двери
private Quaternion openRotation; // Позиция двери в открытом состоянии

void Start()
{
    closedRotation = transform.rotation;
    openRotation = closedRotation * Quaternion.Euler(0, openAngle, 0);
}

void Update()
{
    if (Input.GetKeyDown(KeyCode.Mouse0))
    {
        Interact();
    }

    // Плавное открытие и закрытие двери
    if (isOpen)
    {
        transform.rotation = Quaternion.RotateTowards(transform.rotation, openRotation, openSpeed * Time.deltaTime);
    }
    else
    {
        transform.rotation = Quaternion.RotateTowards(transform.rotation, closedRotation, openSpeed * Time.deltaTime);
    }
}

public void Interact()
{
    isOpen = !isOpen; // Переключение состояния двери
}

}

summer shard
#

!format

rich adder
eternal falconBOT
summer shard
#

wow

rich adder
#

i specifically said read it, and you did not read it..

#

perfection

stone pilot
#
{
    rb.bodyType = RigidbodyType2D.Kinematic;
    transform.position = startPos;

    rb.velocity = Vector2.zero;
    rb.angularVelocity = 0;
    transform.rotation = Quaternion.identity;

    Debug.Log("FallingPlatform has been reset.");
}```
#

this works?

verbal kiln
#

Hi guys, I would like to ask you to help me, if you help me, I will be glad. In general, there is such a problem, I want to create a code in which the doors will open like phasmaphobia, please help. Here is the code

summer shard
rich adder
molten pulsar
#

hi i have a problem

stone pilot
rich adder
stone pilot
rich adder
rich adder
stone pilot
#

Wait, the body type isn't even being set to Kinematic?

#

There's a problem I will check the death script

verbal kiln
rich adder
stone pilot
# rich adder well then thats issue, dynamic rb will override transform pos
{
    rb.simulated = false;
    rb.velocity = new Vector2(0,0);
    transform.localScale = new Vector3(0,0,0);
    tr.emitting = false;
    yield return new WaitForSeconds(duration);
    transform.position = startPos;
    transform.localScale = new Vector3(1,1,1);
    rb.simulated = true;

    StartCoroutine(trail());
    cam.ChangeColour();
    if (fp != null)
    {
        fp.Reset();
    }
}```
#

What's wrong here?

#

(fp is the fallingPlatform script)

rich adder
stone pilot
#

but it's not

#

working

rich adder
#

ddid you put log inside fp.Reset() method to see if its running

stone pilot
#

I did ig

verbal kiln
stone pilot
#

and the debug is popping up in the editor

rich adder
stone pilot
#

so I still don't know whats the issue

verbal kiln
#

yeah

rich adder
languid spire
stone pilot
verbal kiln
stone pilot
#

But why the setting rigid body type to Kinematic not working?

rich adder
# verbal kiln yeah

you can use without physics but easier to use physics as beginner, put the door as rigidbody then use a hinge at corner so it rotates around it, when you want to Pull door use raycasthit rigidbody of door to AddForce(playerPos - doorPos )
or do opposite dir to push

stone pilot
#

rb.bodyType = RigidbodyType2D.Kinematic;

#

That's not working

#

When the Reset func gets called

verbal kiln
#

please

rich adder
#

you can just turn Simulated off and reset pos, you prob dont even need that

stone pilot
# rich adder find out why

I tried setting the rb body type to kinematic in the editor but even setting the rb to kinematic keeps the platform falling

stone pilot
#

didn't work

rich adder
# verbal kiln can you help me with this?

how do do you want me to help you ? I told you more or less the steps, you need to research each one. Break down bigger problem into smaller easier to solve ones.

verbal kiln
#

I will try to do something, thanks in advance!

stone pilot
# rich adder show the platform code

Here

{
    public float fallDelay = 1f;
    public float destroyDelay = 2f;

    Vector2 startPos;

    [SerializeField] private Rigidbody2D rb;

    private void Start()
    {
        startPos = transform.position;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.CompareTag("Player"))
        {
            StartCoroutine(Fall());
        }
    }

    IEnumerator Fall()
    {
        yield return new WaitForSeconds(fallDelay);
        rb.bodyType = RigidbodyType2D.Dynamic;
    }

    public void Reset()
    {
        rb.bodyType = RigidbodyType2D.Kinematic;
        transform.position = startPos;

        rb.velocity = Vector2.zero;
        rb.angularVelocity = 0;
        transform.rotation = Quaternion.identity;

        Debug.Log("FallingPlatform has been reset.");
    }
}```
rich adder
rich adder
stone pilot
rich adder
#

its calling 3 times?

stone pilot
#

So it got called 3 times

verbal kiln
stone pilot
#

But that's not the case

rich adder
verbal kiln
#

Thanks

rich adder
#

nvm

#

dont name the method Reset()

#

thats already unity method

stone pilot
#

Oh ok

#

I will call it ResetPosition()

rich adder
#
  public void ResetPlatform()
  {
      rb.simulated = false;
      rb.position = startPos;
      rb.velocity = Vector2.zero;
      rb.angularVelocity = 0;
      transform.rotation = Quaternion.identity;
      rb.simulated = true;
      Debug.Log("FallingPlatform has been reset.");
  }```
#

try this one

stone pilot
#

Alright

rich adder
#

idk if .position has to wait till simulated is on to work, if it doesn't try transform.position again

stone pilot
#

Still didn't work, but I Tried freezing the y pos then setting the Kinematic and I think that worked

#

I will try this

summer shard
#

is doing a for loop for 4 game objects bad in update?

molten pulsar
#

hi

#

im having this problem

#

i need that a object that is a child of other dont follow the rotation of the parent object

#

theres a way to do that?

rich adder
#

have plenty of scripts that iterate hundreds of objects in an update / costum tick loop

#

just be smart about it

summer shard
#

nvm i wanted to hide all inventory objects every frame except the one that is equipped but i changed it to be only if player changed the item

rich adder
#

thats usually the smarter way to go when events aren't possible

#

but usually events are the best, Observer pattern. Only do something when something happened

languid spire
rich adder
#

or just position constraint works if you dont need anything else

molten pulsar
#

okay

#

i making a musket game

#

and i need that musket follow the player rotation when he is pointing to something

#

but dont when the musket is idle

#

i will try that

rich adder
#

in this case use the parent constraint and you can probably just toggle the rotation follow option there via code,

molten pulsar
#

okay

#

thx for that information

stone pilot
#

Damn I finnaly got it working

verbal kiln
summer shard
#

is this a bad practice?

struct InventoryKey {
    public KeyCode key;
    public int index;

    public InventoryKey(KeyCode key, int index) {
        this.key = key;
        this.index = index;
    }
}

private static InventoryKey[] inventoryKeys = {
    new InventoryKey(KeyCode.Alpha1, 0),
    new InventoryKey(KeyCode.Alpha2, 1),
    new InventoryKey(KeyCode.Alpha3, 2),
    new InventoryKey(KeyCode.Alpha4, 3),
};
rich adder
summer shard
summer shard
rich adder
summer shard
#

i mean now when i look at the code i have to do foreach array in the update look to get if player pressed the keycodes...

rich adder
#
   [SerializeField] private KeyCode[] weaponKeys = new KeyCode[] { KeyCode.Alpha1, KeyCode.Alpha2, KeyCode.Alpha3, KeyCode.Alpha4 };
   private void Update()
   {
       for (int i = 0; i < weaponKeys.Length; i++)
       {
           if (Input.GetKeyDown(weaponKeys[i]))
           {
               currentWeaponIndex = i;
               Debug.Log("Detected " + weaponKeys[i]);
           }
       }
   }```
verbal kiln
summer shard
rich adder
ivory bobcat
#

There's only four elements

rich adder
#

what you do inside a loop is far more important than having a loop

#

if you're instantiating objects with a loop without conditions in update yes, you will melt your pc soon

summer shard
#

i mean this looks bad but im guessing it's more optimized than the loop??

        if (Input.GetKeyDown(KeyCode.Alpha1)) {
            ChangeInventoryIndex(0);
        } else if (Input.GetKeyDown(KeyCode.Alpha2)) {
            ChangeInventoryIndex(1);
        } else if (Input.GetKeyDown(KeyCode.Alpha3)) {
            ChangeInventoryIndex(2);
        } else if (Input.GetKeyDown(KeyCode.Alpha4)) {
            ChangeInventoryIndex(3);
        }
rich adder
#

this is literally worse but ok
this goes against one of the main principles of DRY (Don't repeat yourself)

ivory bobcat
#

Where you'd be able to repeat some patterns.

languid spire
summer shard
verbal kiln
rich adder
#

ah yes lets base performance on how things "look"

summer shard
ivory bobcat
#

The first assumption that loops are bad is incorrect

rich adder
languid spire
summer shard
rich adder
#

if its somehow is more legible to you, thats more valid than assuming for loops are issues in update performance wise or anything ..

languid spire
ivory bobcat
#

If there were a hundred elements, you'd be stuck either hard coding a hundred if-else statements or using a loop with one if statement.

summer shard
rich adder
#

thats only because you have wrong assumptions

summer shard
#

yea 😦

rich adder
#

writing Input.GetKeyDown 4+ times instead is considered "wrong" just by the fact you wriote the same thing that many times instead of 1 time

languid spire
verbal kiln
# verbal kiln

as you can, please help, look through the messages and video that I sent you, help, I beg you.

verbal kiln
rich adder
#

and did you loock the rigidbody on it?

#

I will show you my setup, but I need to open it . be patient though

verbal kiln
rich adder
verbal kiln
#

could you drop your door?

ivory bobcat
#

If you're looping for some sort of validation every frame (null check etc), it can be bad as you could find other preventative means. If you're looping to iterate some collection to repeat a necessary task (polling for input is necessary unless you're using events - likely polls under the hood anyways but without you needing to do so multiple times), it's technically more sane than brute forcing a bunch of repetitive lines. Here you'd benefit from refactoring. @summer shard

verbal kiln
# rich adder

stop, show me what you have in the inspector for the two objects, and how you did it hange

#

if you can send a video please

rich adder
#

ill show you setup vid one sec

lunar hollow
#

This is not code related, but i cant get the Package Manager to work, when i go to The My Assets Tab i get an error related to the Unity ID, i am Logged in, have no Firewall and no proxy settings, does anyone know what could cause this, or how i could download packages without the manager?

verbal kiln
verbal kiln
verbal kiln
summer shard
#

how do i get the amount of items (not null) in a fixed array

rich adder
verbal kiln
verbal kiln
rich adder
verbal kiln
rich adder
#

strongly suggest you do start learning some of this stuff with the Unity learn courses

#

it will be easier to modify / use scripts

verbal kiln
#

Thanks for your help!

cursive rover
#

Can someone help me? My camera is jittery (when rotating) but only in the unity editor. When i build the game everything is fine. I cant really test my game with the jittery camera. Here is my Look function (executed in fixed update of my player movement script)

//Looking around by using your mouse
    private void Look()
    {
        float num = Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime * sensMultiplier;
        float num2 = Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime * sensMultiplier;
        desiredX = playerCam.transform.localRotation.eulerAngles.y + num;
        xRotation -= num2;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);
        FindWallRunRotation();
        actualWallRotation = Mathf.SmoothDamp(actualWallRotation, wallRunRotation, ref wallRotationVel, 0.2f);
        playerCam.transform.localRotation = Quaternion.Euler(xRotation, desiredX, actualWallRotation);
        orientation.transform.localRotation = Quaternion.Euler(0f, desiredX, 0f);
    }

And here is my camera move script (in a camera empty containing the main camera as a child)

using UnityEngine;

public class MoveCamera : MonoBehaviour {

    public Transform player;

    void Update() {
        transform.position = player.transform.position;
    }
}
slender nymph
cursive rover
#

Thanks! I will try that out.

rich adder
cursive rover
verbal kiln
summer shard
#

whenever i drop the item, it either doesn't drop in the right position but straight out of the hand, or teleports to the raycast position for a split second then teleports back to the hand or it works normal BUT ONLY whenever the interpolation is set to interpolate or extarpolate, on none it works fine

public bool DropHeldObject(bool throwObject) {
    if (heldInventoryIndex < 0 || inventory[heldInventoryIndex] == null) return false;
    Pickable heldPickable = inventory[heldInventoryIndex];
    Rigidbody heldRigidbody; Vector3 dropPosition; RaycastHit hit;

    if (!heldPickable.TryGetComponent<Rigidbody>(out heldRigidbody)) return false;
    dropPosition = Physics.Raycast(cameraHolder.position, cameraHolder.forward * dropDistance, out hit, dropDistance) ? hit.point :
                                                                                cameraHolder.position + cameraHolder.forward * dropDistance; //If the raycast is correct then teleport to raycast hit else teleport using the front of the camera

    heldRigidbody.isKinematic = false;
    heldRigidbody.transform.position = dropPosition; //MovePosition doesn't change anything=
    heldRigidbody.AddForce(throwObject ? cameraHolder.forward * dropStrength : Vector3.zero);

    inventory[heldInventoryIndex] = null;
    ChangeInventoryIndex(-1);

    return true;
}
slender nymph
cursive rover
verbal kiln
summer shard
# rich adder start debugging

i mean what is there to debug, the position only changes correctly whenever interpolation is set to none. im just trying to see if maybe i change the position in non-correct way

slender nymph
cursive rover
slender nymph
#

can you at least select the correct language to include syntax highlighting if you're going to use pastebin

cursive rover
verbal kiln
# rich adder start debugging

oh that's it, I fixed the error in the code, your names are slightly different, they are together in the code, but the folder name is different

verbal kiln
naive shoal
#

Am I allowed to share my Git here or anywhere to allow someone to review my game? I'm doing a course as an absolute beginner and I'm struggling with some parts

short hazel
#

!code posting guidelines below

eternal falconBOT
dire flare
#

Pls where can I get free asset not copyright I want to use it for my game

short hazel
rich adder
dire flare
#

Am scare to use some one work and later hold my game for copyright

verbal kiln
rich adder
cosmic quail
verbal kiln
short hazel
#

And if you still have doubts on whether you can use an asset or not, talk to someone competent in that matter, like a lawyer

rich adder
verbal kiln
dire flare
#

Megascan thanks guys

#

What of audios

rich adder
rich adder
#

you just...plug it in..

verbal kiln
#

aaa

#

i stupid

#

and what should I put in the firepoint?

rich adder
#

the type it wants

verbal kiln
#

im idiot

#

thanks

rich adder
#

np

verbal kiln
#

and what button does it open on anyway?

#

otherwise it won't open

rich adder
#

the script has that I think

verbal kiln
rich adder
rich adder
#

read the error message it tells usually exactly where to look for

jaunty coyote
#

quick question, why does nameshagent.SetDestination(player.position); stop the AI? it gets called every frame in the update, asking because its the first time this would cause an issue and fully stop the agent

rich adder
#

possibly because its being called every frame, iirc they changed that

night mural
#

from the docs

Note that the path may not become available until after a few frames later. While the path is being computed, pathPending will be true. If a valid path becomes available then the agent will resume movement.

#

so you're asking for a path, then it starts calculating one, then you ask for it again, then it starts calculating one, repeat forever

ember tangle
#

I've written a caching system for projectiles, to be used in other systems in my game as well. This is my first time using generics. I'd love some feedback if you want to look https://hatebin.com/rufpfodmdd

jaunty coyote
#

but i need my path being updated, the player is moving afterall

ember tangle
#

Each object adds itself to the queue through an awake function in a manager object.

night mural
jaunty coyote
#

everytime the setdestination is called the velocity gets set to 0

#

is it possible to disable that?

night mural
night mural
jaunty coyote
jaunty coyote
ember tangle
bitter sage
#

What's a good resource to look into in properly revoking the script from certain exports?

crisp hamlet
#
void RotateWheels(){
        float carSpeed = Vector3.Scale(carRb.velocity, transform.forward).magnitude;
        float horizontalInput = Input.GetAxis("Horizontal");
        foreach(GameObject wheel in wheels){
            float rotationAngle = CarPhysics.CalculateWheelTurnSpeed(carSpeed, wheelRadius);
            wheel.transform.Rotate(rotationAngle, 0f, 0f, Space.Self);
        }

    }
    void turnFrontWheels(){
        float horizontalInput = Input.GetAxis("Horizontal");
        frontLeftWheel.transform.localEulerAngles = new Vector3(
            frontLeftWheel.transform.localEulerAngles.x,
            horizontalInput * maxTurnAngle,
            frontLeftWheel.transform.localEulerAngles.z
        );
        frontRightWheel.transform.localEulerAngles = new Vector3(
            frontRightWheel.transform.localEulerAngles.x,
            horizontalInput * maxTurnAngle,
            frontRightWheel.transform.localEulerAngles.z
        );
        frontLeftWheel.transform.localRotation = Quaternion.Euler(frontLeftWheel.transform.localEulerAngles.x, horizontalInput * maxTurnAngle, frontLeftWheel.transform.localEulerAngles.z);
    }``` 

Does anyone know why my wheels turn 180 degrees on z axis? i dont change it anywhere so im quite confused
night mural
nocturne kayak
night mural
# crisp hamlet ```cs void RotateWheels(){ float carSpeed = Vector3.Scale(carRb.velocity...

it seems wrong to me that your rotation angle is based on your wheel turn speed, but maybe it makesa sense?
generally though, you won't get consistent rotations if you are using quaternion.euler, since a given euler representation can have multiple quaternion representations, and unity might convert inconsistently when it's setting that rotation. The solution is to maintain your own Quaternion which you modify, then set the actual rotation from

jaunty coyote
crisp hamlet
jaunty coyote
nocturne kayak
#

In that case, do you have any pointer on how i could begin to try and implement collisions in that usecase? (video0

crisp hamlet
jaunty coyote
nocturne kayak
#

Coolio

#

I think kinematic does have collision tho

night mural
nocturne kayak
#

otherwise there would be no kinematic character controllers

night mural
#

a character controller is usually already having been doing that

nocturne kayak
#

I don't think i'm gonna need to go as far as implementing a character controller for this

#

I'm just mulling over what would be the best say to simply

#

Stop the cube if it hits a wall

timber tide
#

Everything can be done with raycasts

#

with that being said, you can just use character controller as it's a raycast based solution

halcyon dagger
#

ayo, does anyone know how to increase the fps limit on the game window inside the editor? its capped at 30

steep rose
halcyon dagger
past spindle
#

I’m coding for a 3D game where objects Instantiate in the sky, fall, and then explode when they hit the ground. My explosion code is right above the destroy object code in the collision method but for some reason my explosions are happening when the objects instantiate.

rich adder
#

this is a coding channel

rich adder
lunar hollow
#

yeah, but ive looked absolutely everwhere to no help, so this was my last resort.

lunar hollow
#

thanks

past spindle
#

I don’t have it in front of me unfortunately. The destroy object code is working as it should though, if that helps.

rich adder
#

idk what that means because I don't have the context and it would be hard to make assumptions

past spindle
#

I can try again after dinner if not

rich adder
#

come back when you got the code then lol

past spindle
#

Ok

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

public class LilTest : MonoBehaviour
{
    private CharacterController characterController;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        Debug.Log(characterController.isGrounded);
    }
}

Shouldnt this be printing true? what am I missing? Why is the cube not being detected as grounded?

#

Please helpnotlikethis

rich adder
#

as it checks the last move made

#

also might be starting to low within the ground

halcyon dagger
#

so, sticking a characterController.Move(Vector3.zero); inside the update should do?

halcyon dagger
#

half the time is true the other half is false XD

rich adder
# halcyon dagger

did you remove the other collider and also get it out of the ground ?

halcyon dagger
#

yeah

rich adder
#

not sure, i just use physics queries

#

isGrounded is finnicky

halcyon dagger
rich adder
#

yup

#

anything that returns more than 1 collider always use nonalloc tho

halcyon dagger
#

The thing is that im making a 3d player controller and ill need to use physics later so i really need to use a rigidbody, however, character controller has a few thigs regarding slopes and allat that id like to have instead of having to build from 0

#

but rb.addForce used for movement doesnt quite like me, for exaple when stopping going up on a ramp or a slope, it does a lil jump

rich adder
#

either controller / way you choose still need physics queries to detect ground imo

halcyon dagger
#

been watching a few tutorials and there is people toggling the rigidbody and character controller in and out of the gameObject when they need to apply a force but it seems unsafe and overcomplicated for me

rocky canyon
#

i would agree w/ u

halcyon dagger
rich adder
#

you can replicate forces through lerps / curves so its no big deal

#

dynamic rb is fun but there are annoying things to work around

timber tide
#

The majority of Unity tutorials uses character controller (somewhat surprising) so if you wanna download one of those templates and open it up to play around with it

rich adder
#

there is also KCC is free now which is a rb but set as kinematic

timber tide
#

I would implement gravity and test collision with that instead of dragging it around on the scene

halcyon dagger
#

🤔

halcyon dagger
timber tide
#

rigidbody comes with gravity

nocturne kayak
#

but i can't for the love of me figure out what's going on there

halcyon dagger
#

how was it

nocturne kayak
#

i can't even copy the collision system

#

It's very feature complete, of course

#

but for beginners (me) the code it a tad too complex

#

i'm facing a similar problem

#

i just want the cube to collide with walls

#

what the hell

full coral
#

I'm making a computer/android game for school and for some reason the enemies aren't receiving hits on mobile. Only computer. I'm raycasting a canvas into a 3d space and a trail rendered follows said raycasting. But for some reason clicking on the enemy doesn't work at all only in mobile. It works fine to interact with UI widgets but the enemy ignores it

verbal dome
nocturne kayak
#

manually setting the transform.position through code

halcyon dagger
#

look at this

timber tide
#

Im pretty sure that has its own methods of movement to call

halcyon dagger
verbal dome
rich adder
halcyon dagger
nocturne kayak
#

But how'd i go about implementing that? how do i check if it's going to collide before it collides?

halcyon dagger
verbal dome
#

Because that means it is blocked

rich adder
halcyon dagger
#

thanks anyways, i really appreciate the help

#

:)

sick glade
#

Sup. I'm working on my first game currently, which is a port of a board game me and my friend made. I want to make an efficient Object Spawning system that I won't have to remake later, is a Singleton ObjectManager class like I'm using the best way to go about this?

rich adder
#

efficient in what way

sick glade
#

When I say efficient I'm thinking reusable in whatever context I need something spawned

#

I'm not sure if theres a standard for game design or not

rich adder
#

then you want to look into object pooling

sick glade
#

I'll look into it

vale karma
#

how could I get the mesh of a SkinnedMeshRenderer to see the highest vertex of the mesh every frame? i keep going down rabbit holes that are talking about general stuff. I cant find the solution

timber tide
#

If it's instanced data then you're probably going to have to do some readback on the vertex buffers

vale karma
#

idk anything about what buffers are, ill start there

timber tide
#

Usually the skinned stuff is all instanced on the GPU

#

probably easier to just open it in blender

past spindle
#

private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
explosionFX.Play();
Destroy(gameObject);
}
}

#

Anybody know why this would be animating explosions during instantiation of the game object?

teal viper
vale karma
past spindle
#

ok, thanks

teal viper
timber tide
#

Oh, thought you meant highest vertex count

vale karma
#

it has a blendshape that has some code, but some things look funny or act weird bc theyre fixed to a certain point when spawning in. If it was able to parent to the top vertex thatd be the vest

timber tide
#

Right, sort by bone is probably the idea first off

vale karma
#

I havent delt with bones, how would those be different from just grabbing the vertex?

#

ill show a lil bit of my issue one sec

teal viper
teal viper
#

And probably more performant.

vale karma
#

sweet, i learned a little bit about some shaders, but not enough to do what i need yet. I was able to make a wave cube lol

timber tide
#

You can also create a non-moving empty bone for your character which you can assign as a pivot too if you want to do it that way

verbal dome
#

Skinnedmeshrenderer.BakeMesh would work but its pretty slow since it has to skin the mesh again on the CPU

#

Definitely use the bone approach if that is accurate enough for you

vale karma
#

This is kind of hard to see. But the discord cap is at like 500mb. If you see when i transplant the cutting into the pot, the next stalk growing is from its base. As of now the entire system calculates the instantiate point from when the one before it is created. your saying compute shaders can fix this issue?

past spindle
#

@teal viper How does a debug log help when the two lines of code are next to each other? Don't they execute near-simultaneously?

teal viper
past spindle
#

I'm seeing the execution of both lines but at different times, and it looks like the first instantiation of clones are not being destroyed for some reason.

teal viper
vale karma
#

fudge its hard to show with the cap

teal viper
vale karma
#

the skinnedmesh is i guess created or used because the model imported has a blendkey in Blender. So it has the key in the SkinnedMeshRenderer instead of the FilteredMEsh or whatever

#

it grows from like a smallish dot to a long stem over the value of the key

past spindle
#

@teal viper void Start()
{
InvokeRepeating("SpawnSpheres", startDelay, spawnInterval);
}

// Update is called once per frame
void Update()
{

}
void SpawnSpheres()
{
int dropQuantity = Random.Range(1, 3);
if (dropQuantity == 1)
{
UnityEngine.Vector3 spawnPos1 = new UnityEngine.Vector3(Random.Range(-spawnRangeX, spawnRangeX), spawnPosY, Random.Range(-spawnRangeZ, spawnRangeZ));
Instantiate(sphere, spawnPos1, sphere.transform.rotation);
}
else if (dropQuantity == 2)
{
UnityEngine.Vector3 spawnPos1 = new UnityEngine.Vector3(Random.Range(-spawnRangeX, spawnRangeX), spawnPosY, Random.Range(-spawnRangeZ, spawnRangeZ));
Instantiate(sphere, spawnPos1, sphere.transform.rotation);
UnityEngine.Vector3 spawnPos2 = new UnityEngine.Vector3(Random.Range(-spawnRangeX, spawnRangeX), spawnPosY, Random.Range(-spawnRangeZ, spawnRangeZ));
Instantiate(sphere, spawnPos2, sphere.transform.rotation);
}
else if (dropQuantity == 3)
{
UnityEngine.Vector3 spawnPos1 = new UnityEngine.Vector3(Random.Range(-spawnRangeX, spawnRangeX), spawnPosY, Random.Range(-spawnRangeZ, spawnRangeZ));
Instantiate(sphere, spawnPos1, sphere.transform.rotation);
UnityEngine.Vector3 spawnPos2 = new UnityEngine.Vector3(Random.Range(-spawnRangeX, spawnRangeX), spawnPosY, Random.Range(-spawnRangeZ, spawnRangeZ));
Instantiate(sphere, spawnPos2, sphere.transform.rotation);
UnityEngine.Vector3 spawnPos3 = new UnityEngine.Vector3(Random.Range(-spawnRangeX, spawnRangeX), spawnPosY, Random.Range(-spawnRangeZ, spawnRangeZ));
Instantiate(sphere, spawnPos3, sphere.transform.rotation);
}
}

eternal falconBOT
teal viper
#

Or just the topmost vertex position at the time of growing?

vale karma
#

Weell yes and no, So as the plant grows, it already knows the next spot it will instantiate the branch or leaf. It creates a timing issue whwere the leaf already grows, or taking the branch off before the leaf grows it still grows on the old spot in the air. Its technically working based on a timing mechanic with blenshape values. Id rather the next child object on top of it follow the highest vertex, rather than betting on whatever spot it calculated at the start is right

#

at the time of growing to answer your question

teal viper
#

Kinda sounds like you have some overcomplicated logic there.

If it's not something you do every frame, maybe try what Osmal suggested. But honestly, I think there's a need to rethink the implementation choices.

past spindle
#

@teal viper So do I need to click these links? I don't understand the !code response. My apologies. I'm not a discorde native lol

eternal falconBOT
past spindle
#

-e

teal viper
prime goblet
#

how could i convert this class into a singleton?

public class SoundPlayer : MonoBehaviour {
    public AudioSource collide;
    public AudioSource merge;

    public void collideSound() {
        collide.Play();
    }
    
    public void mergeSound() {
        merge.Play();
    }
}
past spindle
mighty compass
#

Anyone here good with python?

teal viper
mighty compass
#

Having a lot of trouble with a Python school project, trying to make a game server that can have multiple client threads at a time.

teal viper
past spindle
#

@teal viper yes

teal viper
steep rose
teal viper
past spindle
#

@teal viper it seems to happen on all of them.

steep rose
#

do you have anywhere else in your code that calls the particles?

past spindle
#

@teal viper it did have play on awake checked. It seems to have changed something but not fixed the problem. Give me a sec to analyze.

#

@teal viper lol I actually have no explosions at all, but I think I can fix it. Odd that I'd be happy to break the game more, but at least it's a problem I understand. Thanks for the help.

north kiln
fierce shuttle
sleek siren
#

I'm using characterController.Move(direction * moveSpeed * Time.deltaTime) to move my player but it moves only when my fps is higher, when my fps is low player doesn't move at all but just sits there. No change in position

cinder schooner
#

possibly your direction has an issue

sleek siren
#

The script is too long to send here

sleek siren
#

[RequireComponent (typeof(CharacterController))]
public class PlayerController : MonoBehaviour
{
    //Exposed variables
    [Header("Attributes")]
    [SerializeField] private float moveSpeed;

    [Header("Settings")]
    [SerializeField] private float mouseSpeed;
    [SerializeField] private float nViewAngleLimit, pViewAngleLimit, playerReach;

    [Header("References")]
    [SerializeField] private MyInput input;
    [SerializeField] private Transform playerCameraTransform;

    //Private variables
    private CharacterController controller;

    private void Awake()
    {
        input.onInteract += CheckInteraction;
    }

    // Start is called before the first frame update
    void Start()
    {
        controller = GetComponent<CharacterController>();
        Cursor.lockState = CursorLockMode.Locked;
    }```
#
    void Update()
    {
        if(GameManager.gameState == GameState.GameRunning && !DialogueHandler.Instance.IsSpeaking)
        {
            Vector2 moveInput = input.GetMovementVectorNormalized();
            Vector3 moveDirection = transform.forward * moveInput.y + transform.right * moveInput.x;
            Vector2 mouseVelocity = input.GetMouseVelocityNormalized();

            HandlePlayerMovementAndRotation(moveDirection, mouseVelocity);
            KeepPlayerGrounded();
        }
    }

    private void KeepPlayerGrounded()
    {
        if (transform.position.y != 0f)
        {
            Vector3 position = transform.position;
            position.y = 0f;
            transform.position = position;
        }
    }

    private void HandlePlayerMovementAndRotation(Vector3 moveDirection, Vector2 mouseVelocity)
    {
        //Move and Rotate
        controller.Move(moveDirection * moveSpeed * Time.deltaTime);
        transform.Rotate(0f, mouseVelocity.x * Time.deltaTime * mouseSpeed, 0f);
        playerCameraTransform.Rotate(-mouseVelocity.y * Time.deltaTime * mouseSpeed, 0f, 0f, Space.Self);

        //Limit player top and bottom view
        float cameraUpAngleX = playerCameraTransform.rotation.eulerAngles.x;
        if (cameraUpAngleX > 180f)
        {
            cameraUpAngleX -= 360f;
        }
        cameraUpAngleX = Mathf.Clamp(cameraUpAngleX, nViewAngleLimit, pViewAngleLimit);
        playerCameraTransform.localEulerAngles = new Vector3(cameraUpAngleX, 0f, 0f);
    }

    private void CheckInteraction()
    {
        Ray ray = new Ray(playerCameraTransform.position, playerCameraTransform.forward);
        if(Physics.Raycast(ray, out RaycastHit hit, playerReach))
        {
            if(hit.collider.TryGetComponent<IInteractable>(out IInteractable interactable))
            {
                interactable.Interact();
            }
        }
    }
}```
waxen adder
#

You're gonna want to use a web service for posting big blocks like that

wintry quarry
cosmic oxide
#

can anyone help here?

thorny sluice
wintry quarry
cosmic oxide
#

thanks

nimble apex
#

if i want to clean up the value of a playerpref key, deletekey or setstring = ""

teal viper
nimble apex
#

if a key is "deleted", getint/getstring will not be nullref right?

#

its okay if returned value is 0, or ""

teal viper
nimble apex
#

NICE

#

ty

keen parcel
#

how can I change these componenet settings in a script?

summer shard
#

does anyone know why that's happening?

    public bool DropHeldObject(bool throwObject) {
        if (heldInventoryIndex < 0 || inventory[heldInventoryIndex] == null) return false;
        Pickable heldPickable = inventory[heldInventoryIndex];
        Rigidbody heldRigidbody; Vector3 dropPosition; RaycastHit hit;

        if (!heldPickable.TryGetComponent<Rigidbody>(out heldRigidbody)) return false;
        dropPosition = Physics.Raycast(cameraHolder.position, cameraHolder.forward * dropDistance, out hit, dropDistance) ? hit.point :
                                                                                    cameraHolder.position + cameraHolder.forward * dropDistance;

        inventory[heldInventoryIndex] = null;
        heldInventoryIndex = -1;

        heldRigidbody.isKinematic = false;

        heldRigidbody.position = dropPosition; //am i doing this wrong??
        heldRigidbody.AddForce(throwObject ? cameraHolder.forward * dropStrength : Vector3.zero);

        ChangeInventoryIndex(-1);

        return true;
    }
sand glen
summer shard
fickle plume
summer shard
fickle plume
#

Did you debug the problem to understand what's happening?

summer shard
# fickle plume Did you debug the problem to understand what's happening?

yup but i don't understand why is that happening, the drop position is correct, there's nothing else that's overriding the position of the object except this piece of code but i set the heldInventoryIndex and the reference in an array to null

//this is this piece of code
private void HandleHand() {
    for (int i = 0; i < inventory.Length; i++) {
        if (Input.GetKeyDown(inventoryKeys[i])) {
            ChangeInventoryIndex(heldInventoryIndex != i ? i : -1); //Inventory 
        }
    }

    if (heldInventoryIndex < 0 || inventory[heldInventoryIndex] == null) return;
    Pickable heldPickable = inventory[heldInventoryIndex];
    heldPickable.transform.position = objectHolder.position;
    heldPickable.transform.rotation = objectHolder.rotation;

    //Dropping object
    if (Input.GetKeyDown(KeyCode.G) || Input.GetKeyDown(KeyCode.Mouse1)) {
        DropHeldObject(Input.GetKey(KeyCode.Mouse1));
    }
}
#endregion
fickle plume
#

I'm not seing any debug messages

summer shard
#

wdym?

fickle plume
#

To solve the problem you need to actually understand it, use debugging tools I've linked.

fickle plume
#

Good, then you know where the problem is.

summer shard
#

i dont like bro

fickle plume
# summer shard i did that tho

You need to put debug messages at every step to understand what the program is doing. If you do that then you'll know what's happening.

summer shard
fickle plume
#

You don't have a single debug message.

#

You don't just throw code here for others to fix it.

summer shard
#

i removed the debug messages before i sent the code...

fickle plume
#

@summer shard You really don't get it. If you've debugged the problem this would've been solved already.

summer shard
fickle plume
summer shard
# fickle plume So you use debug messages to pinpoint the exact moment coordinates change

yea ```cs
public bool DropHeldObject(bool throwObject) {
if (heldInventoryIndex < 0 || inventory[heldInventoryIndex] == null) return false;
Pickable heldPickable = inventory[heldInventoryIndex];
Rigidbody heldRigidbody; Vector3 dropPosition; RaycastHit hit;

if (!heldPickable.TryGetComponent<Rigidbody>(out heldRigidbody)) return false;
dropPosition = Physics.Raycast(cameraHolder.position, cameraHolder.forward * dropDistance, out hit, dropDistance) ? hit.point :
                                                                            cameraHolder.position + cameraHolder.forward * dropDistance;

Debug.Log(dropPosition);

inventory[heldInventoryIndex] = null;
heldInventoryIndex = -1;

heldRigidbody.isKinematic = false;

heldRigidbody.position = dropPosition; //am i doing this wrong??
Debug.Log("Dropped the object lamo");
heldRigidbody.AddForce(throwObject ? cameraHolder.forward * dropStrength : Vector3.zero);

ChangeInventoryIndex(-1);

return true;

}

private void HandleHand() {
for (int i = 0; i < inventory.Length; i++) {
if (Input.GetKeyDown(inventoryKeys[i])) {
ChangeInventoryIndex(heldInventoryIndex != i ? i : -1); //Inventory
}
}

if (heldInventoryIndex < 0 || inventory[heldInventoryIndex] == null) return;

Pickable heldPickable = inventory[heldInventoryIndex];
heldPickable.transform.position = objectHolder.position;
Debug.Log("Changed the position of the object lol"); // here
heldPickable.transform.rotation = objectHolder.rotation;

//Dropping object
if (Input.GetKeyDown(KeyCode.G) || Input.GetKeyDown(KeyCode.Mouse1)) {
    DropHeldObject(Input.GetKey(KeyCode.Mouse1));
}

}

fickle plume
#

It's not just printing out things blindly, you probe state of the variables at different stages and find out where (or when) is the problem

summer shard
#

the position changed correctly but it didn't change

fickle plume
#

Examine what coordinate you are actually assigning.

#

You need to inspect everything.

fickle plume
#

If after assigning coordinates are wrong see what you are actually assigning

#

at that moment

#

Need to investigate and look up the chain of events.

summer shard
fickle plume
#

so print out what happening inside dropPosition each time

summer shard
fickle plume
#

and when it gets you incorrect data examine what you are feeding it to get that result

#

Make sure you are not mixing up local and global space as well

ivory bobcat
#

Basically, if it's being assigned the correct value either the code here isn't the issue (being overridden elsewhere) or the coordinate system isn't what you're expecting it to be.

summer shard
fickle plume
ivory bobcat
#

We're assuming the first is incorrect - possibly the second after proving the first.

fickle plume
summer shard
#

i turned off setting the position of the held object and as far as i've seen it works but i don't know why, since debugging told me that the drop happened after setting the position of held object ?

covert hemlock
#

when i create monobehavior script, I don't see the 'using System.Collections;' namespace. Is that normal?

cinder schooner
#

yes,

#

by default you don't "need" it

covert hemlock
#

ok ty

red cedar
#

does anyone know why my restart button is not working ?

summer shard
fickle plume
red cedar
#

sure I have it

fickle plume
#

do you get any errors

red cedar
#

no I didn't got any

fickle plume
#

debug that

#

Also your !ide is not configured, you won't get any error tracking there

eternal falconBOT
red cedar
red cedar
fickle plume
# red cedar

So when you load game over scene, do you keep the main one with don't destroy on load, does it exist at all, or you didn't assign button in the first place

red cedar
fickle plume
#

See if it is still assigned at runtime

red cedar
red cedar
languid spire
fickle plume
#

If it was assigned it would be executing. You might have another method with the same name doing nothing somewhere.

fickle plume
red cedar
#

Is it because of my event system?

languid spire
red cedar
fickle plume
red cedar
#

no

fickle plume
#

is it present when you press the button

red cedar
#

when I add canvas it already automatically add event system

languid spire
#

your button in not in your canvas

red cedar
languid spire
red cedar
#

😁

rancid tinsel
#

how do I check if a specific index in a char array or list is "empty"?

#

checking if == "" doesn't work since "" is a string i guess?

slender nymph
#

check if it equals default

lapis yew
rancid tinsel
wintry quarry
#

It can't be actually "empty", it will exist. But you can compare it to some known value like null

rancid tinsel
wintry quarry
#

Compare it to "" then

rancid tinsel
#

idk why it thinks its an int

slender nymph
wintry quarry
slender nymph
#

it cannot be null but it can be the null character (char)0

rancid tinsel
wintry quarry
#

Again yeah compare to some known value

wintry quarry
rancid tinsel
#

i was looking up unity instead of c# because im not very bright

slender nymph
#

that's still the first result

rancid tinsel
#

i searched this up since i didnt really understand what it was

wintry quarry
#

An array is merely a collection of multiple variables

rancid tinsel
frank flare
#

how can I check if something touches collider inside FixedUpdate() ? I don't want OnColliderTrigger or something because I want to put a few colliders

teal viper
frank flare
teal viper
desert plinth
frank flare
desert plinth
teal viper
desert plinth
#

And using SphereCasts also allows you to use FixedUpdate()

frank flare
desert plinth
teal viper
white obsidian
#

in my code i have these, but when i open my unity it doesnt show it even tho i did [SerializeField] to it, why?

wintry quarry
polar acorn
#

Do you have any compile errors

white obsidian
#

oh yeah i do have 1

wintry quarry
#

You must fix that first

#

then it will work

#

(even if it's from another file or something)

polar acorn
white obsidian
#

thanks guys

burnt skiff
#

hi im doing a 2d project and i want to change the camera background from the default blue background to a png but when i use the canvas it gets in front of my prefobs how do i fix this

wintry quarry
#

that's why it's called overlay

#

anyway this is not a CODE question

#

so you're asking in the wrong channel

burnt skiff
#

oh mb

#

which channel should i go to

burnt skiff
cosmic quail
flat tree
#

hello, I want to ask about unity projects;
I am a beginner so is there any project tutorials from unity from scratch till end where we learn basics and all working of unity editor and making whole games etc

wintry quarry
#

I'm sure many such things exist on youtube, sure

burnt skiff
eternal falconBOT
#

:teacher: Unity Learn ↗

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

flat tree
dim yew
#

i can't find out why i'm getting a nullref here, i would guess its something to do with the gamemanager

hexed terrace
#

whatever is on line 27 ..

cosmic quail
dim yew
#

so is this just a universal singleton issue?

#

or should i start using start for these things

hexed terrace
#

Initialise in Awake() get stuff in Start()

hasty tundra
#

i want to get a random point on the outline of a circle, essentially i want to be able to input a float value, then i want to be able to calculate a random point on a circle from 0,0 on that line. How would i calculate the correct x-y coordinates to make it accurate?

hexed terrace
#

FYi - next time you share code, include the line numbers. Don't make us guess/ assume which line has the error

dim yew
#

good idea, my bad

night raptor
odd widget
#

Hello

hasty tundra
odd widget
#

Does checking system date/hour by using DateTime.Now resource intensive? Is it okay to do it in void Update()?

hasty tundra
#

ok thatd prob work then 😭

rotund garnet
#

If i have a procedural world generation system that places chunks as the player moves around, would it then be bad practice to have a script on each chunk, that would just place smaller world props, like trash cans, and fire hydrants based on spawn points? Or should i have a script that searches for spawn points?

night raptor
# hasty tundra ok thatd prob work then 😭

One thing to note is that if the random point happens to be at the center which is very unlikely but possible, .normalized will return a zero vector so depending on how big of a problem that would be in your case, you might wanna do something like this:```cs
Vector2 randomOnCircle;
do
{
randomOnCircle = Random.insideUnitCircle.noramlized;
} while (randomOnCircle != Vector2.zero)

hasty tundra
#

thats a shout acc, thanks

rotund garnet
night raptor
rotund garnet
#

I mean i guess not.. but the chunks consist of 8x8 tiles, which have a large logic to be placed correctly, so i was wondering if i should divide it up more. Each tile will (based on random.range) spawn between 0 - 3 props

azure cairn
#

anyone know where to go for help with UI stuff?

languid spire
azure cairn
nocturne kayak
#

Hey, is there a way to make a raycast ignore an gameobject of specific tag?

languid spire
azure cairn
nocturne kayak
night raptor
# rotund garnet I mean i guess not.. but the chunks consist of 8x8 tiles, which have a large log...

Splitting up the code is not bad but attaching extra script to each tile might even hurt the performance if there's a lot of the chunks. I would probably create a static helper class (or regular class created in the chunk generator) named PropPlacer or something similar that you can refer to place the props when the chunk is spawned. Since the prop placement should be done at the same time with the chunk generation, I'd couple them in code too.

strong wren
nocturne kayak
#

i assumed the layermask param was going to make the raycast ONLY detect that layer, but apparently it only ignores that one

wintry quarry
#

the mask can contain any number of layers

#

the easiest way to define a mask is in the inspector. e.g.

public LayerMask myLayerMask;```
rotund garnet
night raptor
rotund garnet
#

The spawnpoints are empty game objects, that are at the places in the tile where it is possible for something to have a chance to spawn…

night raptor
rotund garnet
#

No i was thinking they were gonna be placed manually…

#

But im guessing that would be a heck of a task

night raptor
#

placed manually on procedurally generated world?

rotund garnet
#

Yeah the world consists of tiles, and each tile has pre-defined points where stuff could spawn

#

Or at least that was my idea

odd widget
#

Does changing the value of Text in TMP takes a lot of resources? Should i use “if one second passed” on the Void Update() to make it a bit more lighter

night raptor
odd widget
#

Or does it not matter and i can make it tmptext.text = “changed value”

nocturne kayak
#

Is this just expected boxcast behavior? for some reason my boxcast isn't taking into account the rotation of the cube

wintry quarry
#

the cube object is irrelevant to the boxcast itself

nocturne kayak
#

When i call it, i'm fairly sure i try to specicy that i want it's rotation to be equal o transform.rotation

#

i expected that would make it have, well, the same rotation as the cube

wintry quarry
#

Assuming transform is the cube and your code actually has that, then yes

nocturne kayak
#

Physics.BoxCast(transform.position, transform.lossyScale/2, transform.forward, out hit, transform.rotation, maxDistance, 5);

night raptor
odd widget
#

Okayu

#

Thankyou!

wintry quarry
#

but yes as far as orientation that looks ok assuming transform is the cube itself

night raptor
nocturne kayak
nocturne kayak
wintry quarry
#

5 is actually this layer mask:
..000000101
so it will hit only layers 0 and 2

frank flare
#

is unity default gravity bad for a player? I've seen some strange effects sometimes but maybe it's just me. Should I replace it with my own gravity?

wintry quarry
#

Make a layermask properly as I explained above

nocturne kayak
#

Shit, so that was luck, still, should the layermask really be affecting the rotation in this instance?

wintry quarry
#

no

#

the layermask does not affect rotation

#

how are you drawing the red box

night raptor
nocturne kayak
wintry quarry
#

you are drawing an unrotated cube

#

that is why the cube that is drawn is not rotated

night raptor
#

You can always rotate the Gizmos.matrix to get rotated gizmos

rotund garnet
# night raptor If you really want to place the points manually, you may want to have a script f...

So this is 3x3 chunks, which each has 8x8 tiles of procedurally generated roads. i want to now place down fire-hydrants, benches, garbage cans, and streetlights, but the game is a post-apocalyptic zombie-surviver, so the things need to be scattered, and broken, which means that i wanted to originally pre-place the points on the tile-prefabs, and then based on rng place something on that point. So my question was, if this would be a reliable method of doing it, or if i should make a script that places things more randomly than the pre-defined points?

wintry quarry
#
Vector3 cubePosition = transform.position + transform.forward * hit.distance;
var oldMatrix = Gizmos.matrix;
Gizmos.matrix = Matrix4x4.TRS(cubePosition, transform.rotation, transform.lossyScale);
Gizmos.DrawWireCube(Vector3.zero, Vector3.one);
Gizmos.matrix = oldMatrix;``` @nocturne kayak
nocturne kayak
night raptor
rotund garnet
frank flare
polar acorn
#

And you can change the value of unity gravity as well

night raptor
burnt skiff
#

why do i get a nullreference exception when i use my find survivor button

polar acorn
burnt skiff
#

18 i think

polar acorn
#

Instead of "thinking", just check

burnt skiff
#

how, sorry im a bit new to this

polar acorn
#

Ah, hang on, mobile only showed the two thumbnails, there's a third pic with the code on it

#

agents is null

burnt skiff
#

is it because its in another class

#

how would i make the button work from there

slender nymph
#

notice how your Initialize method has 0 references

verbal dome
polar acorn
#

this means that either Initialize was called with a null value, or it wasn't called at all at the time that code runs

burnt skiff
#

oh alright i think its wasnt initialized because i dont see the debug message

#

gimme a sec

verbal dome
burnt skiff
#

when the drones are initialized i can see the log message on which drone has the survivor but for some reason maybe the button script cannot access it?

verbal dome
#

@nocturne kayak Might need to cache Gizmos.matrix before and reset it afterwards. Not sure if it auto resets after drawing gizmos
Also, you can do Gizmos.matrix = transform.localToWorldMatrix to draw in local space of the transform

burnt skiff
polar acorn
burnt skiff
#

alright so this is the class everything is in after the drones are initialized they get put into the list and then they get partitioned and then the partitions establish a communication i want to make it so that when i press the button it will use the communication and find the drone with the survivor

#

but the findsurvivor is in the other class and im not sure how to make it accessible to that class

polar acorn
burnt skiff
#

is it possible if instead of using a different class for the controller i just use that flock class make the findsurvivor method in there and specify that that method will run on click using this

polar acorn
burnt skiff
#

oh alright ill try it out thanks

red cedar
#

does anyone know why my restart button is not working when I'm on scene 2 then move to scene game over? but if I open scene game over manually the code can be executed.

slender nymph
#

!code

eternal falconBOT
slender nymph
#

also you need to get your !IDE configured 👇

eternal falconBOT
nocturne kayak
#

And it works

#

i have a rough understanding on how it all works, which is frustrating

#

i hate implementing code i don't understand

#

But looking into matrixes rn

red cedar
nocturne kayak
#

Right now i'm trying to think of a way to just

slender nymph
fickle plume
nocturne kayak
#

Not move the cube past the hit result, but i don't know if simply if transform = wirebox.transform then don't move in that direction

frank flare
#

is there a way to get main object's rigidbody (to add force to it from a fan) ? (not with getparent)

I will get Capsule by OnTriggerStay and will have to get main rigidbody, which is player to add force on it

I also plan on adding grabbable items which will be elevated by fan

wild widget
#

Anyone can tell me what is this means "Even Instantiate will still instance the whole object, while returning the component. This avoids calls to GetComponent". From #💻┃code-beginner message, how to referencing rigidbody from Instantiate without GetComponent?

rich adder
slender nymph
polar acorn
frank flare
#

but I guess if I can't I'm gonna do it

rich adder
#

this way you can make Rigidbody a property you just grab
var rb = mycol.GetComponentInParent<MyScript>().Rb

red cedar
slender nymph
#

yes

rich adder
#

now it says Assembly instead of Misc

red cedar
red cedar
# red cedar
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager3 : MonoBehaviour
{
    public void RestartGame()
    {
        Debug.Log("Restarting game...");
        SceneManager.LoadScene(1);
    }
}
rich adder
#

do you have Event system in the new scene?

languid spire
red cedar
rich adder
red cedar
red cedar
rich adder
red cedar
languid spire
red cedar
polar acorn
rich adder
red cedar
#

if i press play the game over scene it's working properly

#

that's the different @polar acorn

polar acorn
red cedar
#

wdym, I don't understand

polar acorn
#

What, in code, is different between the different managers

red cedar
eternal falconBOT
red cedar
polar acorn
#

Okay, and what's different about this than, say, GameManager1?

#

Or GameManager3?

red cedar
polar acorn
#

Okay, these are utterly different things. This class should absolutely not be called GameManager3

#

This is at best like, RestartButton

red cedar
rich adder
#

wow..

polar acorn
red cedar
#

I think my code is worse than my handwriting😭

nocturne kayak
#

It stops moving if the distance between the cube and the wall is lesser than 0.1, and it doesn't work if it moves too fast

#

Truly, a programming masterpiece.

sage mirage
# red cedar https://hatebin.com/loovreqcva

Hello! I have seen your code in Game Manager. So, I have to make a few notes for you. So, first of all prefer when working with a lot of game objects which in your case isn't an important issue to just use a list or an array to hold every item and just make a loop for it to deactivate or activate your game objects in start or wherever you want that free up space in memory and it's more efficient rather than creating so many game objects and call SetActive() all the time. Second note, do not prefer calling your script Game Manager instead call it RoundManager or with a different name because I had some issues in my code if I remember correctly when one time I call it that way. For example, I am making right now a horror game already 2-3 months development and I have so many scripts and game objects to handle, what I did was to just make an array to hold the items that I needed for example to deactivate or activate. Third note, you should get used to work with singleton pattern, so instead of creating references everytime just create a static class and call it whereever you want in other scripts that way you can prevent null references in your code and it's more efficient.

frank flare
#

am I doing something wrong?

Vector3 distance = (collider_rb.position - local_Transform.position).magnitude;

slender nymph
#

magnitude is a float

frank flare
#

ah... yes

rich adder
#

it was already created so space is already occupying/allocated the memory

#

only when you Destroy it is marked for removal on the next GC tick

sage mirage
#

Rather than creating in the whole script SetActive methods ?

#

You are making a method and you use for example a static class, you call the method that has that line of code where it deactivates or activates the game objects on an array. That way you just call the method which is one line and done

rich adder
#

making it disabled doesnt do anything but stop callbacks like Update etc

#

thats why when you Pool you recycle objects but you still need them created

#

once created the memory is already allocated for it

#

Creating And Destroying is what creates MORE unecessary allocation on and on

sage mirage
#

So, what do you suggest in order to free up space in memory and to remove garbages?

rich adder
#

don't run expensive operation when you don't need to , clear any objects you no longer use, recycle anything you keep reusing , like pooling bullets, or anything you keep needing to despawn and respawn etc

still elm
#

what does this peice of code do?
void Update()
{
time -= Time.deltaTime;

}

#

if time is a float being 60

rich adder
#

Time.deltaTime is always the time between each frame

still elm
rich adder
still elm
rich adder
still elm
wintry quarry
#

this creates a timer.

#

Update runs once every frame
Time.deltaTime is the duration of the previous frame

rich adder
#

there is also tracking Time.time for timers, but more common with looping timer

still elm
#

this would work?
void Update()
{
time -= Time.deltaTime;

    if (time == 0)
    {
        WaveSpawner();
        time += 30;



    }
wintry quarry
#

it wouldn't

rich adder
wintry quarry
#

it will never == 0

still elm
#

I'll do an int instead then

wintry quarry
#

it will be like 0.032 one frame and -0.015 the next frame

rich adder
#

floats always use some form of < or >
or Mathf.Approximately

wintry quarry
#

That won't work

still elm
#

oh

wintry quarry
#

Just do if (time <= 0)

still elm
wintry quarry
still elm
#

what time.DeltaTime does

wintry quarry
#

It's just a number

#

it's the number of seconds since the previous frame

#

it changes every frame

wintry quarry
#

if your frame takes 1/60th of a second, then the value of Time.deltaTime is 1/60 (aka 0.016777)

#

but it will not be some known number

#

it will just be however long the computer took to process the previous frame

languid spire
#

be a good trick if deltaTime was negative @wintry quarry

wintry quarry
#

So if your first frame takes 0.011 seconds to process, then after one frame time will go from 60 to 59.899 @still elm

still elm
#

thanks for the example it helped

wintry quarry
#

every frame it will reduce by a little bit

dawn mulch
#

Hey everyone I'm new here. And I don't really understand what im doing and need some kind of guidance.

I dont understand code. Okay not true. I understand variables, loops, bool, integers, if/else, maybe others I haven't mentioned. But I don't understand the rest. I see videos out there that talk about it, but I don't understand how people know the rest of it, like vector3 and where it goes and how it's used, or how they know when to use spriterenderer, or any of that. And nowhere do they explain it. I've spent the last 3 days racking my brain trying to understand where they are finding this info, and I found that they said something about an API, but I can't find where it is in unity, and the examples they show in the API looks confusing, on top of also not super clear on what they do or how they need to be used. Can anyone explain it in to me, im really struggling to understand how they know to use moveDir, and how to structure code.

I hope this makes sense.

wintry quarry
#

based on how much time elapsed

rich adder
#

its looks daunting because 3 days isn't enough time to be comfortable

eternal falconBOT
#

:teacher: Unity Learn ↗

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

thorny basalt
rich adder
#

this sometimes takes years

#

literally

wintry quarry
#

Vector3 is nothing more than a collection of 3 numbers though. Often used as, for example, cartesian positional coordinates (i.e. representing position as 3 numbers x, y, z)

rich adder
dawn mulch
wintry quarry
#

but it can also represent other things in other contexts, such as colors, euler rotation angles (rotation round the x, y, z axes) etc

#

it can be used for anything you want

#

and is used for many things

#

You can even dream up new uses for it, and people do so every day

rich adder
dawn mulch
languid spire
rich adder
#

you learn by trial and error, and some basic understanding on how to plug which type into what

#

if you keep making shitty lego houses at first, eventually you figure out how to use each piece and make entire city scapes

wintry quarry
dawn mulch
wintry quarry
#

it will come in time

dawn mulch
#

I just wish I could see the list of the library, if that makes sense. To see how each one works

wintry quarry
#

Get good at google too

rich adder
#

more important than replicating someones code / video you actually learn how each piece works and how you can put them together

languid spire
wintry quarry
#

but it's not that useful on its own

dawn mulch
wintry quarry
#

it's like learning how to speak english by reading the dictionary

#

This is reference material

#

reference material is not useful when read cover to cover
it is useful to look things up as you need

languid spire
dawn mulch
rich adder
still elm
#

when both using System class and UnityEngine class. Random.Engine is unsure which class to use for Random.Range Function. How would this be resolved?

wintry quarry
#

any significant piece of software worth using has documentation

wintry quarry
#

for example, if you want the Unity version

rich adder
languid spire
still elm
#

thanks

#

😄

dawn mulch
wintry quarry
# still elm ah ok

You can also just type out the full UnityEngine.Random.Range(..) at the moment you use it instead

rich adder
still elm
dawn mulch
still elm
#

thanks

rich adder
still elm
#

can I post code somewhere here just for quick overview?

rich adder
still elm
#

pastebin?

rich adder
#

oh god no

#

!code

eternal falconBOT
dawn mulch
dawn mulch
#

I type in what I need and it pulls relevant info. This is amazing

rich adder
#

or even just linking a script as serialize reference in the inspector

wintry quarry
# dawn mulch Oh see this works here

note this is only a small part of it. This is the "core" api. it doesn't include the hundreds of packages in Unity.

It's way too much information to just... read through. But absolutely feel free to look at things you're interested in here.

still elm
#

How can I improve in my wave spawner code. I tried to make it the best I could. I am relativley new to programming. https://hastebin.com/share/ucibicujin.csharp

dawn mulch
rich adder
dawn mulch
rich adder
rich adder
#

there isnt a Library unity uses per se.. Unity is the library

dawn mulch
rich adder
#

yeah those hours are good too, but you can easily burn out quick. Just balance it out

#

when i first learned unity I would do 10 hours sessions at night, and then have work 2 hours later in AM lol

#

it was not good to learn /code tired though. One thing i regret, lots of wasted hours solving issues i solved next day with fresh mind in 2 mins lol

dawn mulch
#

But I'm also starting with no experience. That including using terminal for work related things, and making a game in scratch when I was in middle school, and my fascination with wanting to understand every games calculations and love to understanding how the games I've played work, all the way down to movement and everything. I took CS50 made a better game than I did in middle school (still very unoptimised and sloppy code that could be cleaned up a lot more, but it was enough to be proof of concept that I understood what was in front of me) and I'm now in unity going through the growing pains of YouTube hell learning what I can from there until I know enough to experiment.

rich adder
dawn mulch
# rich adder it was not good to learn /code tired though. One thing i regret, lots of wasted ...

Exactly. I know my body well enough to know when I'm burned out and need food or a nap, so I take them because the last thing I want is to burn out. I don't want my love of coding being soiled by my own poor choices. Which is also why I'm trying to not rely on anything as a crutch or just blindly copying code typing it out letter for letter, but since eim in the beginning I understand that for some sections I kinda have to just to get the repetition in.

dawn mulch
#

And what I understand is the right way is to do as much of it yourself before asking anyone. Exhaust every conceivable option before asking anyone. Hence why I'm here 🤣

rich adder
#

researching skills are invaluable.

#

you will be doing it 80% of your time

#

google "how do i...."

dawn mulch
#

Yeah. Which is why I'm doing it that way as much as possible. It helps that I try to do everything myself first anyways. I'm notbthe type who likes to ask for help.

dawn mulch
rich adder
#

nothing wrong with asking for help though esp if you're confused, having this much communication has its benefits too 😛

rich adder
#

hate that google shoved that in the search page now..

dawn mulch
# rich adder yeah just stay clear of any "AI"

See it hear mixed reviews on that, and they swing both ways. People seem to detest it, and others think it's okay as long as you're using it to explain things to you and little else.

rich adder
#

all it does it hinders your ability to think for yourself imo

#

and most of the regurgitated info is mostly wrong or not the most efficent way

#

anyway dont want to carry away with offtopic 😛 that AI topic has been beaten to death

#

we should prob make a thread or move to unity code questions 😛

dawn mulch
rich adder
dawn mulch
#

Yeah I don't see any channels listed anything close to unity questions

rich adder