#💻┃code-beginner

1 messages · Page 69 of 1

tepid cobalt
#

Thanks man

mystic oxide
#

tested creating 2 new project, first project still occur/appear, 2nd aren't

tepid cobalt
#

I just thought I had to queue the objects when i returned them to the pool

#

But I've got nothing controlling that queue lel

#

If you change to a Release method, it implies a different management strategy. For instance, if you were using a stack (Last-In-First-Out, LIFO) or a list where you want to place objects back at specific positions, Release might be more appropriate. However, this would require significant changes to the pool's logic and might not necessarily offer any benefits over the current queue-based system, depending on your specific use case.```

Use Case: A Player dies, they call an object from the pool. Another player picks that up and the object and returns to the pool, waiting to be used again.
fossil drum
#

Interesting, didn't know that UnityChanThumbsUp

tepid cobalt
static cedar
#

Well damn. UnityChanThink

somber viper
#

i need help with unity

#

idk what to do

gaunt ice
#

fix the compilation error

tepid cobalt
#

Double click the red warning down the bottom

#

It will open your IDe to the problem line

fierce shuttle
# somber viper

To elaborate, Unity will not update any script changes if your project has any compile errors in it, even if they are unrelated to what you were working on, so youll want to make sure you resolve your other errors first

somber viper
#

no issues

gaunt ice
#

the compiler says there is compilation error, or you havent configured your !ide

eternal falconBOT
somber viper
#

im new with unity and stupid

gaunt ice
#

just choose the way how your vs was installed and follow the instructions of the link

somber viper
#

installed via unity

gaunt ice
#

so click the link

somber viper
#

ok

#

or do i press

#

an the visual studio button

gaunt ice
#

yes

#

there should be an option of visual studio 20XX

somber viper
#

in where

#

theres only visual studio 2019 {16.11.33529}

gaunt ice
#

yes this one

#

idk your visual studio version

somber viper
#

ok

#

i thout it was the same for everyone

#

found it

#

pdated

#

updated

gaunt ice
#

now regenerate project file and click one of your scripts, the visual studio will be opened

somber viper
#

ok

#

preassed it

#

but an error popped up

gaunt ice
#

show it

somber viper
gaunt ice
#

ignore the warning first, double click one of your scripts to see if the vs opened

somber viper
#

ok

#

it did

gaunt ice
#

is your vs underlines line 2 in red in Grab.cs?

somber viper
#

blue

gaunt ice
#

show the screenshot btw

somber viper
#

ok

gaunt ice
#

it is still not configured...

#

open the visual studio installer, click the modify button on right hand side, see the unity is clicked

fossil drum
#

You can probably just right click and Reload these, I think that should fix the issue.

gaunt ice
#

didnt notice that

fossil drum
#

The recalculate thing you mentioned should have fixed this to be honest

craggy ledge
fossil drum
#

Unless he didn't close the IDE

#

And that install thing seems weird indeed. Never seen that. Perhaps you are right he still needs more components

somber viper
#

so what do i do

fossil drum
static cedar
somber viper
gaunt ice
#

you dont need it

#

you need the "game development for unity" only (byinstructions)

gaunt ice
somber viper
#

how do i get in that place

#

page

gaunt ice
#

the link in !ide....

eternal falconBOT
somber viper
#

which one of those

fossil drum
#

He also said he installed it via Unity, so that part should have been enabled for him...

somber viper
#

mannually

#

nooo

#

no

#

via unity i installed the vs

#

i think

fossil drum
somber viper
#

insttalling

#

done

#

now what

#

hello?

gaunt ice
#

open the Grab.cs

somber viper
#

now

gaunt ice
#

is the ide underlines line 2?

somber viper
#

what

gaunt ice
#

why the file is miscellaneous.... try open c# project in editor

#

right click in the project window->open c# project

#

if it still not works, regenerate project file and open c# project again

somber viper
#

i dont want to do it

tepid cobalt
fossil drum
gaunt ice
#

Release is just a wrapper of enqueue

rich adder
tepid cobalt
#
using System.Collections.Generic;
using UnityEngine;

public class PoolManager : MonoBehaviour
{
    public GameObject prefabToPool;
    public int poolSize = 20;

    private Queue<GameObject> pool = new Queue<GameObject>();

    void Start()
    {
        for (int i = 0; i < poolSize; i++)
        {
            GameObject obj = Instantiate(prefabToPool, this.transform);
            obj.SetActive(false); // Initially deactivated
            pool.Enqueue(obj);
        }
    }

    public GameObject GetPooledObject()
    {
        if (pool.Count > 0)
        {
            var obj = pool.Dequeue();
            obj.transform.position = Vector3.zero; // Reset position
            obj.transform.rotation = Quaternion.identity; // Reset rotation
            // obj.transform.localScale = Vector3.one; // Reset scale if needed
            obj.SetActive(true); // Activate the entire prefab
            Debug.Log($"Object taken from pool and activated: {obj.name}");
            return obj;
        }
        Debug.Log("No object available in pool.");
        return null;
    }


    public void ReturnObjectToPool(GameObject obj)
    {
        obj.SetActive(false); // Deactivate before returning to pool
        pool.Enqueue(obj);
    }
}

Working ver of poolManager

gaunt ice
#

i see it works.....

#

dequeue when get enqueue when release

tepid cobalt
#
    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }

        InitializePool();
    }

    private void InitializePool()
    {
        for (int i = 0; i < poolSize; i++)
        {
            CreatePooledObject();
        }
    }

    private GameObject CreatePooledObject()
    {
        GameObject obj = Instantiate(prefabToPool, this.transform);
        obj.SetActive(false);
        pool.Enqueue(obj);
        Debug.Log("Created and added object to pool: " + obj.name);
        return obj;
    }

    public GameObject GetPooledObject()
    {
        if (pool.Count == 0)
        {
            Debug.Log("Pool is empty, creating a new object.");
            CreatePooledObject(); // Optionally increase the pool size
        }

        var obj = pool.Dequeue();
        ResetObjectState(obj);
        obj.SetActive(true);
        Debug.Log("Object taken from pool and activated: " + obj.name);
        return obj;
    }

    public void ReturnObjectToPool(GameObject obj)
    {
        ResetObjectState(obj);
        obj.SetActive(false);
        pool.Enqueue(obj);
        Debug.Log("Object returned to pool and deactivated: " + obj.name);
    }

non working

#
    {
        // Reset object state as needed
        obj.transform.position = Vector3.zero;
        obj.transform.rotation = Quaternion.identity;

        var rb = obj.GetComponent<Rigidbody>();
        if (rb != null)
        {
            rb.velocity = Vector3.zero;
            rb.angularVelocity = Vector3.zero;
        }

        // Reset any additional components or states here
        Debug.Log("Object state reset: " + obj.name);
    }
}```
gaunt ice
#

You mean the pool cant return objects?

weak talon
#
private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Enemy"))
        {
            pRb.AddForce(-gameObject.transform.right * 5, ForceMode2D.Impulse);
            eRb.AddForce(gameObject.transform.right * 9, ForceMode2D.Impulse);

            StartCoroutine(Hit());

            gameObject.SetActive(false);

            if (pScript.facingDown)
            {
                pScript.bonusJumps += 1;

                pRb.velocity = new Vector2(pRb.velocity.x, 10);
                eRb.velocity = new Vector2(eRb.velocity.x, -10);
            }
        }
    }
    IEnumerator Hit()
    {
        eScript.isHit = true;
        yield return new WaitForSeconds(0.2f);
        eScript.isHit = false;
    }

this code when ever i hit an enemy i want it to knock back enemy and make isHit true for 0.2 seconds
everything works apart from the ienumerator, i put a debug.log at the start and at the end and it only works at the start not the end
anyone know a fix

gaunt ice
#

!code

eternal falconBOT
fossil drum
#
    gameObject.SetActive(false);

You disable the gameObject though. UnityChanHuh
It wont run the script anymore the next frame.

weak talon
#

that is the sword hitbox so theen it does not hit the enemy multiple times
so it should only do it once

#

wait

#

nvm you might be right

gaunt ice
#

What is escript? Enemy script?
And i think there are more than one enemy in your game, and you dont know which one you hit, so you should use the argument of ontriggerXxx

tepid cobalt
#

So how do i get around that logic then if it deactivates it for the next frame no matter wht action is called next?

tepid cobalt
#

Oh sorry

fossil drum
#

I don't know how to fix your problem. For me pools usually just work.

gaunt ice
#

so what is the problem... i cant get it....

#

to me it seems that the pool cant return the obj

fossil drum
#

Well first it was that he couldn't give back to the pool, but now it seems like it doesn't do it for all of them.

dry tendon
#

is this better than github for a collaborate project with two people in realtime?

gaunt ice
#

pause the game and see if all the active objects on scene
object pool is unordered so the hierarchy tells you nothing about the pool

rich adder
#

there is no "realtime"

gaunt ice
#

as long as the number of objects in pool+number aof objects allocated=initialize amount of object created then it is correct

dry tendon
desert elm
#

Will this just set the "Target" variable" to be the "mousePos" variable?

rich adder
#

its gonna copy it

desert elm
#

thank you

#

How can I get a script to read a variable from a component in a game object?

rich adder
#

make a reference to that script / component

#

eg [SerializeField] private Foo foo; var valueFromScript = foo.bar

desert elm
#

thank you again

desert elm
rich adder
desert elm
#

oh okay

rich adder
#

(they will show up in the gameobject inspector)

desert elm
verbal dome
desert elm
desert elm
verbal dome
delicate portal
#

How should I make a camera rotate system around an obejct with cinemachine, but in a way that it doesnt rotate exactly around the object, but it does a rectangular motion (I want this to be implemented into my housebuilding system, where you can rotate the camera around the rectangular shaped house).
Thanks

desert elm
verbal dome
#

I mean the one that has target

#

Oh I guess it is InputManager?

desert elm
verbal dome
#

So make a serialized field of that type: cs [SerializeField] private MovementManager movementManager;
Then you can access target with movementManager.target

desert elm
#

oh okay thank you!

verbal dome
#

target has to be public to be accessed from other scripts

desert elm
#

What does it mean to serialize a field?

verbal dome
#

Serialize means 'save' pretty much

#

It also means that unity will show the field in the inspector

desert elm
#

okay

delicate portal
queen adder
# desert elm What does it mean to serialize a field?

Serializing means Unity will convert some class(object) into a readable format of JSON(example). This happens in Scene file too. Likely, if you open a scene file in text editor, you will see how serialization works.

rich adder
rich adder
#

make 4 corners and connect said corners, make cam only move on said path between points

#

you might be able to use unity's spline

desert elm
#

Thank you for the help

desert elm
#

Is it possible to have two different inspectors looking at two different game objects

short hazel
#

Yes, you can select one object, then right-click the Inspector tab at the top and select Lock

rich adder
#

^^ additionally, you can right click one of the components and click Properties and it will pop out its own inspector

delicate portal
desert elm
#

okay

delicate portal
verbal dome
#

Better than fiddling with the locks

rich adder
gaunt ice
#

the editor will throw if too many of inspector windows are opened when enter play mode iirc

static cedar
#

Now i that i think about it, i wonder how crap my editor scripts are. UnityChanThink

desert elm
#

why does this not work?

silk night
desert elm
#

yes and?

silk night
#

You need to "translate" it to World coordinates

desert elm
#

oh right

#

its vector2 not vector 3

#

wait

rich adder
desert elm
#

wait

rich adder
#

if this supposed to be a unit mover I would call the MouseInput method directly from Unit controller not unit itself

desert elm
#

oh it works now

#

I just needed to flip mousePos and Target around

gilded verge
#

unity absolutly LOVES not working

rich adder
desert elm
#

How can I check if the gameobject the script is attached too is the Selected Unit?

short hazel
#

Selected Unit variable is not a GameObject, it's a Unit (the script you've shown in this screenshot).
So that would be a if (selectedUnit == this)

verbal dome
#

I feel like selectedUnit should be in some sort of manager script instead of a unit

short hazel
#

Yeahh

desert elm
#

currently just trying to find out movement script

#

how do I make sure that the objects Z coordinate will remain over -1?

fossil drum
wintry quarry
static cedar
#

If you use rigidbody, pretty sure there's a way to lock the z position.

verbal dome
#

Yep but they want to limit it to min -1, not lock it entirely

willow breach
#

hey i'v been coding in js for the past decade and my C# skills are rusty. im trying to use Visual Studio but not getting any auto completion from the UnityEngine library
so i make silly typo mistakes and need to wait for Unity to compile the script before I can see it

I have the tools installed do why cant my VS read the library?

eternal falconBOT
#
Visual Studio guide

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

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

rich adder
#

btw visualstudio and vscode
are different so make sure you are talking about VS visualstudio

desert elm
#

and yeah found it

#

thanks

#

nevermind

#

can you use 3d rigid body for a 2d object?

verbal dome
#

Only if every other object uses 3D colliders & 3D rigidbodies

#

Because 2D and 3D physics can't interact

#

Why do you want a 3D rigidbody though?

desert elm
ivory bobcat
willow breach
#

i did the first guide

verbal dome
ivory bobcat
#

Whatever the case is, go through the check list and tell us what you did and did not do.

willow breach
verbal dome
willow breach
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

desert elm
verbal dome
#

If so, you should use rigidbody2d.MovePosition

desert elm
#

just made the mousePos vector 2

rich adder
#

yez because Z pos

verbal dome
#

You should still move it with Rigidbody functions if you want to use physics

willow breach
# rich adder yes

Perhaps I need to restart the pc to register the path envs of .net

#

nope ):
still no auto completion
@rich adder

rich bluff
winter quiver
#

made a character controller with isGrounded but if you fall off you can jump again. do I use a OnCollisionExit void?

willow breach
rich bluff
winter quiver
#

2019 or 2022?

rich adder
#

and show external tools page

rich adder
#

Overlap, Cast or Checkbox/sphere

#

Character Controller component has a built one with .IsGrounded but its not reliable

winter quiver
#

Oh i'm using Rigidbody

#

using UnityEngine;

public class CharacterController : MonoBehaviour
{
[SerializeField] Rigidbody rb;
public float movementXZ;
public float movementY;
[SerializeField] bool isGrounded;

// Update is called once per frame
void FixedUpdate()
{
    if (Input.GetKey(KeyCode.W))
    {
        rb.AddForce(0, 0, movementXZ * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.A))
    {
        rb.AddForce(-movementXZ * Time.deltaTime, 0, 0);
    }
    if (Input.GetKey(KeyCode.S))
    {
        rb.AddForce(0, 0, -movementXZ * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.D))
    {
        rb.AddForce(movementXZ * Time.deltaTime, 0, 0);
    }
    if (isGrounded) 
    {
        if (Input.GetKey(KeyCode.Space))
        {
            rb.AddForce(0, (movementY * 100) * Time.deltaTime, 0);
            isGrounded = false;
        }
    }
}
private void OnCollisionEnter(Collision collision)
{
    if (collision.collider.tag == "Floor") 
    {
        isGrounded = true;
    }
}

}

rich bluff
#

oh vsc

rich adder
willow breach
rich adder
# willow breach

try hit regen project files.
also you dont need all those checked off lol

winter quiver
rich adder
#

you restarted PC ? dotnet install usually requires it

willow breach
#

ok im not sure what happned but it works now!!!!

rich adder
#

eh couldve still been installing or something

#

in vsc console

willow breach
#

im so happy

rare basin
#

Also this code would cause you much pain to work with, it is not extendible

#

Fixed update is only for physics operations

#

Checking for input there is not correct and might behave weird

worthy stirrup
#
void Update ()
    {
        transform.RotateAround(player.transform.position, Vector3.up, Time.deltaTime * speed);
    }
#

I am using this to rotate my camera around a player when I press X or C (for left and right). For now I'm just experimenting with rotating it at a constant speed

#

however this causes my camera to rotate faster and faster as time goes on

#

as you can see it goes faster and faster gradually

#

why is it doing this and how do I resolve it?

eager elm
#

Do you change the value of speed anywhere?

swift crag
#

Show the entire script.

swift crag
#

(i.e. when you're running at more than 50 fps)

topaz mortar
#

I have an empty Player object that's a ragdoll, it has all the body parts properly set up attached to the torso
If I want to make my player move left & right, where do I apply the force?
Do I apply it to the torso so my other body parts automatically follow?
Or is there something I can add to the player object so I can directly move that and it will control all the children?

#

This is during a fall animation, so it doesn't have to be pretty

rich bluff
#

you can test it by freezing the torso and dragging it around to see how it behaves, my guess is yes the torso will have the most mass and will dominate

fresh roost
#

does anyone have an idea on how to create source engine movement & rocket jumping in tf2?

worthy stirrup
# swift crag Show the entire script.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class RotateCamera : MonoBehaviour
{
    public GameObject player; // the player object
    public float cameraMaxSpeed = 10.0f; // rotation speed
    private Vector2 direction;
    public InputActionReference rotate;
    private Vector3 input;
    private float speed = 1; // current rotation speed

    void Awake()
    {
        rotate.action.performed += OnRotate;
    }

    void OnEnable()
    {
        rotate.action.Enable();
    }

    void OnDisable()
    {
        rotate.action.Disable();
    }

    public void OnRotate(InputAction.CallbackContext context)
    {
        direction = context.ReadValue<Vector2>();
        if (direction.x < 0)
        {
            Debug.Log("rotatingL");
        }
        else
        {
            Debug.Log("rotatingR");
        }
    }
    void Update ()
    {
        transform.RotateAround(player.transform.position, Vector3.up, Time.deltaTime * speed);
    }

}

#

the other parts of the code is for eventual rotation using C and X

rich bluff
swift crag
worthy stirrup
#

right?

#

I have no idea wtf is wrong 💀

fresh roost
swift crag
#

Framing Transposer could be trying harder and harder to catch up with where it wants to be

worthy stirrup
#

oh that might be it

rich bluff
#

tf2 is built in Source, souce is built on quake engine, with most of the physics from quake 1 still present, like surfing and rocket jumping, i think its safe to assume it will be almost identical, at least at the base level @fresh roost

worthy stirrup
swift crag
#

to find out, turn off the Body behavior

swift crag
#

I would suggest moving a camera target that the camera then chases

#

if you feel the need to directly move where the camera

rich bluff
worthy stirrup
#

nope it still speeds up

fresh roost
swift crag
#

you parented the virtual camera to the main camera

#

the dog is chasing its own tail

#

don't do that

worthy stirrup
#

wait what that's so cool why does it do that

swift crag
#

the main camera is being repositioned to where the virtual camera is

rich bluff
# fresh roost nope

look into KCC, as a base controller on top of which you can build any mechanics you want, but its pretty advanced coding

swift crag
#

so the virtual camera winds up getting moved

worthy stirrup
#

ohhhh

#

that's wacky as hell

swift crag
#

it's pretty neat. I haven't used it to its full potential yet

swift crag
#

It gives you a bunch of hooks so it can ask you things like "is this ground stable?" and "where should I move to?"

#

It definitely requires more work than just using the CharacterController

rich bluff
#

KCC gives you full access to all data, whats ahead, all the contact points, everything, so you can modify and make decisions on how it should behave

#

best thing about it is that it wont get stuck like CC, works in any conditions

fresh roost
#

the thing is,im making a mobile port of tf2 so alot of movement needs to be simplified

#

crouch jumping to rocket jump etc will have to be simplified

rich bluff
#

as in direct port? what does simplified mean in this case?

fresh roost
#

how could that even be achieved with 4 fingers on mobile

#

so, if im going to add rocket jumping

#

its only going to be look behind

#

shoot

#

and yeah

fresh roost
rich bluff
#

right, still use KCC as a base, if you are comfortable with it, because using anything else while on the surface will be simple, will introduce many edge cases

fresh roost
#

gotcha

rich bluff
#

landing on a sharp corner after jump, walking into a tight spot, etc

fresh roost
#

smileythumbsup thank u

#

for the help

#

rocket jumping works currently its just not 1:1 or close to tf2

autumn tusk
#

how do i make a child inherit only the position of its parent

summer stump
#

You would have to track the rotation and scale of the parent and inversely change them on the child.
That kinda goes against what a parent/child relationship is for though

Easier to just NOT have it be a child, and follow the other object via code

#

Or have them BOTH be children of a common gameobject that only moves, then change the old parent now siblings scale and rotation

timber tide
#

Assuming you want it not to rotate then you change the rotation of the child to point to another non-rotating element (some hidden gameobject like a singleton/manager)

#

silly hack but it works

polar badge
#

Hi team - Say I have team A of 200 agents attacking a team of 200 agents. Best Approach A) Each agent has it's own event on "I am targetting enemy X", "I am shooting enemy X" "I am melee attacking enemy X"" etc, so everyone subscribes to each others events when they target or attack, and the one that is targetted, attacked, or whatever, knows it and runs appropriate logic to respond

#

or B) Have ONE global event that they all subscribe to, like Global_I_Attack_Enemy (myID, IDofEnemy, AttackingRangedorMelee, DirectionofAttack, yaddaYadda), and all the units get those events but only act if their ID is the one called

timber tide
#

Right, or change state logic they run to Attack

polar badge
#

Not sure if 400 agents subscribing to like 400/800 events is the right way, or all subscribe to one event. Not sure the best practice for scalability

timber tide
#

B) is interesting for something like an RTS when you're dealing with pathfinding as multiple attacking units may need to communicate with each other

polar badge
#

That's exactly it

#

Think Mount and Blade clone

#

basically

#

Is there a best practice for when you can have X agents, each with like 3-4 events that trigger, and you can subscribe/unsubscribe chaotically multiple times in a ten second span?

#

or is the performance hit so not worth it that I shouldn't worry?

#

I might be overthinking it

timber tide
#

Just my experience with pathfinding and optimizing it is that I'm not updating/recalculating every frame if not needed. Units farther away from combat will only recalculate very other frame, but those closer to combat will be higher priorty on calculating new paths. As far as subscribing to a new unit each time they change target is miniscule.

#

General idea is to prevent a large amount of calculating (don't have every single unit and unit groups calculate path/subscribe/communicate at once) and to spread it over each update.

polar badge
#

VERY good point!

#

You're right

#

even if I have say 500 guys killing each other

#

it won't be every frame

#

and I'm trying to offset logic anyway by a few frames

#

so they're not all doing the same thing on the same tic, like raycasts for enemies, etc

timber tide
#

My problem though is rendering and that's a whole another issue itself ;)

polar badge
#

So yeah, keep is simple, have em each have local events that they subscribe to, etc. I'll use a map in a global script so it's fast to pull the right reference to subscribe to, without using a "getcomponent"

#

ah yes

#

rendering

#

I'll eventually get there. My rendering and physics is killing me, but that's my last step haha

#

wish I could help you

#

Thanks man, I appreciate the advice

timber tide
#

I've just some shader batching issues which I'll eventually take care of haha

#

Yeah np

polar badge
#

rendering is just mumbojumbo to me lol. I'm primarily a bbackend guy haha

polar badge
#

so for lots of sub/unsub, might not be best, but when it's fairly static, then no concerns

timber tide
#

Makes sense. Maybe I'll consider using unity events more in the future, haha.

#

the sample size is quite large for a single update, but yeah perhaps it's just better to couple references in some data struct on each unit instead

solid verge
#

how can i invoke a prefab with a random color?

swift crag
#

do you mean instantiate a copy of a prefab?

#

you don't "invoke" a prefab

solid verge
#

well yeah that's what i mean

swift crag
#

What kind of renderer does it have?

#

is it a SpriteRenderer? MeshRenderer?

solid verge
#

what is a renderer

#

oh wait

swift crag
#

Objects don't have a color.

#

This cube is only visible because it has a Mesh Renderer component, for example

solid verge
#

Sprite renderer

swift crag
#

Okay, so that'll be easy

#

The sprite renderer has a tint field

#

er, a Color field, I should say

#

this color is overlaid on the sprite to tint it

#

so, if you change the color field on your sprite renderer, you will change the color of the sprite

#

I would suggest doing it like this

#
[SerializeField] SpriteRenderer myPrefab;

public void Whatever() {
  var instance = Instantiate(myPrefab);
  float hue = Random.value;
  instance.color = Color.HSVToRGB(hue, 1, 1);
}
#

Since myPrefab is a SpriteRenderer, you will only be able to drag a prefab that has a SpriteRenderer on it into the myPrefab field

#

and when you Instantiate it, you'll get a SpriteRenderer

#

Color.HSVToRGB creates a Color from a hue, a saturation, and a value

#

hue is the kind of color; saturation is how strong the color is; value is how bright the color is

#

so, if you pick a random number between 0 and 1 and use that as the hue, you'll get a random color

#

using 1 for saturation makes it a vivid color (instead of gray) and using 1 for value makes it a bright color

#

and then you assign the resulting Color into instance.color, which changes the color of the sprite renderer

woeful hedge
#

    IEnumerator FireShakeEvent(GameObject obj, float count)
    {
        Debug.Log("SHoot");
        obj.SetActive(true);
        Color color = obj.GetComponent<SpriteRenderer>().color;
        int x = 1;
        while (x < count + 1)
        {
            Debug.Log(color);
            color.a = UnityEngine.Random.Range(0f, 1f);
            obj.GetComponent<SpriteRenderer>().color = color;
            x++;
            yield return new WaitForSecondsRealtime(Time.fixedDeltaTime);

        }

        color.a = 0;
        obj.GetComponent<SpriteRenderer>().color = color;
        //obj.transform.position = new Vector3(-0.45f, -0.15f, 0);
        obj.SetActive(false);

    }
#

So I just Changed Color Alpha, but the GameObject keep displaying total black even the color is white

#

What did I wrong?

swift crag
#

you've got a sprite renderer inside of a canvas, which is weird

#

Does the sprite look correct if you don't run that coroutine?

woeful hedge
#

it was but wait ill check

#

uhh It doesnt

swift crag
#

I'm also unsure about the material you're using

#

Isn't there a specific sprite shader?

woeful hedge
swift crag
#

You've got the Standard shader

swift crag
#

If you want to display a sprite with a UI canvas, use an Image

woeful hedge
#

No its not

swift crag
#

Maybe you just had it parented to one at some point, then

#

You can jsut remove it

woeful hedge
#

ok

#

nvm solved

#

why this thing has standard Material as you said

#

weird

solid verge
#

Fen, what does the s and v do in the random color thing

#

S and V

#

oh

#

wait

#

you explained i think

#

ok yes ty

#

wait

#

in my prefab

#

i have a cube

#

that has a sprite renderer

#

but the prefab doesn't

#

how do i assign

#

my prefab to the script

#

fixed

#

i just added a sprite to the prefab

#

but is it possible to make it so it cannot be white?

rich adder
solid verge
#

cause i made my background white

solid verge
#

maybe i can do it with a switch thing

fast knot
#

Is it "okay" to call another method inside OnTriggerEnter2D which is doing a gameobject.transform.localScale?
Or should the gameobject.transform.localScale only be executed inside FixedUpdate?

rich adder
fast knot
#

What do you exactly mean by "one frame scale"?
FYI the game object is a moving car if this makes any difference 😄

swift crag
#

Perhaps you've dragged the prefab into the scene, then added a SpriteRenderer to that instance?

#

This won't affect the prefab.

rich adder
solid verge
#

on spawn, so it like moves back to back

fast knot
swift crag
#

I don't follow. Do you want the individual prefabs to be moving side to side, or do you want to spawn many prefabs in a pattern that goes left and right?

solid verge
#

i think i could minus the transform.position.x with 2 and plus 2 but idk how to make it update

swift crag
#

the prefab will need a component on it that changes its position

tepid cove
#

I have two models in unity i want to have an idol animation. one works fine, and the otehr one jsut doesnt animate even tho both are almost exactly the same jsut different models and i dont know whats wrong, they both also ragdoll when i enable it but one just wont animate

autumn tusk
#

this is my code, i dont know whats causing the issue

#

!code

eternal falconBOT
autumn tusk
#

the error im getting is "the variable bulletgenerator of playershooting has not been assigned"

rich adder
#

are you sure you saved?

summer stump
autumn tusk
#

changed the variablename to firepoint

summer stump
#

Show the actual error

autumn tusk
summer stump
#

Ok, so you don't have a transform reference assigned

#

Drag one it

rich adder
#

then you have a copy of the script

#

or somehow unassigning it at runtime

autumn tusk
#

alright

#

i removed a copy i accidentally put in

#

but its still firing on the y axis

rich adder
rotund hull
#

how can i make raycasts not interact with triggers

rich adder
timber tide
#

you want the forward direction not the up direction

rotund hull
rich adder
#

its an enum

autumn tusk
rich adder
autumn tusk
rich adder
#

put it Local / Pivot mode on scene view

rotund hull
rich adder
rotund hull
#

i dont have an ide

rich adder
#

Visual Studio for example

rotund hull
#

but how would i put it in here RaycastHit2D hit = Physics2D.Raycast(bulletSpawn.position, bulletSpawn.right, range, null, true);

rich adder
#

enums arent true or false

#

do c# basics

autumn tusk
#

ok i managed to do a hacky solution

rotund hull
#

for me those things dont show up

#

i do have visual studio

rich adder
#

so configure it

rotund hull
#

how

autumn tusk
#

manually flipped the firing box

rich adder
rotund hull
#

the blue one

rich adder
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

rich adder
autumn tusk
#

i tried something else

rich adder
#

because if this is supposed to be Local Pivot then you're using wrong direction

#

transform.right is the correct one

autumn tusk
#

ok lemme test that

rich adder
#

bullet must also point the same way

rich adder
autumn tusk
#

nope, didnt work

rich adder
#

wdym "didn't work"

#

what did you do exactly

autumn tusk
#

changed firePoint.up to firePoint.right

rich adder
#

and are you in Local mode? you never said if thats what you've shown

#

also show bullet pivot in local mode

rotund hull
autumn tusk
#

ok

rotund hull
#

that was to somone else

autumn tusk
#

thanks for your help

summer stump
untold bridge
#

Can anyone help with this problem... recently i made my game multidevice so it can be played from pc mobile and ps. However to do this i had to switch to the new input system while all my scripts were coded woth the old one. I found on unity how the controler is but does anyone know how is this line translated: Input.GetAxis("Horizontal"); or at least how to make smooth movement using it?

rich adder
rotund hull
#

i just want to know how to make a raycast ignore triggers

#

please

rich adder
rotund hull
#

ok how woyuld i do that in this code becasue i dont know what a enums is ----- RaycastHit2D hit = Physics2D.Raycast(bulletSpawn.position, bulletSpawn.right, range);

rich adder
rotund hull
#

yeah but is it a true or faslse

rich adder
#

aren't Documentations amazing ?

rotund hull
#

RaycastHit2D hit = Physics2D.Raycast(bulletSpawn.position, bulletSpawn.right, range, ignore);------------like that

rich adder
#

not even close no

rotund hull
#

just tell me how

rich adder
#

You should learn how an enum works

rotund hull
#

then tell what it s

rich adder
#

if this is something you are struggling with you're gonna have even more of a hard time

#

Its literally in the example man

#

fucking read it

rotund hull
#

dude you can make so much easier for both of us just tell me if it is more than one word or just how to do it

untold bridge
#

has anyone played celeste before?

rotund hull
#

i dont know what that is

rich adder
untold bridge
#

ok np

rotund hull
untold bridge
rotund hull
#

is that what i type

rich adder
rotund hull
#

you guys are just showing me a picture

rich adder
#

how to type it

rich adder
untold bridge
#

Just a question... are there any new features for 2D in 2023 Unity version except Visual studio 2022

rotund hull
#

is it a number or a word

summer stump
rotund hull
#

or a bool

rich adder
#

what dont you get

#
    public enum Moods { Sleepy, Annoyed, Productive}
    public Moods Mood = Moods.Annoyed;
rotund hull
#

so its just a number

rich adder
#

they are enums, named numbers

rotund hull
#

you could have said that and not have taken 5 mins

summer stump
rich adder
rotund hull
#

i came here for help

rich adder
#

this is part of help, to teach you how to help yourself

summer stump
#

This is a place of learning, not spoonfeeding

fickle plume
rich adder
summer stump
celest shoal
#

Hello, got some weird thing where during the transitions from my idle and walking animation, if I were to stop, it'd wait for the animation to finish then stop even though exit time has been ticked off - any help?

summer stump
# rotund hull 🤓

Yeah, caring about others and not rudely demanding help is very nerdy.... notlikethis
Some people....

rich adder
celest shoal
fickle plume
celest shoal
topaz mortar
#

rb.AddForce(new Vector2(horizontal * 50, 0), ForceMode2D.Impulse);
Why does this also slightly increase my falling speed?

solemn fractal
#

hey guys.. is there a way to change the color of the text of those strings that I show inside the red box?

timber tide
#

think you can add some html/css tags within the strings

fossil drum
solemn fractal
solemn fractal
# rich adder wdym the color?

managed to do like that ```cs
fireRate.text = "Fire Rate: <color=red>" + _player.fireRate.ToString("F3") + "/s</color>";

signal cosmos
#

vcontainer in 2023 is actual?

ruby python
#

Evenin' all, Could someone help me out with this please? I'm thoroughly confused as to why this isn't doing what it's supposed to be doing.

    void Update() {

        firingPoint.LookAt(playerTarget.transform);

        GameObject bullet = GameManager.instance.GetPooledObject("Bullet");
            if (bullet != null)
            {
                bullet.transform.parent = firingPoint;
                bullet.transform.localPosition = firingPoint.localPosition;
                bullet.transform.localRotation = firingPoint.localRotation;
                bullet.SetActive(true);
                bullet.transform.parent = null;
               }
    }

And on the Bullet script (lives on the bullet prefab.....

    private void Update()
        {
        transform.position += bulletSpeed * Time.deltaTime * Vector3.forward;
        }

It's a simple bullet firing system, I have a firing point that is always pointing at the the player (works great), but the bullets don't travel along it's forward direction, they just travel in the 'world' forward direction and I'm seriously baffled as to what I'm doing wrong.

swift crag
#

you're adding Vector3.forward to the position

#

you will always move in the world's forward direction

#

you need to use transform.forward if you want the local forward direction

ruby python
#

Ah balls, I always do that. lol.

#

Thank you.

queen adder
#

Where do you usually put UI objects you dont want the camera to see?

swift crag
queen adder
#

the red thingy in the top, i want to like hide it from camera sometimes, im just using -(5000, 5000) for now.
I cant really close it since it invokes some things when it did

swift crag
#

you could move it to a layer that the camera ignores

#

I think that'll work for an overlay canvas, at least

#

oh, you could also just use a CanvasGroup

novel void
#

I'm sure I'm making an obvious mistake here but after looking at the same lines of code for hours, obvious things become invisible.

I have a simple water wave effect that moves vertices of a mesh based on some simple sin wave and world coordinate math. This is working correctly but I've created a "runaway" effect where the ocean object's X and Z position continually adds to the position of the vertices. I need the ocean object to follow the player to create the illusion that the ocean is larger than it is (pretty basic stuff) but the ocean mesh shouldn't run away from it's object :p
I'm almost certain the issue is with my wave math on the line commented but I can not for the life of me figure out how the object's position is continually accumulating the vertex position. Thanks in advance for any help.

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

public class Waves : MonoBehaviour
{
    public float linearWaveSpeed;
    public float linearWaveHeight;
    public float linearWaveLength;
    public float rippleWaveSpeed;
    public float rippleWaveHeight;
    public float rippleWaveLength;
    public Transform waveOrigin;
    Mesh mesh;
    MeshCollider physicsMesh;
    Vector3[] newVertices;

    void Start()
    {
        mesh = GetComponent<MeshFilter>().mesh;
        physicsMesh = GetComponent<MeshCollider>();
        newVertices = mesh.vertices;
    }

    void Update()
    {
        if (linearWaveLength < 0.01f) linearWaveLength = 0.01f;
        if (rippleWaveLength < 0.01f) rippleWaveLength = 0.01f;

        for (int i=0; i<newVertices.Length; i++)
        {
            Vector3 vert = newVertices[i];
            Vector3 wPos = gameObject.transform.TransformPoint(vert);
            float dist = (vert-waveOrigin.position).magnitude;
            newVertices[i] = new Vector3(wPos.x, (Mathf.Sin(Time.time*linearWaveSpeed+wPos.x/linearWaveLength)*linearWaveHeight) + (Mathf.Sin(Time.time*rippleWaveSpeed+dist/rippleWaveLength) * rippleWaveHeight), wPos.z);//Setting vertex height here based on sin waves.
        }//here
        mesh.SetVertices(newVertices);
        mesh.RecalculateBounds();
        physicsMesh.sharedMesh = mesh;
    }
}```
timber tide
#

Beyond getting too involved with the math it seems the world point values you're adding is increasing some values exponentially

#

at least that's my observation on the clip here

#

I'm not seeing any accumulation in your code though but reading this stuff on mobile is hard.

#

Could also just keep it stationary in a sense and transform the waves, while following the player

novel void
#

Ah, that's a good alternative.
Though if I simply add the player's horizontal position to the waves then I won't get the world coordinate waves...?
Oh it works!

timber tide
#

oh, hey im just thinking out loud but nice haha

novel void
#

that's simpler than trying to solve whatever the issue was.

#

moving the ocean causes ai boats to fall off the end of the world so I'll have to fake their ocean physics somehow :p

gusty void
#

Hi, I’m having trouble with a CS102: error with the type CharacterMovement already containing a definition for hSpeed. I really don’t know how to fix this, and I’d love to have some help thank you

polar acorn
gusty void
#

Thank you I’m so sorry I can’t believe I didn’t see that😭

polar acorn
#

also configure your !ide

eternal falconBOT
eternal needle
eternal falconBOT
eternal needle
#

Damnit

gusty void
#

Okay thank you!

worthy stirrup
#

wtf is happening here

#

"Screen position out of view frustum (screen pos 403.000000, 319.000000) (Camera rect 0 0 699 542)
UnityEngine.SendMouseEvents:DoSendMouseEvents (int)"

#

here is my code:

using System.Collections;
using System.Collections.Generic;
using Cinemachine;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerMovementBasic : MonoBehaviour
{
    public float speed = 10.0f;
    public InputActionReference moveAction;
    private Vector2 moveInput;
    private Rigidbody rb;
    public CinemachineVirtualCamera vcam;
    
    void Awake()
    {
        rb = GetComponent<Rigidbody>();
        moveAction.action.performed += OnMovePerformed;
        moveAction.action.canceled += OnMoveCanceled;
    }

    void OnEnable()
    {
        moveAction.action.Enable();
    }

    void OnDisable()
    {
        moveAction.action.Disable();
    }

    void OnMovePerformed(InputAction.CallbackContext context)
    {
        moveInput = context.ReadValue<Vector2>();
    }

    void OnMoveCanceled(InputAction.CallbackContext context)
    {
        moveInput = Vector2.zero;
    }
    void Update()
    {
        Vector3 moveDirection = new Vector3(moveInput.x, 0, moveInput.y);
        moveDirection = vcam.transform.rotation * moveDirection; // Rotate the move direction vector by the camera's rotation
        moveDirection.y = 0;
        // Set the player's velocity
        rb.velocity = new Vector3(moveDirection.x, rb.velocity.y, moveDirection.z) * speed;

        // If the player is moving, rotate the player to face the direction of movement
        if (moveDirection != Vector3.zero)
        {
            Quaternion toRotation = Quaternion.LookRotation(moveDirection, Vector3.up);
            transform.rotation = Quaternion.Lerp(transform.rotation, toRotation, speed * Time.deltaTime);
        }
    }
}
#

it looks like the player is just being instantly sent to another realm whenever it touches another object with rigidbody

short hazel
#

Solution is to exclude the Y component when calculating the final vector, by multiplying moveDirection itself with the speed, before applying it to the velocity

bitter canyon
#

How can i make it so that my player moves smoothly on a platform going up and down instead of not being able to jump when going up and constantly falling then hitting the platform when going down

fierce shuttle
# bitter canyon How can i make it so that my player moves smoothly on a platform going up and do...

Platforms are notoriously difficult, since you have 2 different forces being applied (the gravity of the character and their own velocity, as well as the velocity of the platform), this example shows horizontal moving platforms, but the logic may help for your scenario as well: https://blog.devgenius.io/moving-platforms-in-unity-4d7299b2d013

Medium

Moving between 2 Transforms

dense root
#

How do I reset the text input field after "inputting" text? i.e. on spacebar resetting the field

abstract onyx
#

I'm having some issues while setting up my IDE, it's not autocompleting code or underlining errors at all, I've been doing solid 3 hours research on the internet on why this might be happening and have done everything on the Microsoft website, any ideas why this is happening? Thanks
keep in mind I'm very new to unity please

azure zenith
#

What is tiling?

woven moss
#
void spawnAsteroid()
    {
        if (spawnRate > 1.4)
        {
            int whichSprite = Random.Range(0, asteroidPrefabs.Length); // Picks a random normal asteroid sprite.
        }
        
        float lowestPoint = transform.position.y - heightOffset;
        float highestPoint = transform.position.y + heightOffset;
        Instantiate(asteroidPrefabs[whichSprite], new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
    }``` How do I do this without getting an error instantiating the prefab?
ivory bobcat
woven moss
#

the name 'whichSprite' does not exist in current context

#

Instantiate(asteroidPrefabs[whichSprite] // here

ivory bobcat
#

Does whichSprite exist in the given context?

woven moss
#

int whichSprite = Random.Range(0, asteroidPrefabs.Length); here in the if statement

ivory bobcat
#

Stuff inside the if statement only exists inside the if statement unless they existed outside of it.

woven moss
#

ohh, so would I make a seperate int outside the if statement then change in the if statement?

ivory bobcat
fair steeple
#

https://pastebin.com/06h63pDJ
Hey I'm having trouble with this script. It is attached to a sphere with a rigidbody and for some reason when I print rb.velocity.magnitude it always returns 0. I made sure the rb reference is the correct one.

ivory bobcat
woven moss
#
void spawnAsteroid()
    {
        int whichSprite;
        if (spawnRate > 1.4)
        {
            whichSprite = Random.Range(0, asteroidPrefabs.Length); // Picks a random normal asteroid sprite.
        }
        
        float lowestPoint = transform.position.y - heightOffset;
        float highestPoint = transform.position.y + heightOffset;
        Instantiate(asteroidPrefabs[whichSprite], new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
    }``` still gets the same error, it may just be a dumb mistake by me
ivory bobcat
#

You can verify this by printing velocity

fair steeple
#

The object is moving tho

short hazel
bitter canyon
#

what line of code would i use to wait a certain amount of in game time?

fair steeple
#

Also it used to work before

woven moss
fair steeple
#

I don't know what changed broke it

short hazel
# woven moss oh i didnt realize

What happens if spawnRate is less than 1.4? Your variable doesn't get a value. The compiler tells you that by reporting that error

ivory bobcat
fair steeple
#

Vector3 velocity = rb.velocity;
print(velocity);
this is printing numbers

woven moss
fair steeple
#

Is that what you meant by velocity?

ivory bobcat
fair steeple
#

I think?

#

I just changed print(rb.velocity.mag) for this

#

I guess I can make use of these numbers for my purposes

weary moss
#

Let's say i create a variable for a game object(public GameObject gameobj;), if i do an IF statement like this: if (gameobj), will it detect if the gameobj is active?

fair steeple
#

you can check with gameobject.activeself

tepid cove
#

how do i make an object move forward and not stop? nothing else

ivory bobcat
weary moss
#

so it checks if it exists?

ivory bobcat
#

Use the appropriate property to check if it's active

fair steeple
#

it checks if it has a reference but not if it is active

rich adder
fair steeple
#

go.activeSelf returns true or false depending on if it active or not

abstract onyx
swift crag
#

installing the workload is not the end of it

abstract onyx
#

Yeah, I've done everything else as well

swift crag
#

Show me your External Tools preferences page

abstract onyx
swift crag
#

close Visual Studio, hit "Regenerate project files", then double-click a script asset in Unity to reopen Visual Studio

abstract onyx
#

Still the same thing unfortunately

swift crag
#

Do you currently have any compile errors in Unity?

#

This would stop new packages from activating.

tepid cove
abstract onyx
swift crag
#

So there are no compile errors.

#

Look at the console to verify this.

hidden citrus
#

how can you pass the class in itself as a generic? I want to get who is calling this function at runtime so I can debug the class causing the issue (some hidden class on the Player gameObject is calling this when it shouldn't)

     public static void EnableMouseLook(GameObject source)
        {
       Debug.Log($"[Enable] Mouse Disabled?: {mouseLookDisabled} from {source.name}!");
        }
rich adder
abstract onyx
#

Console is empty

swift crag
#

One other thing to do

#

go to your project root and delete any .csproj files that are present

#

then regenerate project files again

#

I had a problem once where everything was doubled up in the .csproj files for...some reason

abstract onyx
#

Just the .csproj files?

swift crag
#

Yes.

#

Only the .csproj files

hidden citrus
hidden citrus
#

awesome thanks

tribal axle
#

how do i add camera borders to unity 3d? there are always 2d solutions

swift crag
#

restricting the camera from moving past a certain point?

rich adder
#

Check console for errors you might have

tribal axle
swift crag
#

hm, you could apply a force if the player's screen space position gets too close to the edges

abstract onyx
tepid cove
swift crag
short hazel
swift crag
#

Someone else might be able to help

tribal axle
#

somehow

swift crag
#

The difficult part is that we don't have an orthographic camera here

#

perspective makes it harder to reason about what to do

#

But I think a decent approximation would be to just shove the player to the camera's right if the player's screen space X position gets near 0

abstract onyx
swift crag
#

that sounds relevant!

abstract onyx
short hazel
#

Right click the first one and select Reload With Dependencies

#

And that should be all fixed

rich adder
abstract onyx
#

Wow all that fixed in a sec

#

Thanks man, you're a legend

tepid cove
rich adder
tepid cove
rich adder
#

Always make sure filename matches the class

copper perch
#

this look ok for the titles?
Can I put a particle system on top of the word snow?
particle system of snow flakes?

rare basin
#

this is a code question

muted wadi
#

what is a good list type for storing the information of highlighted objects?

#

for example, you're locking onto multiple targets and want to store their positions and the order of which you've locked onto them

vale sparrow
#

arrays?

muted wadi
#

do arrays store the current position and the order that they've been added?

vale sparrow
#

you can have an object array which contains all of the objects/targets that are "highlighted". if you have an object array "GameObject[] targets" you could then access their position with: targets["index in array"] .transform.position;

muted wadi
#

ah i see

#

so say I wanted the objects in the array to be destroyed in the order that they were added, would that also be possible using this method?

vale sparrow
#

yes. the array index starts at 0 and goes up to however many you have. you could use a for loop to go through each position and destroy it

static cedar
vale sparrow
#

starting from 0 and going up every loop

static cedar
muted wadi
vale sparrow
#

thats one way. i personally prefer arrays

static cedar
#

I think List might fit too. UnityChanThink

muted wadi
#

yeah arrays are perfect for what I'm trying to do here it seems. I figured I wouldn't be able to use a HashSet because it doesn't store enough information or something

static cedar
#

But i'd like to know more how you're going to make the selected items into a set first before i would suggest list or array.
Because with List, you can add 1 item at a time. Arrays are just locked into one size so you normally have to know the count in advance.

muted wadi
#

oh wait what

#

oh damn you're right

static cedar
#

You can't change the size of an array.

muted wadi
#

actually yeah List would be better because I don't know many objects will be added to the array once the player finishes locking on

static cedar
#

List on the other hand is secretely an array with some utilities to be able to add stuff and remove stuff.

muted wadi
#

ahhh

#

how do i make a list variable?

static cedar
#

List<TypeGoesHere>

muted wadi
#

thanks

static cedar
#

You never encountered types with <> yet?

muted wadi
#

i have i just didn't realise they were lists

#

still pretty bad at programming tbh

#

btw do I create this list as a variable by itself or do I create it once the locking on has started?

static cedar
#

Ah, you'll have to learn generics eventually, i suggest you search up on that later.
Generics basically just templates that allows it to work with different types. You can have a generic class or methods. GetComponent<>() is an example.

static cedar
muted wadi
static cedar
muted wadi
#

i assumed you just tell it to get a component and specify what type you want to get in the brackets

static cedar
vale sparrow
#

this whole convo reminds me that i need to start using lists, theyre really useful

static cedar
muted wadi
static cedar
#

Welp, I think any sets are going to need generics.
Look at List<> it kinda has to be a generic to support any kind of type right?

#

And so the Add method also changes. Since the argument is based on the generic type of the list you're using.

muted wadi
#

so is getcomponent a generic?

static cedar
#

Just the GetComponent<>() one.

#

Another benefit of generic is you can restrict what you can put in it.

#

E.g. GetComponent<TComponent>(); where TComponent : Component

#

Compiler will not let you use int in the generic parameter. Just anything that inherits from Component like Monobehaviour.

muted wadi
#

very confusing

#

i'll have to read up on this later

static cedar
#

Aye, i guess it's not time yet. UnityChanThink

static cedar
vale sparrow
#

just when you think its starting to make sense, you discover more...

static cedar
muted wadi
#

true

#

I'm at that point now where I know just enough to know how little I know

vale sparrow
#

thats good

#

signs of progression and room for improvement

muted wadi
#

i also started learning shader programming and it just feels like being back to square 0

vale sparrow
#

@static cedar btw, do you perhaps know a couple of things about 9 slices and animations? 👀

static cedar
#

What do you mean exactly? You mean like what they are fundamentally?

vale sparrow
#

look

#

i want to have a conveyor belt animations

#

that i can like stretch

#

or have it be any length

#

could i use 9 slice to split it up and have the middle part have an animation?

static cedar
#

Ah. Idk too much about that yet. But what i do know is that in 9-slice, the corners don't stretch whilst the side stretches only on 1 direction, and the middle section stretches both directions.
So you shouldn't be using 9-slice for the conveyor belt, that will still stretch the sides.

vale sparrow
#

ah

#

got it

#

will try to find something else, tysm

queen adder
#

Hey guys, can you tell me how when I clicked a button in one menu it will open another menu? Like this, I clicked inventory button and it will open the inventory menu. I tried to make simple inventory system as I added the inventory script to the player.

copper perch
timber tide
#

Use buttons and their events to call those methods

queen adder
timber tide
#

yeps

queen adder
# timber tide yeps

Alright. So I use that On Click on the Button, then which one that I should drag to the On Click?

timber tide
#

Which ever game object you want

#

you don't even need to make a script, it can already access the gameobject setactive method

analog depot
#

Netcode For Gameobjects and Local same system co-op multiplayer - Is it worth trying to solve both onlien and local play with the same system? Is there a pattern for local co-op as managed network objects?

queen adder
#

I put the InventoryMenu and the method are these, so I should chose the SetActive method, right? And after that, what I should do?

timber tide
#

try it out

queen adder
#

Everything correct but it seems something wrong with my Main Menu and Inventory Menu scripts. No errors showing on the console though

#

I also looked through youtube about On Click but it seems the fault lies on my Main Menu and Inventory Menu scripts

near knot
#

hello! i was following the unity course but while doing so i came across a problem but idk how to fix it, im basically trying to drag a script i made in an object in the hierarchy then this window pops up 😛

#

idk what channel to get help i hope this is it -_-

slender nymph
near knot
#

how about this error?

drifting horizon
#

how do you easily convert a float to a double

#

nvm got it

bitter canyon
#

does anybody know how i can make an object rotate around a 2d play by pointing at the mouse

#

i wanna make like a sword that swings around the player at a fixed distance

young warren
#

you'll find some resources on that

static mortar
#

hey guys, its been a while since i've used unity and i thought it would be nice to relearn it by making a lil Sonic fan game, more of a test/tech demo thing but uh yeah.

question i got here: how do i make it so there is acceleration to the walking, like: goes from the minimum speed to the maximum in a certain amount of time. (pretty much how acceleration works-)

#

nvm found the exact thing i was trying to do in git hub

elfin heron
#

hey! I'm making a game with input fields, I'm a starter so I don't really know much, so like I have it if its a string that it needs to be then it shows the gameobject, I aalready have everything but the script isn't really working, the text is equal as the string but it still somehow sees it like not equal (its a string "number")

Here is the script:

using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour
{
   public InputField inputField;
   public string desiredString = "1";
   public GameObject correctObject;
   public GameObject incorrectObject;

   private void Start()
   {
       if (correctObject != null)
       {
           correctObject.SetActive(false);
       }

       if (incorrectObject != null)
       {
           incorrectObject.SetActive(false);
       }
   }

   void Update()
   {
       if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter))
       {
           CheckAndShowObjects();
       }
   }

   void CheckAndShowObjects()
   {
       if (inputField != null && !string.IsNullOrEmpty(inputField.text))
       {
           if (inputField.text.Equals(desiredString))
           {
               StartCoroutine(ActivateAndDeactivateWithDelay(correctObject));
               Debug.Log("Correct!");
           }
           else if (!inputField.text.Equals(desiredString))
           {
               StartCoroutine(ActivateAndDeactivateWithDelay(incorrectObject));
               Debug.Log("Incorrect!");
           }

       }
   }

   IEnumerator ActivateAndDeactivateWithDelay(GameObject targetObject)
   {
       if (targetObject != null)
       {
           targetObject.SetActive(true);
           yield return new WaitForSeconds(2.5f);
           targetObject.SetActive(false);
       }
   }
}

please help me with this asap, I tried so many things!

floral trout
#

!code

eternal falconBOT
floral trout
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BaseStatModifier : ScriptableObject
{
    public iStatsHandler source; //what iStatsHandler created this stat modifier script
    public UnitStat.StatType statType;
    public UnitStat.IncreaseType increaseType;
    public float amount;
    public bool extra;

}
#

Hi, I'm getting an error with the following code(and another script using a BaseStatModifier value). I get a similar error when I create a new so script thats supposed to hold data for similiarly named script.

gaunt ice
#

did you save your script?

floral trout
#

yup

gaunt ice
#

are there any other compilation errors, the script looks correct

floral trout
#

there;s that, but i think they has to do with layers

gaunt ice
#

not error, just a log

#

everything looks correct...

floral trout
#

my only work around so far is slightly changing the name

fierce shuttle
gaunt ice
undone inlet
#

Can I ask git related questions here?

fringe plover
#

Fixed

tawdry nymph
#

soemthing in this code keeps freezing Unity and i dont know what

[Header("Fan")]
    public bool ActiveFan;
    public float floatiness;
    private float EndHeight;
    public float FloatHeight = 10f;

public void ToggleFan()
    {
        EndHeight = Player.transform.position.y + FloatHeight;
        
        ActiveFan = !ActiveFan;
        if (ActiveFan == true)
        {
            floatiness = 1.2f;
        }

        if (ActiveFan == false)
        {
            floatiness = 0f;
        }
        
    }
void Update()
{
  if (Player.transform.position.y > EndHeight && ActiveFan == true)
        {
            while (ActiveFan == true)
            {
                floatiness = Random.Range(1.15f, 1.2f);
            }
        }
        else if (ActiveFan == true)
        {
            floatiness = 1.2f;
        }
}```
fossil drum
tawdry nymph
#

thanks that worked

fossil drum
near knot
#

how do i fix this error??

#

i was following the unity official course and while in the lesson 1.2 in moving the "PlayerController" script, i came a cross an error but pop up window and an error came along too!

#

this error window

keen dew
#

You can't continue until you fix the error

near knot
#

thanks

torn vapor
#

Sup, ive ran into a pretty weird problem, when i hover over the gallery button the sounds still play even though its inactive, same thing with all the other buttons. However, the sounds do not play when all of the buttons are disabled, do you guys know what the problem could be?

rich adder
torn vapor
#

yeah, the buttons played sound even though they are inactive

#

its fixed now though, somehow they all depended on if new game button is active or not

stiff stump
#

how can i only show an value in the inspector if another value is true
ive seen it done in some packages not sure how to di t

civic oriole
#

Hey guys, how can i create maps like this? so realistic map with mountains and the stuff like that

#

i want to create a terrain generator but doesnt work

rich adder
#

and you need assets

#

anyone can make this with Enough assets

civic oriole
civic oriole
rich adder
#

this isn't a hand me script forum

civic oriole
#

i have a question for a script

#

this channel is "code-beginner" with description "Ask questions and discuss anything related to beginner coding concepts in Unity"

rich adder
#

doesn't mean scripts are handed out

#

you're expected to do at least some of the work yourself and come here for extra help / stuck

civic oriole
#

that's why i said how i can do it because i'm not getting anywhere with my own stuff

rich adder
#

how can you do what?

#

generating a map involved MANY different systems

#

including rule sets

civic oriole
#

i tried to create a gen but doesnt work

rich adder
#

"it doesnt work"

#

what does that mean

civic oriole
#

the terrain looks like this, wait i create pic

short hazel
#

If you want to make a terrain generator that yields something remotely complex, you're not going to do it in 4 hours

civic oriole
civic oriole
#

the only thing i get is this like the pic

short hazel
#

I'm talking more in the range of weeks-months to achieve a fully auto-generated terrain like in your first screenshot

civic oriole
#

i tried with ChatGPT but ChatGPT and coding is bullshit

rich adder
#

go figure

#

you have to grasp a firm understanding of mesh / uv manipulation including height map etc

#

make pong or some shit

#

this isn't a code beginner thing

civic oriole
rich adder
#

you can apply the same knowledge on terrain

timber tide
#

Basically you throw a bunch of noise maps at it until it looks like something

rich adder
#

pretty much xD

blazing plank
#

I've got a question regarding rigidbodys and their constraints. I've got a grabbable object (cube), and a grabber (my vr controller). I froze the cube's rotation in x and z but it still rotates in all directions. Following is the code responsible for the rotation (it's on the controller/grabber):

protected virtual void MoveGrabbedObject(Vector3 pos, Quaternion rot, bool forceTeleport = false)
    {
        if (m_grabbedObj == null)
        {
            return;
        }

        Rigidbody grabbedRigidbody = m_grabbedObj.grabbedRigidbody;
        Vector3 grabbablePosition = pos + rot * m_grabbedObjectPosOff;
        Quaternion grabbableRotation = rot * m_grabbedObjectRotOff;        

        if (forceTeleport)
        {
            grabbedRigidbody.transform.position = grabbablePosition;
            grabbedRigidbody.transform.rotation = grabbableRotation;
        }
        else
        {
            grabbedRigidbody.MovePosition(grabbablePosition);
            grabbedRigidbody.MoveRotation(grabbableRotation); //that's the problem
        }
    }

I think the constraints of the grabbed object get overwritten by the code part marked with the comment.
Changing the grabbableRotation to

Quaternion grabbableRotation = Quaternion.Euler(0, rot.eulerAngles.y, 0);

solved my problem, but that's a dirty workaround. Is there a way to make the freeze rotation constraints work the way they should?

runic lotus
#

anyone here worked with Microsoft mesh before?

short hazel
quaint thicket
#

I'm trying to setup animations via C# and I get a bunch of errors. Anyone know why?

rich adder
#

regen project files maybe

quaint thicket
#

Will try

rich adder
#

if you are using assembly definitions that might also be something to look into

quaint thicket
#

Regen didn't help

rich adder
#

also tthese errors are from another script

#

Animator.cs ?

#

not wise to name classes after Unity components that already exist

quaint thicket
#

Ah

quaint thicket
#

TY

blazing plank
# short hazel It rotates because you do so via `transform.rotation`, which bypasses the rigidb...

That unfortunately didn't work.
That's the updated code:

 protected virtual void MoveGrabbedObject(Vector3 pos, Quaternion rot, bool forceTeleport = false)
    {
        if (m_grabbedObj == null)
        {
            return;
        }

        Rigidbody grabbedRigidbody = m_grabbedObj.grabbedRigidbody;
        Vector3 grabbablePosition = pos + rot * m_grabbedObjectPosOff;
        Quaternion grabbableRotation = rot * m_grabbedObjectRotOff;        

        if (forceTeleport)
        {
            grabbedRigidbody.transform.position = grabbablePosition;
            grabbedRigidbody.rotation = grabbableRotation;
        }
        else
        {
            grabbedRigidbody.MovePosition(grabbablePosition);
            grabbedRigidbody.MoveRotation(grabbableRotation);
        }
    }

It still rotates in all directions

queen adder
#

hello, im still new and im not sure what im looking at...
i made a grid that dis places sprites, as you can see there are sprites, they are just small... im confused as to how the ui overlaps with the game camera and why wouldnt i see the sprites in the game view?

short hazel
#

The UI doesn't overlap, it's just how Unity renders it in the Scene View

short hazel
#

Resize your UI elements so they fit in that rectangle

queen adder
short hazel
#

Are these sprites under the UI, or in the world?

short hazel
#

Shouldn't make a difference anyway, but you might want to change the Pixels Per Unit value in the sprite import settings to make them bigger. That value represents how many pixels should be in a 1×1 square in world space

#

Like if you need the 16×16 image to fit in a square of 1×1 unit in the world, then set the PPU to 16

queen adder
short hazel
#

Nah camera and UI are separate. Looks like you're spawning them in via code, maybe they're at the same Z position as the camera (or behind), rendering them invisible?

#

They should be spawned at Z = 0

#

And the camera below that (default is Z = -10)

queen adder
#

jup, it was the camera, it was set to 0, thank you :D

blazing plank
stiff stump
#
    [CustomEditor(typeof(Item))]
    public class ItemEditor : Editor
    {
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            Item item = (Item) target;

            if (item._stackable)
            {
                item._maxStack = EditorGUILayout.IntField("Max Stack", item._maxStack);
            }
        }
    }

im trying to make the inspector only show the max stack property when stackable is true but this dosnt show anything wether it is true of false

not sure if this makes a difference but in the IDE

it says both the ItemEditor class and the OnInspectorGUI have 0 references

vernal pond
#

guys i am making an application that converts speech to text in unity engine, how can i do it ?

gaunt ice
#

dont cross post

#

have you google it first, i see some solutions on google

rotund hull
#

how do you put lights in a particle system in 2d because it doesnt let me

rich adder
rotund hull
#

in the particle system there is a tab for lights

rich adder
rotund hull
#

ok

rich adder
#

If its a slot for light you just drag the light inside

rotund hull
#

it is on the right

rich adder
#

I don't use 2D like that

rotund hull
#

ok

rich adder
# rotund hull ok

but yeah pretty sure its because 2D lights are different component than Light

rich adder
#

i dont see whats so special about this light slot

#

just make a prefab with the particle + 2D light

rotund hull
#

i am finna try that

spiral narwhal
#

I want to move a UI object to the Mouse position. Which of these camera conversion methods do I use?
For reference, Vector 0,0 is exactly in the middle of my Canvas and the _child is a direct child of the Canvas

_child.transform.position = Camera.main.ViewportToScreenPoint(Mouse.current.position.value);
short hazel
#

None of the conversion methods, mouse position is already in UI space

#

Assigning the mouse position directly to the RectTransform's position should do the trick

spiral narwhal
#
_childRectTransform.position = Mouse.current.position.value;

Unfortunately, this does not work, the position is somewhere in the middle of nowhere

short hazel
#

Log what's the result of Mouse.current.position.value

#

Never used that

spiral narwhal
#

It prints the resolution coords (at the end I was near the center of the canvas)

short hazel
#

Okay so like the old Input.MousePosition. Try changing the rect transform's .anchoredPosition instead, as this will respect its current anchoring preset

spiral narwhal
#

It is closer, but also out of bounds of the Canvas. I think if the vector 1376,1254 is appromately the center of my resolution, that's the issue right? Because the object would be considered in the center if it is at vector 0,0

#

That's why I thought I need some kind of conversion

autumn tusk
#

how would i make it so that any tile on a given layer automatically becomes a wall

short hazel
# spiral narwhal That's why I thought I need some kind of conversion

The coordinates you see in the inspector is local (relative to parent) position, like a regular Transform. Global position is what your logs show, where (0, 0) is bottom-left, and (x, y) is top-right and depends on your screen resolution. Your canvas is a screen-space overlay one, right?

spiral narwhal
#

No it's screen-space camera

short hazel
#

Okay that's why, then

#

No idea how to convert in this mode