#💻┃code-beginner

1 messages · Page 85 of 1

full imp
#

What I'm confused most about is the second part since before I run it everything is at 0,0,0

#

Then everything just moves up

slender nymph
#

you probably have some code doing that 🤷‍♂️

rich adder
#

Your agent is snapping to the navmesh

full imp
#

Okay I managed to moved it to 0,0,0 and the same problem still persists

#

Apparently the agent is still not close to navmesh

slender nymph
#

well it appears that you are spawning the object with the navmesh after the agent has started so that warning is going to persist

#

as for why clicking it doesn't work, have you ensured that the object you are creating there actually has a collider?

full imp
#

This is what I coded it to do

#

So everything should be there once the mesh is generated

#

(hopefully)

eternal needle
#

You'll probably have a better time just using a terrain here

#

You should add debugs like if that raycast hit anything, and where it hit. Maybe even put a object in your scene which follows where your raycast is hitting so you can visually see what's happening

slender nymph
#

yeah and also actually check the object after you've created the mesh instead of assuming that everything is set up correctly

full imp
#

Yeah everything is there

slender nymph
#

okay and what debugging steps have you taken

full imp
#

I've managed to print out the position of where the raycast hit

#

I'm also trying to do the second option where the object follows it

slender nymph
#

so you're printing out where the ray hits, so is it hitting the mesh?

full imp
#

Nahh it's not - that means the mesh doesn't have a collider?

#

The simple solution is to change the collider to convex but that would mean that the object would just float a bit

slender nymph
#

just for testing purposes, make the mesh collider convex and try it again

full imp
#

Yeahh it works on a flat plane

#

Oh wait since NavMesh makes the agent snap to the mesh wouldn't that mean that the agent wouldn't be able to float?

slender nymph
#

it might be that raycasts don't work correctly with non-convex mesh colliders. i'm not 100% certain on that, i'd ask for advice regarding that in #⚛️┃physics maybe

full imp
#

Yeahh I'll do more testing and if nothing happens then I'll go into that channel - thanks for the help though 🙂

eternal needle
upbeat moon
#

Hey all, I have a quick q. I have a list of 7 keywords, that get compared against a speech to text string. That all works fine, my issue is I only want my keywords to increase a score value 1 time and then not be able to increase the score value again.

wintry quarry
#

Save the already used ones in a HashSet or List and check each time if it's been used or not

#

Or remove them from the list as they are used

upbeat moon
#

thank you!

#

i was so blocked on that

#

removing them seems iffy, I think adding to list and checking against will be ok as it's only 7 keywords

upbeat moon
unreal imp
#

guys how i set the object that the player is carrying in the object holder?The objectHolder is an object that indicates where the object is positioned when you carry it, as in my case I placed it in front of the camera

#

the code part: void GrabObject(GameObject obj) { objRigidbody.isKinematic = true; obj.transform.SetParent(objectHolder); obj.transform.position = objectHolder.position; float yRotation = obj.transform.rotation.eulerAngles.y; if (yRotation < 90f) { obj.transform.rotation = Quaternion.Euler(0f, 90f, 0f); } else if (yRotation < 180f) { obj.transform.rotation = Quaternion.Euler(0f, 180f, 0f); } else { obj.transform.rotation = Quaternion.Euler(0f, 0f, 0f); } }

wintry quarry
#

That rotation code is janky, and it's unclear where that rigidbody reference comes from. But otherwise looks ok assuming the references are ok

#

What's the issue you're having?

unreal imp
#

that rotation thing is something I'll ask about later

#

I wanted to make it so that by pressing E on an object the player could carry it

#

the objectHolder I think you will know what it is

wintry quarry
#

Well like I said this seems mostly ok what issue are you having?

verbal dome
unreal imp
#

I actually want to do all 3

unreal imp
verbal dome
#

Then get the rigidbody component and check its mass

#

hit.collider.attachedRigidbody

unreal imp
#

yep i already did that if (objRigidbody != null && objRigidbody.mass <= 15f)

unreal imp
#

carrying object position = object holder position

verbal dome
unreal imp
# verbal dome What exactly goes wrong?

As I said, the GrabObject code method does not apply, that is only because I already did debug.log in everything.
It seems weird because it looks so correct

#

Do you have any solution or do you know which is the problem?

verbal dome
#

So is GrabObject even getting called? And do you get any errors while playing/grabbing?

#

Where do you set objRigidbody?

#

Showing the rest of the !code would be better

eternal falconBOT
unreal imp
abstract finch
#

Is it possible to return a bool from an inheritant class form the main one?
public class Dog : Ai

teal viper
last edge
#

hey guys am i allow to copy paste code files here or no?

abstract finch
verbal dome
teal viper
abstract finch
#

the attack class is basically a collider that holds the transform inside it

abstract finch
teal viper
#

Python?

last edge
#

yep

teal viper
#

How is that unity related?

last edge
#

its not xD i joined this awhile ago when i had a c# project so hoping maybe someone here maybe could lend a hand even though its kinda off topic

#

it was a last min desperate attempt

abstract finch
#

thanks

teal viper
#

This is not the right place.

last edge
#

gotcha fair enough sorry about that

verbal dome
#

Also instead of this; cs GameObject obj = hit.collider.gameObject; Rigidbody objRigidbody = obj.GetComponent<Rigidbody>();
Do this:cs Rigidbody objRigidbody = hit.collider.attachedRigidbody;
Otherwise it won't work on child colliders

abstract finch
austere monolith
teal viper
wintry quarry
austere monolith
#

aight

#

that wasnt it

#

but its my fault for not giving the gunscript too

#

the issue was that in the script i gave, it was able to go to previous and next when scrolling, but the gun script only had one direction for scrolling

dense root
#

How I get my NPC objects to move left and right?

private float speed = 1f;
public float direction = 1f; // 1 for right, -1 for left

private void Update()
{
    transform.Translate(new Vector2(speed * Time.deltaTime * direction, 0));
}
#

This just moves it up

silk night
#

Also if your object is rotated it will move your object in the local direction relative to its rotation

polar acorn
rich adder
frank whale
#

Guys, I'm having a problem with light2D:
"The type or namespace name 'Light2D' could not be found (are you missing a using directive or an assembly reference?)"
Does anyone know what I can do? I tried adding "using UnityEngine.Rendering;" and it's not working

frank whale
#

Dude, I'm pretty new to this "assembly" thing, like I was doing some work and out of nowhere some assembly errors came up, I watched some videos, read a little, tried to fix it by creating an assembly definition, but these problems came soon after

frank whale
#

Ah, I added a URP runtime assembly and the error stopped, now I just need to resolve the same error for something like "searchService" and "U2D", that's difficult.

nimble scaffold
#

Guys which is best normal coding or visual scripting??? And which is easy

#

And please tell me how to get water in unity

#

And also tell me how to make my fps game multiplayer and 10 max member each room capacity using photon

ashen trail
#

Hello. Can someone send me a link of a unity beginners coding guide to C#. I cant find it. thx!

gaunt ice
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

ashen trail
#

THX

nimble scaffold
rich adder
round scaffold
#

first question is pretty subjective lol

cerulean crypt
#

Heya, does anyone know how to prevent my camera from flipping upside down? I'm currently attaching it to my mouse movement using this code void Update() { transform.eulerAngles += LookSpeed * new Vector3(-Input.GetAxis("Mouse Y"), Input.GetAxis("Mouse X"), 0); }

#

I don't really understand what attribute determines whether the camera is upside down so I can't lock it in place

ivory bobcat
cerulean crypt
#

If so, the y doesn't seem to be the problem. It can have the same values whether the camera's flipped or not

summer stump
#

They can go negative while the ones in the inspector are positive. They don't always match, if that's what you meant

cerulean crypt
#

Because the inspector does show both pos and neg and I can get the camera to flip without the Y val changing

summer stump
cerulean crypt
#

Ah it's the X value being outside the range of 90 -> -90

#

Dunno how it happens but I'll try limiting it

#

Nope NVM wasn't that

#

Okay still confused on what value is different from the camera to be upside down

#

Okay so still don't completely understand why it flipped, however I managed to stop it from flipping by preventing the camera from looking directly up/down or any update that would've pushed it past. I used the eulerangles.x value to figure out how high up the camera was pointing. Thanks for the suggestions guys!

static cedar
#

What have you made or done so far?

teal viper
topaz mortar
#
Equipment equipment = FindFirstObjectByType<Equipment>();```
Why does the 2nd line work but the 1st throws a NullReference?
Equipment is a Script reference on a character gameobject that references the equipment gameobject
eternal needle
#

the 2nd line has no relation, that searches for any loaded object unrelated to whatever a character is

topaz mortar
#

yeah just tested that, character is set, but it doesn't find the equipment on character

eternal needle
#

then there is no equipment on the character

topaz mortar
#

I'm missing something stupid lol
I can see the equipment script on my character, hmmm

teal viper
eternal needle
#

like dlich said, you could be looking at the wrong place, but you could be looking at the wrong time. What if you are doing character = null at some point

woven crater
topaz mortar
#

is there some way I can list all the components of my character?

eternal needle
topaz mortar
#

ah lol, equipment is a private variable on character
just had to do character.Equipment to use the get function

eternal needle
#

🤔 how were u seeing an Equipment component on your GO then?

topaz mortar
#

[SerializeField]

#

in editor

eternal needle
#

that alone is just a way to provide a reference, it still not a component on the GO then. But glad you solved it at least

eternal needle
teal viper
topaz mortar
#

thx for the help 🙂 working perfectly now

#

knew I was doing something silly lol

woven crater
#

i did and also not understand much

teal viper
#

!code

eternal falconBOT
slender nymph
woven crater
#

it matched

slender nymph
#

Turretattribute != TurretAttribute

woven crater
#

ah got it. thank much

teal elk
#
    {
        if (input.Shoot)
        {
            gunController.OnTriggerHold();
            playerController.PlayShootTrigger();
            Debug.Log(input.Shoot);  
        }
        if (input.ShootRelease)
        {
            gunController.OnTriggerRelease();
            playerController.ResetShootTrigger();

        }
    }``` anyone  know why my animation is refusing to trigger, i get no errors.
topaz mortar
#

Is there a way to programatically assign a Scriptable Object to a gameobject?

eternal needle
eternal needle
#

some script is either gonna have to use Resources (or something similar) to load them all from assets, or you'll need to drag the reference into a script with a public or [SerializeField] field

timber tide
#

make a database of SO references if they are loaded already

eternal needle
#

depends what you're trying to do

topaz mortar
#

I'm saving my items to a database
But I need some way to save the SO to the database and then load it in my game again

timber tide
#

ids

eternal needle
#

why would you need to save a SO, these should be immutable data

topaz mortar
#

just need to save a reference to it, like an id
but I'd still need to load the SO on the item once I create it

#

my item SO's hold the item image

queen adder
#

i'm trying to Loop through a list of classes but for some reason unity throws a NullReferenceException unless i have the player selected in the Hierarchy

slender nymph
#

show the code, i'd bet something in the list is null, not the list itself

eternal needle
# topaz mortar my item SO's hold the item image

ah my misunderstanding, yes you'll have to generate your own ID. How u do this really doesnt matter, an ID can be an int, string, whatever you want as long as you have 1 unique per item. You could store a dictionary from ID -> SO but when you save you'll also need SO -> ID.
I think best would just be store the ID on the SO, then some database holds all the SO in a list (or you can still do a dictionary if you care to)

topaz mortar
#

yeah the problem is not the saving
I just don't know how to load (attach SO to gameobject) my SO again through code, I've only used SO's through references
I guess Resources.Load?
Or should I make a gameobject that holds all my item SO's that I can reference instead?

queen adder
#

the code works perfectly fine if i select the player but doesn't work if i didn't, i'm not sure if this is the correct way to create lists

eternal needle
#

it would likely be a singleton unless u are some die-hard DI fan

#

Resources.Load would be more automatic, but you have to follow its forced file structure

topaz mortar
#

yeah it would be a bother to manage that dictionary

timber tide
# topaz mortar just need to save a reference to it, like an id but I'd still need to load the S...
public class SerializeItem
{
    public string storableID;
    public List<string> modIDs = new();
}

public class string WriteItem(Item item)
{
    if(value == null)
    {
        return null;
    }

    SerializeItem serializeItem = new();
    serializeItem.storableID = item.Storable_ID;
    
    foreach(String mod in serializeItem.ModIDs)
    {
       //Add mod ids
    }

    //Convert to JSON
}

public Item ReadItem(string value)
{
    if (value == null)
    {
        return null;
    }

    //Convert back to type

   return new Item(serializeItem);
}```
eternal needle
#

it wouldnt have to, you can directly plug them all into a list in one motion. then on awake, the script can generate the entire dictionary. Its technically more of a waste of space but 🤷‍♂️

timber tide
#

oh yeah and your load manager should have a dictionary of SOs

#

too lazy to write that all

#

Dictionary<ID, SO>

#

implying your SOs are immutable

#

I would just paste my whole script but it's tangled in covariance bullcrap

topaz mortar
#

seems way too complicated for what I need lol

#

Resources.Load is probably fine

timber tide
#

I've actually not really touched much on Resource.Load but I should probably look into it. I feel like SOs are light enough as is for data objects.

uncut holly
#

what does the time.deltatime and the number 20 mean?

eternal needle
eternal needle
timber tide
#

thing is I feel like stuff for items I would never dynamically remove the SOs once loaded in so I feel like I should just upfront it all

eternal needle
#

yea for sure, makes sense for an item dictionary. i just find resources really awkward because of the forced file structure. I also dont know how the other solution works but i plan to learn it eventually

timber tide
topaz mortar
#

Not sure if I explained it right.
My game is saved to and loaded from a MySQL database
So in the database a simplified item would have: ItemSO-ID, itemName, itemStats, ...
So when the player loads the game and I Instantiate their items, I somehow need to re-attach that ItemSO-ID as a Scriptable Object to the Item gameobject

#

The only thing I use the SO for is storing the item image (maybe there's a better way to do this?)

timber tide
#

dictionary

#

database ID to match up with SO ID

topaz mortar
#

but then I'd have to manually drag all my SO's into that dictionary?

#

and they are subject to (a lot) of change

timber tide
#

Eh, you can just do it in start()

#

Make a script to grab all SOs you want, then when you start your program it adds all SOs to a dictionary using their ID as a key

topaz mortar
#

I'd still need to use Resources.Load for that then?

timber tide
#

Resource.Load is for when you don't want to upfront the assets. As is, you load every single asset in your program if it's not bundled in a way or stored specifically. Actually stuff is somewhat compiled out I think if it's not part of game assets like prefabs, SOs, ect. Need to read up more on this.

topaz mortar
#

so you're saying I don't need it?
then how to I put the SO in my dictionary?

#

The SO's don't exist in my scene, they're only in my assets folder

timber tide
#

SOs dont ever exist in the scene. You start your program and you instantiate a single instance of each of them

#

and they live in memory

topaz mortar
#

I might end up with thousands of items over time, so it's probably better to just load the ones I need instead of putting them all in the dictionary?

#

one player will only be using 10-100 items
but there might be 1000's in the database

#

item types, not items

timber tide
#

Right, so this is what me and bawsi was saying that if you don't want these instances to be loaded on program start, then you need an alternative way to bundle them then load them via path or directory.

topaz mortar
#

so Resources.Load?

timber tide
#

Yeah, and assetpath/bundles

#

Depends how you want to manage the data, but SOs alone aren't heavy, it's usually what they are referencing is what you want to manage.

#

textures/models/ect

topaz mortar
#

So I guess I just save the resources.load path to my database instead of an id?

#

it's just basic sprites, nothing heavy

#

2d game

timber tide
#

path is pretty much unique so it can be an ID. May still be wise to give the SOs a guid.

topaz mortar
#

this helped a lot, thx 🙂

timber tide
#

ye

topaz mortar
#

actually don't even need to save the path if I just make sure my item name is always the same as my SO name

#

gold.ItemSO = (ItemSO)Resources.Load<ScriptableObject>("Items/" + gold.name); 🙂

teal elk
noble summit
#

What is the word for unlocking cursor in Cursor.lockState = CursorLockMode. ?

ivory bobcat
tawdry mirage
#

if i make SmallClass smallClass { get; private set; } i can access it with bigClass.smallClass
how to "override" it so it returns other smallClass?

#

so it's not bigClass.smallClass(), just bigClass.smallClass

#

i know i can make it as virtual method and then just override it, but can i make it look like it is property?

gaunt ice
ivory bobcat
timber tide
#
bigClass.smallClass(), just bigClass.smallClass```
What is your expected return type here?
tawdry mirage
#

SmallClass

timber tide
#

Yeah, but even if you override it, you're still expected to have an explicit return type.

#

Sounds like you'd probably want some generic constraints, but I'm not exactly sure of your use case.

#

You know what, maybe it is a property you need.

tawdry mirage
#

damn i already knew how to do that :/

#

already did that 3 months ago

#

sooo
if parent creates new list

public virtual List<Waypoint> waypoints { get; protected set; } = new List<Waypoint>();

but child override it without creating new list

public override List<Waypoint> waypoints { get; protected set; }

no new list will be created, right? or it will be created and removed by GC?

timber tide
#

I'd assume the compiler is smart enough not to create it.

ivory bobcat
#

Looks like default value is a new instance

#

Override simply mutates the getter and setter?

timber tide
#

Does that throw any errors? Pretty interesting design choice but if it works.

#

also still waiting on my struct initializer update ;(

ivory bobcat
#

I'm assuming the back field is made visible to the inspector and modifiable.

gaunt ice
#
using System;
public class P{
    public virtual int x{get;set;}=100;
}
public class C:P{
    public override int x{get;set;}
}

public class HelloWorld{
    public static void Main(string[] args){
        Console.WriteLine(new C().x+" "+new P().x);
    }
}
```outputs 0 100, looks likes the field initialization also be overridden not only the getter setter
#

may not be true inside unity btw

ivory bobcat
#

Just reread that, got it.

#

Those were x outputs from two different instances

tawdry nymph
#

I want my enemy to turn around when it hits a wall but I can't figure out why it doesn't work this is my code

public bool TurnRight = false;
    private void OnCollisionEnter2D(Collision2D collision)
    {
        print("turn");
        if (TurnRight)
        {
            transform.parent.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(1, 0);
            TurnRight = false;
        }
        if (!TurnRight)
        {
            transform.parent.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(-1, 0);
            TurnRight = true;
        }
    }```
the collision is being called and the boolean is being turned but the velocity won't change?
ivory bobcat
#

Both if statements will be true if the first is true

#

You probably want an else if

#

Or simply an else

gaunt ice
#

second->
first then second (after first if block sets the turnRight to false second if block got executed)

tawdry nymph
#

that makes sense, but an else statement still gets called, do i need to implement some sort of cooldown?

ivory bobcat
#

You could probably also do:cs { ... = new Vector2(TurnRight ? 1 : -1, 0); TurnRight = !TurnRight; }

ivory bobcat
tawdry nymph
#

but it seems to call the collision entry 2 times so the second time it would be rediorected to the else statement

timber tide
#

Is there such a data struct in c# that's a linked list, but instead of autosizing I'd keep the preferred size so I can reuse my struct data. It's an odd requirement, but I should never have a capacity larger than preferred, and would like to insert at O(1)

ivory bobcat
gaunt ice
#

just limits the size before insert?
btw linked list is not random access

timber tide
#

yeah, but you always have the head

#

what's happening is that I have data being removed at different times

#

I'm working with buffers so I've got a capacity and stride I need to respect, but so each of these objects in the linked list will have an index to the buffer when it's read in

ivory bobcat
#

If the number of elements aren't too much, consider a regular list.

timber tide
#

Yeah, but the thing is I need a 0(1) insert time while respecting nulls and capacity

ivory bobcat
#

Want or need?

#

The two types of collection both have their limitations.

timber tide
#

buffers that were being updated every frame. It's something that probably needs to be as performative as possible.

ivory bobcat
#

Is insertion speed more important or avoiding garbage collection de-allocation UnityChanwow

timber tide
#

idk :(

#

it's a particle pool so I have a lot of indices

gaunt ice
#

just keeping a regular array and remove as swap back, since each element have the index pointing back to the array

timber tide
#

linkedlist -> Knows where to add on last. Knows how to reconnect list when data is removed. But, is garbage collected when removed.

ivory bobcat
#

Yes.

timber tide
#

instead of recreating structs of my data, I just need to change a variable from on to off

#

that's kinda what I'm trying to do

#

can't be nulls in the buffer and it respects a stride

topaz mortar
#

Hello again 😇
So I have a GameObject Character that holds a Script Character that References a Script Inventory
How do I get my Character Script through code in the Inventory Script?
I've tried GetComponent, GetComponentInChildren and GetComponentInParent but can't seem to fetch it?
Probably doing something silly again

tawdry nymph
gaunt ice
#
public struct Array<T>where T:IHasIndex{
public T arr;
public int count;
public void remove(T t){
  count--;
  T back=arr[count];
  back.index=t.index;
  arr[t.index]=back;
}
}
ivory bobcat
topaz mortar
tawdry nymph
#

that doesn't work either...

topaz mortar
ivory bobcat
timber tide
#

Yeah, I swear I've used some library for this type of struct in c++ but doesn't seem to be such natively in c#

#

capacity with head and tail pointers that aren't removed

ivory bobcat
#

Just pool the data. I don't think adding nodes are the issue. The old nodes being collected are a concern though.

tawdry nymph
ivory bobcat
topaz mortar
#

he posted it above

ivory bobcat
#

I've only seen the previous with two if statements

topaz mortar
#

just updated oncollisionenter to oncollisionstay I think

ivory bobcat
#

Which the second would behave the first - relative to the boolean turn right.

tawdry nymph
#
    private void OnCollisionStay2D(Collision2D collision)
    {
        print("turn " + gameObject.name + transform.parent.gameObject.GetComponent<Rigidbody2D>().velocity);
        transform.parent.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(TurnRight ? 1 : -1, 0);
        TurnRight = !TurnRight;
    }```
ivory bobcat
topaz mortar
tawdry nymph
#

I just added the velocity to the log and it does say it's changing so the problem is still the multiple calls

topaz mortar
ivory bobcat
#

Comment out the velocity statement and see how often it's printing.

#

If the object is intentionally returning to the collision point after being repelled, you'll get multiple events to be fired.

topaz mortar
#

that's probably what is happening yeah

tawdry nymph
ivory bobcat
#

That's what's assumed.

#

I'm assuming this is some pong variant that only traverses left and right.

topaz mortar
#

Character character = this.gameObject.GetComponent<Character>();
How is this returning Null when the script I'm calling it from is referenced inside a Character script?
this is Inventory, which is referenced inside my Character 😦

ivory bobcat
#

Get component returns null if the object doesn't have the component

tawdry nymph
topaz mortar
ivory bobcat
topaz mortar
#

NullReferenceException: Object reference not set to an instance of an object

tawdry nymph
ivory bobcat
#

Game Object property cannot return null so I'm assuming you're using the reference elsewhere that's causing the error to be thrown.

topaz mortar
#

ah yeah my line just returns Null

tawdry nymph
#

so it is turning back in a different frame

topaz mortar
#

no error

tawdry nymph
teal viper
topaz mortar
#

I just want to get my Character Script from the Inventory Script
GetComponent, GetComponentInParent and GetComponentInChildren all return Null

ivory bobcat
topaz mortar
#

yeah the error is from the line below where I try to use it lol, error is not important here
I just don't get how it can return null - or how to fix iit

teal viper
#

And share more of the code.

ivory bobcat
#

When logging with debug, use the second argument of this to have the object highlighted.

#

Perhaps forcefully pausing the editor if the object isn't in the scene by default

topaz mortar
#
{
    public void AddItemToInventory(Item newItem)
    {
        //Character character = FindFirstObjectByType<Character>();
        Character character = this.gameObject.GetComponent<Character>();
        Debug.Log(character);```
topaz mortar
ivory bobcat
#
Debug.Log($"Character: {character}", this);```
#

If you select the log in the console tab, it'll highlight the object in the hierarchy.

#

If present

gaunt ice
#

if the inventory and character are in the same gameobject, why dont just reference it?

topaz mortar
teal viper
topaz mortar
#

so my inventory script is on a totally different gameobject lol

ivory bobcat
#

It's very common UnityChanCoder

topaz mortar
#

and Character is just also referencing that gameobject script

#

crazy

uncut holly
#

hello, i may need some help regarding understanding this code. so i can understand the plater is link to the game object (main camera) but i am confused about the transform.position = player.transform.position + new Vector(0, 5, -7)

#

so will it repeatedly like go up since the y is a positive

gaunt ice
#

Player.transform+offset

#

Not its transform+offset

ivory bobcat
uncut holly
ivory bobcat
#

It should set this object to the position of the player with some offset

#

If this component is on the player, you'll go up to infinity.

uncut holly
#

so the code i sent earlier, the player.transform.position + new vector(0, 5, -7) since its written under update does y goes up by 5 units repeatedly

uncut holly
ivory bobcat
#

Or if this object's position is with respect to the player as well

#

ie child object etc

gaunt ice
#

If the player is child then the camera and player will both go up infinitely

uncut holly
#

then i have a question since this code is in the components of the main (im doing unity tutorial), why does it still ask me to target a game object

#

shoudnt it by default bve targeted onto the main camerqa\

ivory bobcat
#

So, make sure the camera/player aren't children or parents of each other.

uncut holly
#

so i should leave this on none(game object) ?

ivory bobcat
#

You'll get a null reference exception error, if that is what you're wanting.

uncut holly
#

so with this code as it is now if i set the main camera as the variable of Player the camera will just fly up right?

fossil drum
#

You have -7 on the Z axis too, so not just up.

gaunt ice
#

is your vs configured?

eternal falconBOT
uncut holly
#

configured?

topaz mortar
#

we should have youtube links to basic tutorials for stuff people ask here non stop
like basic movement of objects (player bouncing earlier, camera following player now, ...)

uncut holly
#

i configured it long time ago actually

#

oh wait wrong one

#

wait ah

craggy bane
#

Hi I'm trying to figure how how to pool 4 different objects make them spawn every 3 seconds and pool them everytime the objects animation occurs

uncut holly
#

you mean this

fossil drum
ivory bobcat
#

Are you able to do object pooling with a single object?

craggy bane
#

But I haven't been able to do that so I thought of object pooling

craggy bane
ivory bobcat
#

What is this for, bullet pooling?

craggy bane
#

Uhh well it's a trash picking game

#

Basically when you click a button 2 animations occur 1 is a tenticle and 1 is a trash

uncut holly
#

its looks nice, better than mine

craggy bane
#

I just need 1 last thing to implement

ivory bobcat
#

The waste management in my county takes paper and plastic together.. thus we've got to clean off food particles from recycled products before recycling them.

craggy bane
#

I want 1 enemy spawned every 3 seconds and dequeued or despawn after 3 seconds

#

but I want it to have the original animation

ivory bobcat
#

We're assuming you've got the spawn and despawn done?

uncut holly
#

since its going up sideways

ivory bobcat
#

Each instance should have its own unique animation timer. Maybe reset the animation state when spawning from the pool?

craggy bane
#

Like each instantiated object should have the animation of it's original?

fossil drum
hollow zenith
#

    public float SellValue { get { return 3 * Level; } internal set { } }

Can I still use setter without creating 2nd variable to store it?

ivory bobcat
uncut holly
fossil drum
uncut holly
#

full screenshot of unity editor or visual studio code

#

oh theres a miscellaneous files

uncut holly
fossil drum
# uncut holly

Yeah it's not setup correctly, spend some time on doing that.

craggy bane
#

yo, Animator anim = Instantiate(object, position, rotation).GetComponent<Animator>(); can someone explain what I should be putting in object, position, rotation in my 3d game

uncut holly
fossil drum
uncut holly
dry tendon
#

heey, how could i add an image to the canvas without deformming it?

fossil drum
uncut holly
#

assign camera as the players position

fossil drum
uncut holly
# dry tendon

this is a deformed canvas? looks preety okay to me

uncut holly
fossil drum
uncut holly
#

wait lemme try something

#

or do i change the target for the player to the tank

lyric drift
#

hello

fossil drum
#

Don't blindly do things, you need to understand what you are doing.

lyric drift
#

i wanna make a script that when b is clicked that it summons a 3d model on the player. anyone know how i could be helped?

modest dust
# uncut holly yes?

You're basically telling the camera to move away from the "player" which is camera itself. It will just constantly try to move away from it's own position

uncut holly
#

ah i got it ... i cahnged the target from the camera to the car ... now the camera is stuck to the car

median escarp
#

can someone see my code and tell me why its not working please

craggy bane
#

Guys how do I put an objects animation on its cloned version

fossil drum
eternal falconBOT
median escarp
#
using UnityEngine;

public class MeleeEnemy : MonoBehaviour
{
    [Header ("Attack Parameters")]
    [SerializeField] private float attackCooldown;
    [SerializeField] private float range;
    [SerializeField] private int damage;

    [Header("Collider Parameters")]
    [SerializeField] private float colliderDistance;
    [SerializeField] private BoxCollider2D boxCollider;

    [Header("Player Layer")]
    [SerializeField] private LayerMask playerLayer;
    private float cooldownTimer = Mathf.Infinity;

    //References
    private Animator anim;
    private PlayerHealth playerHealth;
    private MonsterMovement enemyPatrol;

    private void Awake()
    {
        anim = GetComponent<Animator>();
        enemyPatrol = GetComponentInParent<MonsterMovement>();
    }

    private void Update()
    {
        cooldownTimer += Time.deltaTime;

        //Attack only when player in sight?
        if (PlayerInSight())
        {
            if (cooldownTimer >= attackCooldown)
            {
                cooldownTimer = 0;
                anim.SetTrigger("Attack");
            }
        }

        if (enemyPatrol != null)
            enemyPatrol.enabled = !PlayerInSight();
    }

    private bool PlayerInSight()
    {
        RaycastHit2D hit = 
            Physics2D.BoxCast(boxCollider.bounds.center + transform.right * range * transform.localScale.x * colliderDistance,
            new Vector3(boxCollider.bounds.size.x * range, boxCollider.bounds.size.y, boxCollider.bounds.size.z),
            0, Vector2.left, 0, playerLayer);

        if (hit.collider != null)
            playerHealth = hit.transform.GetComponent<PlayerHealth>();

        return hit.collider != null;
    }
    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireCube(boxCollider.bounds.center + transform.right * range * transform.localScale.x * colliderDistance,
            new Vector3(boxCollider.bounds.size.x * range, boxCollider.bounds.size.y, boxCollider.bounds.size.z));
    }

    private void DamagePlayer()
    {
        if (PlayerInSight())
            playerHealth.TakeDamage(damage);
    }
}
#

it should display the attack animation and deal damage to the player when its inside the hitbox but it doesnt

fossil drum
fossil drum
fossil drum
craggy bane
#

Guys how do I put an objects animation on its cloned/instantiated version

modest dust
craggy bane
modest dust
#

Then put these animations onto the animator and play the animation you need

craggy bane
fringe plover
#

is something wrong? text is "x", but it doesnt display coin count

modest dust
craggy bane
#

they clone themselves when the game starts

fringe plover
modest dust
fringe plover
craggy bane
#

I think I already did that

#

wait

craggy bane
#

but they don't only the original do

fringe plover
#

ur getting component, not adding🤓

craggy bane
#

bro no way that's what the problem was

#

😭

fringe plover
#

add component and then get it

modest dust
craggy bane
fringe plover
#

you didnt forget to save prefab right?

modest dust
#

Unless you remove it manually, it should be there

craggy bane
minor roost
#

using UnityEngine;

public class TerrainGeneration : MonoBehaviour
{
public int worldSize = 100;
public float NoiseFreq = 0.05f;
public float seed;
public Texture2D noiseTexture;

private void Start()
{
    seed = Random.Range(-10000, 10000);
    GenerateNoiseTexture();
}

public void GenerateNoiseTexture()
{
    noiseTexture = new Texture2D(worldSize, worldSize);

    for (int x = 0; x < noiseTexture.width; x++)
    {
        for (int y = 0; y < noiseTexture.height; y++) 
        {
            float v = Mathf.PerlinNoise((x + seed) * NoiseFreq, (y + seed) * NoiseFreq); 
            noiseTexture.SetPixel(x, y, new Color(v, v, v));
        }
    }

    noiseTexture.Apply();
}

}

minor roost
#

help whats error?

fringe plover
#

!code

eternal falconBOT
fringe plover
minor roost
fringe plover
#

i mean !code

eternal falconBOT
minor roost
#

!code

eternal falconBOT
fringe plover
#

JUST OPEN IT AND PASTE CODE INSIDE

minor roost
#

you know error?

fringe plover
#

i dont see anything wrong

#

try copy and paste script

minor roost
#

ik

fringe plover
#

it helped to me

gaunt ice
#

did you save your code, how your ide looks like?

minor roost
fringe plover
blazing jay
#

Hi i created an isGrounded bool variable and a few lines after its not detecting it for some reason.

fringe plover
#

:/

#

im gonna kill myself if i see that again

#

use isGrounded instead of isGrounded()

#

almost all text with () means function

gaunt ice
#

isGrounded is method, it is not variable

blazing jay
blazing jay
fringe plover
#

everywhere

blazing jay
fringe plover
#

everywhere, replace all isGrounded() with isGrounded

blazing jay
#

but than the other code parts lose the accessor

gaunt ice
#
private TextMeshPro text;
[SerializeField] private SaveManager saveManager;
[SerializeField] private PauseManager pauseManager;
```why not just serialize the text (as the two fields below) and drop the instance to it in inspector?
fringe plover
#

im getting TMP as component

delicate notch
#
    private void OnTriggerEnter2D(Collider2D collision)
    {
        // Read dmg then reduce health of player
        dmg = collision.GetComponent<DamageDealer>();

        if (dmg != null)
        {
            Destroy(collision.gameObject);

            health -= dmg.GetDamage();

            Debug.Log("Damage recived: " + dmg + " Player health: " + health);
        }


        if(health <= 0)
        {
            // Player Ship Destroy.
            Destroy(gameObject);

            Debug.Log("Player Destroyed!");

            return;
        }
    }

fringe plover
#

and?

#

any text?

gaunt ice
#

you dont need to get it in Start().....

fossil drum
fringe plover
fossil drum
gaunt ice
#

just serialize the reference and set it in inspector

fringe plover
#

oh ok

delicate notch
fringe plover
fossil drum
rigid hinge
#

guys why i have to click E multiple times to make the code works

this is the code:

RaycastHit hit;

        if (Physics.Raycast(transform.position, transform.forward, out hit, RayDistance))
        {
            
            if(hit.transform.tag == "Sofa")
            {
                  if(FNum == 0)
                {
                    InteractionE.SetActive(true);
                }
                else
                {
                    EmptySlot.SetActive(true);
                }   
                if(Input.GetKeyDown(KeyCode.E) && FNum == 0)
                {
                 FNum = 1;
                 _Sofa.SetActive(false);
                 SofaUi.SetActive(true);
                }
            }

           if(hit.transform.tag == "Table")
            {
                if(FNum == 0)
                {
                    InteractionE.SetActive(true);
                }
                else
                {
                    EmptySlot.SetActive(true);
                }
                
                if(Input.GetKeyDown(KeyCode.E) && FNum == 0)
                {
                  FNum = 1;
                  _Table.SetActive(false);
                  TableUi.SetActive(true);
                }
            }
delicate notch
fossil drum
fringe plover
delicate notch
fossil drum
tawdry mirage
#

i'm making some navigation with waypoints. Now i need to make A-B-C path calculation, where A and C are just single waypoint, and B is array of waypoints. So, first i need to find shortest paths from A to each of B, then shortest path from each B to C, then pick two shortest paths and return them. Is it just better to go with cached pathfinding instead?

fringe plover
delicate notch
fossil drum
fringe plover
delicate notch
fringe plover
delicate notch
fossil drum
topaz mortar
#

Uff what am I getting myself into public static List<Dictionary<string, object>> LoadItems(int playerNumber)

delicate notch
#

its in a separate if statement

fossil drum
#

Destroy runs, kills the object, Debug.Log never runs.
Change them around, and it works just fine.

gaunt ice
gaunt ice
# fossil drum

the Debug.Log will still run even the object destroyed, instructions are saved in different memory space

fringe plover
#

` if(health <= 0)
{
// Player Ship Destroy.
Debug.Log("Player Destroyed!");
Destroy(gameObject);

        return;
    }
}`
delicate notch
#

E ye still desont

ivory bobcat
#

Destroy shouldn't occur immediately UnityChanHuh

#

Likely the if statement isn't true

delicate notch
#

Thats why idk why my ship being destroyed when conditions arent met

fossil drum
#

The ship gets destroyed.

ivory bobcat
#

Ah, I'm not aware of the discussion. Maybe something else is destroying it UnityChanHuh

gaunt ice
delicate notch
#

Il just make it die through a boolean variable and see what happens

ivory bobcat
#

comment out that destroy call and see if he's still being destroyed

#

The problem won't go away if this isn't the cause

delicate notch
#

bro what i did it like this look

    bool isDestroyed = false;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        // Read dmg then reduce health of player
        dmg = collision.GetComponent<DamageDealer>();

        if (dmg != null)
        {
            Destroy(collision.gameObject);

            health -= dmg.GetDamage();

            Debug.Log("Damage recived: " + dmg + " Player health: " + health);
        }


        if(health <= 0)
        {
            isDestroyed = true;
        }
    }

    void isDead()
    {
        if (isDestroyed)
        {
            Destroy(gameObject);
        }
    }

its still dyin

#

il just comment out if statement and see what happens at this point

ivory bobcat
#

Maybe it's hitting itself?

delicate notch
#

I didnt add a damagedealer script to player

ivory bobcat
#

It would destroy itself if so if damage isn't null

#

Log who hit what

delicate notch
#

Obstical hitting my player

ivory bobcat
#

Is that what the log shows?

delicate notch
#

Yep

#

WHAT

#

its getting destroyed wtihout my code still

#

nani

ivory bobcat
#
Debug.Log($"{name} was hit by {collision.name}", this);```
#

Did you save? Are there errors in the console prior to running the application?

delicate notch
#

No errors

#

Is there a setting in rigid body taht would destroy an object?

ivory bobcat
#

Maybe you've got something else destroying stuff in the scene

delicate notch
#

maybe from here?

ivory bobcat
#

Rigid body does not destroy hierarchy objects..

delicate notch
ivory bobcat
#

You've got a script destroying stuff

delicate notch
#

il try to find it ig

#

WEll

#

I found the issue

#

having mass lower than 1 was the issue

#

what a waste of like 3hrs omg

nimble scaffold
#

And also tell me how to make my fps game multiplayer and 10 max member each room capacity using photon

frosty hound
#

Nobody is going to tell you how to do that.

nimble scaffold
#

Why sire

#

I'm a newbie

frosty hound
#

Nobody has the time?

#

So find a tutorial if you think making something as complicated as multiplayer is a feasible scope for you.

nimble scaffold
#

Okay sir👍👍👍👍

humble lantern
#

Heya, I'm working on an inventory system where you can toggle (Activate/Deactive the game object of) the inventory menu. Because of this I made a Method "ShowInventory" that runs after I Activate the Inventory.
For each slot I want to insert the corresponding item from GameObject array "items", which is done by a SetItem method taking a GameObject in Script "InventorySlot" assigned to each slot.
I'm getting a NullReferenceException telling me that the Object reference is not set to an instance of an object at line 69, and have no idea what causes it :/

humble lantern
#

which component? Inventory(current script) is on an object called "UI" which has a child "Inventory" which the Slots are children of. InventorySlot is on the mentioned Slots

ivory bobcat
#
Debug.Log($"Found: {searchedSlot}", searchedSlot);```
#

Place that line before the error line

humble lantern
ivory bobcat
#

Select the log and see which object is highlighted

humble lantern
#

omg it was the other child of UI

#

thank you, that was a simple error

topaz mortar
humble lantern
topaz mortar
#
            var values = JsonConvert.DeserializeObject<Dictionary<int, object>>(result);

            // For debugging
            foreach (KeyValuePair<int, object> pair in values)
            {
                Debug.Log(pair.Key + ": " + pair.Value);
            }```
How would I loop through this next part?
ivory bobcat
#

What exactly are you wanting to do?

topaz mortar
#

get to the individual key/values

ivory bobcat
#

Well, you've looped through and printed everything.

queen adder
#

well hello guys I need some help with my car system

topaz mortar
ivory bobcat
#

It's a dictionary and you've printed the key value pair

queen adder
#
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class Car_Controller : MonoBehaviour
{
    public float steeringAngle, motorPower, powerToApply;
    public WheelCollider[] wheelcolliders;
    public Transform[] wheelObjects;
    public Transform centerofMass;
    public int gear, maxGear;
    Rigidbody rb;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        CalculateMotorPower();
        ApplyToWheels();
    }

    private void FixedUpdate()
    {
        //rb.centerOfMass = centerofMass.position;
    }

    void CalculateMotorPower()
    {
        powerToApply = Input.GetAxisRaw("Vertical") * motorPower;
    }

    void ApplyToWheels()
    {
        for(int i = 0; i < 2; i++)
        {
            wheelcolliders[i].steerAngle = Input.GetAxisRaw("Horizontal") * steeringAngle;
        }
        for (int i = 0; i < wheelcolliders.Length; i++)
        {
            wheelcolliders[i].motorTorque = -powerToApply;
        }
    }


}

how can I apply the rotation of the wheel colliders to my all wheel meshs?

ivory bobcat
#

Dictionary is a c# collection

gaunt ice
#
var values = JsonConvert.DeserializeObject<Dictionary<int, object>>(result);
foreach (KeyValuePair<int, object> pair in values){
    Debug.Log(pair.Key + ": " + pair.Value);
}
```do you know what is the type of "values"
topaz mortar
#

it's a nested dictionary
the first one is <int, object> wich has 1, dictionary<string, object> and 2, dictionary<string, object> which is what you see in the screenshot
I need to loop through the inner dictionary, but can't find a way that works

ivory bobcat
#

So the element found in the dictionary is a dictionary.

topaz mortar
ivory bobcat
#

You'd use the public members provided by dictionary to access it's data

topaz mortar
short hazel
#

Why not use a Dictionary<int, Dictionary<int, object>>?

gaunt ice
#

cast the object to string

short hazel
#

Or use a custom class for your JSON representation, like how it's meant to be used

topaz mortar
gaunt ice
#

yes just deserialize the result as dictionary<int, your class>

short hazel
#

What do you want to do in the first place?

topaz mortar
topaz mortar
short hazel
#

If you get a JSON payload from some API, then you should have a class that conforms to the structure of the JSON payload

gaunt ice
#

json is a transfer format of class fields

#

as key-values pair

short hazel
#
[
  {
    "name": "Sample Sword",
    "damage": 42
  },
  {
    "name": "Wooden stick",
    "damage": 1
  }
]

Given this payload, this could be deserialized to a List<Item>, where Item is:

class Item
{
    public string Name { get; set; }
    public int Damage { get; set; }
}
topaz mortar
topaz mortar
gaunt ice
#

no, you should create the class in c# side as spr2 said instaed of just cast it to string and generate other dictionary<string,object>

tawdry rock
#

I want to save a GameObject visibility ( SetActive(true/false) ). What is the simples solution for it? Playerprefs.SetBool is not existing.... i read a workaround to make a SetInt for the bool 1 or 0 and do a if statment if that int is 0 then false, 1 return true. But i wonder if there is another easier method for this.

short hazel
#

The library will take care of creating the class instances for you

ivory bobcat
topaz mortar
short hazel
#

I don't know how your JSON looks, so hard to say. The structure of your C# classes depends on the structure of the JSON you receive from the server

gaunt ice
#

just deserialize the string as your class instance, change the generic parameter

ivory bobcat
#

I believe they're suggesting that you wrap up the collections and other such data in classes to better maintain not having to convert stuff.

topaz mortar
#

yeah it sounds nice, but also complicated

#

my brain can't handle it atm lol

gaunt ice
#

i think the json format (ie what are the values to return) returned by your api is defined by yourself?
then create the class in your c# script

short hazel
#

I can see a part of the payload here, so you'd need a Dictionary<int, Item>, where Item is a class that has the properties listed in the screenshot there

topaz mortar
#

I think I'll just stick with the bad way of doing it for now, but I'll keep it in mind if I ever wanna refactor this

#

pretty sure it won't work with my current Item class, since that does some other stuff too and has more values than the json has

gaunt ice
#

eg your api return an object which is

let name:string;
let numbers:Array<number>;
```then create a c# class to receive the json response
```cs
public class{
  string name;
  List<double> numbers;
}
short hazel
#

You'll have to convert all the fields public int Sample; to properties public int Sample { get; set; }, or configure Newtonsoft to populate the fields instead

forest locust
#

Im following this tutorial to make my own animated character: https://www.youtube.com/watch?v=cEqjkubspGo
but the code they used was fine, however when I import it- its completely broken to the point it doesn't know what unity even is.
37 errors of it now knowing what anything means.

In this Unity tutorial, I teach you guys how to make a basic third person character controller in Unity using the C# programming language. This character controller allows you to jog (forward and back), sprint, and rotate around for basic player movement. I also show a few easy camera methods as well.

#Unity #Unity3D

For more Unity tutorials o...

▶ Play video
gaunt ice
#

the first using SXXXX causes the parser fails

forest locust
quick ruin
#

this doesnt work, how else could I make the player face forward with the camera

gaunt ice
#

remove the using Systusing

#

not valid c# syntax

short hazel
forest locust
short hazel
#

!vs

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)

willow breach
#

Hey I'm trying to create an enemy that leaps forward if its close to the player, it mostly works but if I go towards the enemy while it close to me I get a bug that cause him to go to the other direction forever
https://gdl.space/cizohasini.cs
i used the logic from a tutorial but i think it's problematic

vital spade
#

Hi there I'm having an issue where the first part of this code works, "currently on trigger" side but the "enemy took damage" does not display and instead "this is not an enemy" is displayed in the console. the colliding object other is tagged as enemy, can't figure out what could be the problem

private void OnTriggerEnter2D(Collider2D other)
    {
        Debug.Log("currently on trigger");


        if (other.CompareTag("Enemy"))
        {
            Debug.Log("enemy took damage");

            enemyShooting enemy = other.GetComponent<enemyShooting>();
            if (enemy != null)
            {
                enemy.EnemyTakeDamage(2); // Reduce enemy health by 2
            }
        }
        else { Debug.Log("this is not an enemy"); }
    }
willow breach
willow breach
magic pagoda
#

I have this bit of code that I use to control waves of enemies, and spawn a new wave from a set of waves when all the enemies in said wave are defeated.

...however, when a new wave is supposed to trigger, Unity just.. freezes. Stops working. Could anyone help, please?

using UnityEngine;

public class arenaList : MonoBehaviour
{
    public List<GameObject> waveList;
    public List<GameObject> enemiesLeft;
    private Rigidbody2D rb2D;
    void Start()
    {
        rb2D = gameObject.GetComponent<Rigidbody2D>();
    }

    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Enemy")
            {
                enemiesLeft.Add(collision.gameObject);
            }
    }

    void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Enemy")
            {
                enemiesLeft.Remove(collision.gameObject);
            }
    }

    void Update()
    {
        if (enemiesLeft.Count == 0)
        {
        for (int i = 0; i < waveList.Count; i++)
        {
            i = enemiesLeft.Count;

            waveList[i].SetActive(true);
        }
        }
    }
}
willow breach
vital spade
magic pagoda
willow breach
willow breach
vital spade
ivory bobcat
magic pagoda
#

if the units didnt spawn I couldve looked at the errors, unfortunately I can not..

ivory bobcat
#

That means there's an infinite loop (recursion or whatnot)

magic pagoda
#

I guessed that couldve been the case-

willow breach
#

try to print 'waveList.Count'

ivory bobcat
#

Pretty certain the script provided isn't the issue

willow breach
#

i suspect it might loop to infinity

magic pagoda
ivory bobcat
#

Show us the units

willow breach
#

do it before the loop

magic pagoda
#

alright give me a second.

ivory bobcat
#

You're simply setting them active so I'm certain something else is managing their placement

magic pagoda
#

hmm.. lemme see.

#

I set this up because some other scripts couldnt do the wave system frequantly. I am pretty sure I cleared them out but let me re-check just in case.

ivory bobcat
#

Why set i equal to count (0)?

magic pagoda
ivory bobcat
#
i = 0;//infinite```
magic pagoda
#

I found one of my old level managers... lemme delete that and give it another try

#

...and another one

ivory bobcat
magic pagoda
#

yeah enemyCount constantly changes

ivory bobcat
#

Where?

magic pagoda
#

wait I meant enemiesLeft

#

enemiesLeft constantly changes

#

anyhow

ivory bobcat
#

Where in the loop?

magic pagoda
#

OH

ivory bobcat
#

It's the problem

magic pagoda
#

OH FU-

#

okay yup I saw the issue.

#

oh my god Im an idiot..

#

I used i to for both the wave count and the enemy count-

#

why did I have that line in there?!

willow breach
#

you will get to the loop only if enemiesLeft.Count == 0 so you alwaty set i to 0
and 0 is always smaller than waveList.Count (probably not 0)
you will get stuck in a loop

ivory bobcat
#

Probably to prevent additional spawning next frame

#

I'm guessing that's a list.

magic pagoda
#

the process now is

  • wave 1 is already spawned when scene loads

  • once wave one is defeated aka no enemies are left in the list, a new wave spawns and those enemies are on the list

  • continue until level clear

ivory bobcat
#

You'd probably want to populate the list with the activated objects.

#

As is, every unit will come out immediately

magic pagoda
#

okay so a lot of things broke but at least unity works now thanks y'all

vital spade
#

alright having another issue where the game is not entering "OnCollisionEnter2D(Collision2D other)", both objects have boxcolliders2d, and have rigidbody2d, one of the box colliders is set to trigger, the other one is not. This script is on the collider which has the trigger.

gaunt ice
#

collided with triggered collider will not fire oncollisionXXXXX

wintry quarry
vital spade
#

changed it, neither of the colliders are triggers, still not entering collision

wintry quarry
amber spruce
#

so you know how most games have like attack animations where if you have a combo it swaps for the next attack animation or whatever

#

so its not just the same animation over and over

#

how would i do that

vital spade
wintry quarry
amber spruce
#

does that allow me to say like if this animation is called again within like half a second of another it does the next one

nimble scaffold
#

Is visual scripting easy?

nimble scaffold
#

How to get ultra high graphics in unity?

nimble scaffold
rich adder
#

doubt anyone here uses visual scripting

nimble scaffold
#

Okay sir

#

How to get ultra high hd graphics in unity? Like unreal

willow breach
#

Hey I'm trying to create an enemy that leaps forward if its close to the player, it mostly works but if I go towards the enemy while it close to me I get a bug that cause him to go to the other direction forever
https://gdl.space/cizohasini.cs
I used the logic from a tutorial but i think it's problematic

is there a chane the is any issue with this method?
transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);

rich adder
amber spruce
magic pagoda
rich adder
magic pagoda
#

done

rich adder
#

Don’t post AI answers

#

Against rules

willow breach
#

oh... why?

cosmic quail
#

cuz AI is often wrong

willow breach
#

this is basic logic problem
it's very good at those

magic pagoda
#

yyup it was wrong lol.

willow breach
#

you should be more spesific and with 2-3 answers youll get it haha

rich adder
#

just dont

magic pagoda
#

also yeah dont.

rich adder
magic pagoda
#

AI tries to basically guess how your code works

#

I hate open AI anyway lol.

willow breach
#

Not really guessing, it doesn’t understand anything, it can just calculate the next word to fill in its answer and with enough context it can generate an answer, when the problem us logistic it usually can predict the error

#

But you do you haha

magic pagoda
#

its like asking someone who doesnt know C# to fix C# code

#

since its a chat algorithm and not a Code algorithm trained on C#

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

[CreateAssetMenu(menuName ="Attacks/Normal Attack")]
public class AttackSO : ScriptableObject
{
   public AnimatorOverrideController animatorOV;
    public float attackDamage;
}

i cant create the scriptable object in unity like it doesnt show up any clues

rare basin
#

Any compile errors?

amber spruce
#

nope

short hazel
#

Is the file name the same as the class name?

amber spruce
#

yeah

short hazel
#

Drag the file to another folder and back, in Unity

#

This will force a reimport

rare basin
#

Could you try to recompile

#

Or maybe add fileName? Idk if that's needed tho

amber spruce
short hazel
rare basin
#

Like spr said

amber spruce
#

so i think i know the problem unity keeps making me restart it to add a new script

#

yep works now

willow breach
amber spruce
#

really weird how i gotta relaunch unity everytime i make a new script

rare basin
#

That's weird

#

Try to delete your library folder maybe

magic pagoda
short hazel
vital spade
#

so I'm now having another issue, I've finally managed to set up a working trigger system using OnTriggerStay2D instead of on collision which works great for the most part. My intented purpose is that when the sword collides with an enemy and a mouse button gets pressed, enemy takes damage, however since enemies are shooting projectiles and they spawn from the center of an enemy at the player and towards the sword, the projectiles are triggering the OnTriggerStay and it takes multiple clicks to kill an enemy because the ontriggerstay is focused on a projectile collider instead of the enemy collider. Is there a way I could fix this?

short hazel
#

Infinite loop successfully created!

magic pagoda
#

wait shit I replied to the wrong thing

#

that one is already fixed

magic pagoda
#

apologies-

rich adder
short hazel
#

EnemiesLeft is never updated

fringe plover
#

!code

eternal falconBOT
magic pagoda
short hazel
#

After the loop

#

It'll always be zero at some point, so it'll activate the wave continuously

magic pagoda
#

its supposed to update when a new wave spawns because there are new enemies in that

short hazel
#

Make sure OnTriggerEnter2D runs when your objects are enabled

magic pagoda
#

isnt it meant to run ever frame?

short hazel
#

Only when a collider enters the trigger

magic pagoda
#

yeah it does run

short hazel
#

As many times as there are enemies under the waveList[i] game object?

magic pagoda
#

mhm

#

the new enemies spawned appear in the list

#

maybe the new waves spawn before the list can update?

short hazel
#

Okay, it might be due to the fact that Update and OnTriggerEnter run at a different rate yes

#

Update runs each frame, varying, while physics messages try to run at 50 times per second (by default), fixed

magic pagoda
#

so.. is there any way I can check that every frame?

short hazel
#

If I were you I'd revamp the whole thing to use events instead

rich adder
#

and I'd check only when enemy is added/removed (when list is modified)

short hazel
#

Or check the list frequently to see if all its elements are destroyed

magic pagoda
#

I could put the for loop under ontriggerexit...

#

brb, I have to go for a sec, Ill try that afterwards.

ebon fox
#

hello.
im trying to set my audiosource to a value that changes over distance but having a problem with the maxdistance value. if its 1 it works perfectly fine but every other value breaks it. i dont know why. appreciate any help

using UnityEngine;

public class HorrorLightSound : MonoBehaviour
{
    public float maxLightSoundDistance;
    public AudioSource lightSound;
    public LayerMask mask;

    private void Update()
    {
        Collider[] hitColliders = Physics.OverlapSphere(transform.position, maxLightSoundDistance, mask);
        foreach (var hitCollider in hitColliders)
        {
            var distance = Vector3.Distance(transform.position, hitCollider.transform.position);

            // check if la playur is in distancey wancy
            distance = Mathf.Clamp(distance / maxLightSoundDistance, 0f, maxLightSoundDistance);

            // Value = now between 0 and 1 :cool:
            var normalizedDistance = 1f - (distance / maxLightSoundDistance);

            // volume is el normalized, now we apply it
            lightSound.volume = normalizedDistance;
        }
    }
}```
short hazel
#

Audio Sources already expose settings for volume-over-distance parameters

#

You do not need to do this in the code

magic pagoda
ebon fox
short hazel
#

It is the option lol

ebon fox
#

but arent audiosources expensive for the gpu?

#

its gonna be for the quest2 and 3 so it should be as optimized as possible

short hazel
#

Audio is not graphics

ebon fox
#

i meant cpu mb

short hazel
#
  1. Make it work
  2. Make it pretty
  3. Make it fast
ebon fox
#

well how do i make it work

short hazel
#

By tweaking the audio source's settings in the Inspector

ebon fox
#

but isnt fixing that script way easier and better then putting a audiosource on every single light (around 500)

short hazel
#

Tbh one OverlapSphere() called 90 times a second (that's the ideal framerate for VR, if I remember correctly) on 500 objects is way more expensive than audio sources

ebon fox
amber spruce
#

how do i get if the current animation has ended

short hazel
#

If the light object is a prefab, add the audio source on the prefab and it'll be reflected on all instances

ebon fox
short hazel
#

Yeah...

#

Filter the Hierarchy with the search bar, and select them all, you should be able to add the sources all at once from the Inspector

ebon fox
#

alright

#

i just dont get why fixing that script isnt easier

short hazel
#

Because you're reinventing the wheel for something that is already way more flexible

#

Audio Source volume over distance supports curves for the volume falloff

viral hemlock
#

How can I add forces to a object?

short hazel
#

And more stuff

ebon fox
viral hemlock
#

thanks

minor roost
#

i have images but how do i make it better resoultuion as its 16x16 rn

rich adder
minor roost
#

lol

magic pagoda
nimble scaffold
#
using UnityEngine;

public class Gun : MonoBehaviour
{
    public GameObject bulletPrefab;
    public Transform firePoint;
    public float bulletForce = 20f;

    void Update()
    {
        if (Input.GetButtonDown("Fire1")) 
        {
            Shoot();
        }
    }

    void Shoot()
    {
        GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
        Rigidbody bulletRigidbody = bullet.GetComponent<Rigidbody>();

        if (bulletRigidbody != null)
        {
            bulletRigidbody.AddForce(firePoint.forward * bulletForce, ForceMode.Impulse);
        }
        
    }
}

is this code right?

rich adder
#

its on the left

rich adder
austere monolith
#

ah shucks i forgot

humble lantern
#

Not sure if this is a question for code, but I get "Cant add script" because the script class cant be found. I copied and pasted the name to be sure it wasnt a mistype, but the class and file name should be identical.
The only issure I can see is that I'm using "public class _ : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler", like alot at the same time

scenic cipher
scenic cipher
humble lantern
rich adder
humble lantern
#

you cant see the script name either, how will seeing the classname help when I already copy-pasted it because I wanted to make sure its not that

rich adder
polar acorn
eternal falconBOT
craggy bane
#

bruv

humble lantern
#

after restarting unity it gave me a popup for Safe Mode, I ignored it (thinking that its nothing game breaking) and now I have these two errors

rich adder
#

IndexOutOfRange is runtime error unless the editor is bugging out or have editor script

humble lantern
#

I hope this is enough for Scriptname and Classname

humble lantern
#

woah!

polar acorn
rich adder
#

you cant add new script if you have compile errorrs

polar acorn
#

Clear your console and see if any errors stick around

#

That gui one looks like an internal editor thing that probably won't affect anything

humble lantern
rich adder
#

make sure to configure your IDE as well if you haven't already

humble lantern
#

I tried once but I dont think I did it correctly

rich adder
#

!vscode

eternal falconBOT
#
Visual Studio Code guide

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

https://on.unity.com/vscode

rich adder
#

would highly recommend you don't code without this

#

otherwise VSCode is no more useful than a text editor

humble lantern
#

yeah I followed that, just updated the VSE package

rich adder
#

double check .NET sdk was installed, if not install it manually

nimble scaffold
#

pls help me by writing a code that when will the player go to a certain cube the health will decrease til 0 and the health ui also get updated

rich adder
#

what does "go to a certain cube" mean

nimble scaffold
#

i mean when player will touch the special cube players health will decrease by 10 each second

#

@rich adder

rich adder
#

or make a coroutine

nimble scaffold
#

ok sir

#
using UnityEngine;

public class CameraSwitch : MonoBehaviour
{
    public Camera mainCamera;
    public Camera secondaryCamera;

    void Start()
    {
        // Ensure only the main camera is active initially
        mainCamera.enabled = true;
        secondaryCamera.enabled = false;
    }

    void Update()
    {
        // Check for right mouse button press
        if (Input.GetMouseButtonDown(1)) // 1 represents the right mouse button
        {
            // Switch between cameras
            mainCamera.enabled = !mainCamera.enabled;
            secondaryCamera.enabled = !secondaryCamera.enabled;
        }
    }
}

code not working its saying that display 1 no camera found

rich adder
rich adder
scenic cipher
queen adder
#

How to make Cut scenes?

scenic cipher
rich adder
minor raptor
#

where is one supposed to start learning unity

scenic cipher
minor raptor
#

thats what i always do!!

#

but its not very efficient rlly

scenic cipher
#

I always prefer learning myself 🙂

minor raptor
#

same

#

and thats what im trying to do

open adder
#

help , i make a script of movement and the player doesn't collide with the walls

scenic cipher
#

Do what ever you prefer, you can't do something if you don't enjoy it

minor raptor
#

but i cant find a good resource

scenic cipher
eternal falconBOT
#

:teacher: Unity Learn ↗

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

open adder
open adder
scenic cipher
scenic cipher
eternal needle
# minor raptor but i cant find a good resource

Most of the beginner tutorials on youtube are just rapidly produced garbage. The best thing imo would be learning c# independently of unity, so you arent learning 2 things at once. None of the unity tutorials really teach you to code either. If you dont already have a good foundation then all you can do is copy paste while assuming you understand it

minor raptor
#

but idk very well stuff like lambda expressions and generics

#

so my plan was to learn a bit of c# while using unity

#

cuz the only thing i can do to practice c# is just to write console applications over and over

eternal needle
#

Best thing is just experimentation then, use tutorials to find out what exists (like functions you weren't aware of), or to find out what a decent structure is for implementing a certain game mechanic

scenic cipher
#

Honestly, you just need to know the bare minimum of C# or other languages to get started with Unity

eternal needle
#

If you dont have an exact goal in mind for what kind of game you want to make, then likely you wont be learning much c# in your current way.

scenic cipher
#

@minor raptor If you understand things like functions, variables, syntax, etc you should be fine to learn with Unity

craggy bane
#

anyone know how to instantiate a prefab after clicking a button at a custom position I can set?

scenic cipher
#

You will need to use Instantiate() in a script

eternal needle
fossil drum
#

Look at the overloads, and pick a version that has a position overwrite

fossil drum
#

Also, most of the docs have 1 or more examples for each function. You can just read up on this most of the time yourself.

novel shoal
#

how to make the rb.velocity of an object equal to the transform.translate() of another?

fossil drum
#

But you can just tryitandsee

craggy bane
#

yo how do I paste a code here

scenic cipher
eternal falconBOT
novel shoal
#

rb.velocity = (Vector3.left * speed);
transform.Translate(speed * Time.deltaTime * Vector3.left);

#

like this?

fossil drum
#

Sure

craggy bane
#

🤷‍♂️

fossil drum
craggy bane
#

Idk

craggy bane
sage mirage
#

Hey, guys! Do I have to save all my values in player prefs inside a single method or do I have to use PlayerPrefs.SetFloat etc on other methods and not all of them on a single one?

fossil drum
summer stump
craggy bane
#
using System.Collections.Generic;
using UnityEngine;

public class WavesLogic : MonoBehaviour {
public float gameTime = 0 ;
public float spawnDuration = 3;
public float deSpawnDuration = 3;

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



{
InvokeRepeating("Timer", 0,1);
InvokeRepeating("SpawnElements", 0, spawnDuration);
}

void Timer()
{
gameTime++;

if (gameTime == 60)
{
spawnDuration = 2; 
spawnDuration = 2;
}

if (gameTime == 120)
{
spawnDuration = 1; 
spawnDuration = 1;
}

}
void SpawnElements()
{


Invoke("DeSpawnElements", deSpawnDuration);
}

void DeSpawnElements()
{
// Destroy (Elements);
}


}
#

I have a quick question

fossil drum
craggy bane
#

If I go ahead and put an instantiate on this wave script

#

will I need to deal with the position pain again?

#

basically where do I put a instantiate script on this for 4 different objects

summer stump
wintry quarry
craggy bane
#

What I'm trying to say is do I make a seperate script for instantiate and put both of them in a gameobject?

wintry quarry
#

For what purpose?

sterile radish
#

!code

eternal falconBOT
scenic cipher
craggy bane
#

To spawn an object every 3 seconds and despawn it after 2 seconds after 60 seconds and spawn it for 1 and despawn for 1 after 120 seconds

sterile radish
craggy bane
#

Gotcha

scenic cipher
#

Not for the wave system

wintry quarry
craggy bane
sterile radish
craggy bane
#

I'm just tryna make these 4 trashes spawn but not all at the same time along with the wave system script I wrote

craggy bane
scenic cipher
#

Yes

wintry quarry
#

that's... part of it?

#

like 5% of it?

scenic cipher
#

But you need to make SpawnWave() an IEnumerator and actually code it

craggy bane
#

Yh

sterile radish
scenic cipher
sterile radish
rare basin
#
Vector2 direction = mousePos - transform.position;
direction.y = transform.position.y;
rare basin
scenic cipher
#

@sterile radish

Vector2 direction = new Vector2(mousePos.x - transform.position.x, transform.position.y);
rare basin
#

that wont work aswell

#

even edited wont work 😄

scenic cipher
#

Happy? lol

rare basin
#

lol

topaz mortar
craggy bane
#

How do I make an instantiated object despawn after a button click?...

scenic cipher
#

You could put all of the objects in a Parent object, then when the button is clicked, iterate through the child objects and destroy them. You could also store them in a list when they're instantiated, iterate the list and destroy them

polar acorn
craggy bane