#💻┃code-beginner

1 messages · Page 450 of 1

summer stump
#

In what way would a queue make sense for standard pooling

tardy needle
#

For a system that bullets will be fired continuously it makes sense a queue should be better but I found in a forum discussion that u shoudln't use them (don't know why), makes sense since the queue are better at removing and adding elements at the head and tail of the queue. When using a list I've made it so it iterates all the list and return the first "desactivated" object, this means that it could iterate through all the bullets that are active and return the first one desactivated, on the other side the queue would just return the first object.

#

Don't know unity has an object pool. I've made one following a tutorial https://learn.unity.com/tutorial/introduction-to-object-pooling#

Unity Learn

Object Pooling is a great way to optimize your projects and lower the burden that is placed on the CPU when having to rapidly create and destroy GameObjects. It is a good practice and design pattern to keep in mind to help relieve the processing power of the CPU to handle more important tasks and not become inundated by repetitive create and des...

summer stump
tardy needle
#

It would just return the head of the queue instead of iterating

summer stump
#

An array is incredibly performant

tardy needle
#

Why?

summer stump
#

Why would it?

tardy needle
#

Its returning the reference of the first object

#

Isnt that O(1)?

summer stump
#

Yes

tardy needle
#

It is very cost efficient?

summer stump
#

So is returning from an array

tardy needle
#

But the problem is finding that object

#

In a queue u dont need to find because its the first one

#

It may depend on the situation.

#

The one i described is re-using bullets

summer stump
tardy needle
#

Then a queue/stack sounds like what will work best?

summer stump
#

It would be ok sure
I wouldn't say best, no

tardy needle
#

Then why can an array be better

#

I was using a list that had 100 bullets but I figured out that when obtaining the bullet it iterated through the list untill it found a desactivated bullet. That "untill" doesn't happen in a queue, how come it isnt better?

summer stump
tardy needle
#

No, thats not the idea

#

Well I am doing it in the list

summer stump
#

Then what do you mean iterate until you find the deactivated object?

#

There is no iterating necessary

tardy needle
#

That might be better

#

Having a list of only desactivated objects

#

Althrough in the unity tutorial it seems it has both, activated and desactivated objects

summer stump
#

My suggestion was the ObjectPool collection btw.

But yeah, classic object pooling is two collections

tardy needle
#

So 2 collections for activated/desactivated each?

summer stump
#

Or potentially one for ONLY deactivated I have seen

tardy needle
#

Yea thats what i've described before, a queue that only contains desactivated ones

#

And those are better than lists since modifying lists costs more

#

Same starting point

mint remnant
#

If making you're own pool I'd think a stack for the pool, just push one when you get one returned tot he pool and pop one when a new one is requested

tardy needle
eternal needle
#

id only really go with a deactivated one if youre trying to apply some effect to every single one. but yea just use the objectpool class for the actual pool. no need to worry about stack/queue/list

tardy needle
#

There is an built in class?

mint remnant
#

yes

#

using UnityEngine.Pool;

summer stump
mint remnant
rich adder
#

its going into another app is it not?

#

application loses focus

#

nice

cold ruin
#

I struggle trying to classify "equipment item" to a certain "equipment slot" (example: I want to equip the "weapon item" exactly to "weapon slot" and nothing else beside the inventory itself). Can someone please help me?

Item

using UnityEngine.Tilemaps;

[CreateAssetMenu(menuName = "Scriptable Object/Item")]
public class Item : ScriptableObject
{
    [Header("Only Gameplay")]
    public ItemType itemType;
    public ActionType actionType;

    [Header("Only UI")]
    public bool stackable = true;

    [Header("Both UI")]
    public Sprite image;
    public enum ItemType
    {
        Weapon,
        Bracelet,
        Helmet,
        Necklace,
        Consumable
    }

    public enum ActionType
    {
        Equip,
        Drink
    }
}

EquipmentSlot

public class EquipmentSlot : MonoBehaviour, IDropHandler
{
    public void OnDrop(PointerEventData eventData)
    {
        if (transform.childCount == 0)
        {
            GameObject dropped = eventData.pointerDrag;
            DraggableItem draggableItem = dropped.GetComponent<DraggableItem>();
            draggableItem.parentAfterDrag = transform;
        }
    }
}
surreal turret
#

Should I make maps for unity in blender, or should I just make assets in blender and build the level in unity?

solemn fractal
#

hey guys.. I am trying to do a simple task here.. I have a 2d object in my scene with the script attached to it with the Class name Enemy. In my player script I try do this as you can see in the SS and it seems like it is not recognizing it.. I did the same steps for my PlayerBullet and worked. This one he cant find it.. any ideas? Thank you.

frosty hound
#

Did you actually save your Enemy script?

solemn fractal
#

I just created the script enemy without opening,. and this happened. After that I opened the Enemy script that I didnt code yet anything inside.. hit save just to be sure.. but still nothing.. if that is the prob I will try to write some code there or create a variable just to save it again and test

frosty hound
#

Do you have compiler errors in your console?

solemn fractal
#

No

#

Even tho after creating a variable inside enemy and saving.. still same issue.. hm. No errors anywhere.. I will close and open unity again

#

After closing and opening unity fixed the issue thank you

frosty hound
#

You may want to check that your IDE is configured, for whatever reason it didn't compile your new script

solemn fractal
#

Yeah.. I will check that again.. thank you

mint remnant
#

THe error typically ends up just ooutside of where you cropped the image

solemn fractal
#

Another question.. If i want my player that is a static player in the middle of the screen. To shoot an enemy every time the enemy is in a certain dist from the player.. what is the best approach? To use in Start method and use something like FindObject or use a serialized field and drag the enemy prefab from project assets to the player script serialized field? or what method u recommend?

#

The best approach to find the enemy.. i mean

mint remnant
#

loop thru a list of the enemies, comparing their distance to the player

cinder night
#

can someone please tell me how to execute C# code from visual scripting?
i have this code inside, but i dont undersntad how to use it

using UnityEngine;

public class Utilities : MonoBehaviour
{
public void PrintMessage(string message)
{
Debug.Log(message);
}

public int AddNumbers(int a, int b)
{
    return a + b;
}

}

frosty hound
#

Stick a trigger collider on your player and check when something enters it

summer stump
balmy steeple
#

is it possible to copy a component and add it to another object

solemn fractal
#

Good ideas.. thank you.. but I mean when it detects that something entered that collider.. I coulkd use other.comparetag"enemy" and with that information I can get the enemy direction to shoot at it I imagine yes correct?

mint remnant
balmy steeple
balmy steeple
surreal turret
#

Its a parkour/mobement game

balmy steeple
#

or the assets route depending on how complex the game is

#

probably doing it the premade assets way if its similar to karlson, but for something like ghost runners visual complexity its probably layout first

balmy steeple
eternal needle
#

if you need to copy everything related to this, at runtime, and may need private variables then itd be better if classes that need this functionality handle it themselves

crisp token
#

Is the Activator class responsible for all instantiations?

#

idk how ive never heard about it before, I always thought the Object class did that

eternal needle
crisp token
eternal needle
#

What's the use case? Reflection isnt like advanced imo but you realllllllly shouldnt need it in your own project.

crisp token
eternal needle
#

I'm guessing you took some AI answer which used it. Because I really fail to see how you would come to reflection here

crisp token
#

like how can I go: take the type of an object --> create a new instance of that type

eternal needle
crisp token
eternal needle
crisp token
eternal needle
#

!code

eternal falconBOT
eternal needle
#

Also I guess explain more of what you're actually trying to do. Because I dont fully understand what "these new instances are not copies" is supposed to mean or why they're created in the first place

crisp token
# eternal needle Also I guess explain more of what you're actually trying to do. Because I dont f...

yeah ik its a bit weird but I have two classes. Movement State Manager and Movement Applicator. I tried to keep Movement State Manager solely responsible for reading input and outputting a state. These objects are already made because each MovementAbility object contains its own information related to what states it can and cannot override, so its neccessary to create instances of them in Movement State Manager to determine the state. However, I dont want to properly instantiate them until the Movement Applicator Class, which is why I need to make new instances here

#

Essentailly the objects in movementAbilitiesToInstantiate are references that only exist to access information

eternal needle
#

this looks more like a problem that doesnt need to exist, but i dont know what to suggest to you because the whole scenario isnt easy to imagine

crisp token
#

it may not need to exist but i dont think its a big problem'

#

i could just use if statements

#

thanks for your time

eternal needle
crisp token
eternal needle
#

this isnt even related to state machines, you are creating an object, passing it to something else, then trying to get the type and use reflection to create it.

#

this is just backwards

crisp token
#

It is backwards to have to create an object to access what could be static class information but the reason i did that was because it keeps code neater

eternal needle
#

and this is not neater by any means

crisp token
#

yeah they are created but when they are constructed imagine only half of the paramters have meaningful values

crisp token
eternal needle
#

then why dont you just populate the values you want...

#

you're passing the instance of the object, just use that instance

crisp token
#

I could , but i'd prefer to keep it in the constructor instead of having separate methods

raw token
#

Separate methods are miles cleaner than instantiating through reflection 👀

crisp token
#

forget about reflection lol

eternal needle
#

ok well have it your way then, but when you make that 2nd constructor id love to see how different that looks than a 2nd method

eternal needle
#

not in the way you're describing, which honestly has been so vague ive had to play 20 questions where the problem changes everytime

crisp token
#

obviously describing an entire system is difficult

eternal needle
#

yes and the answer was you shouldnt be using reflection. Of course id want to provide an alternative instead of just saying that and leaving

crisp token
eternal needle
#

my answer is still the same, for what i understand the problem to be.
just create a new method so you can assign values to the existing object instead of whatever youre trying to do here.
Or
dont create the instances from a place where a place where they shouldnt be created with half the values needed to function

crisp token
#

its a good idea

sweet sierra
#

Your tip saved me! 🫡 Quite literally...

#

My character was spawning after the ball so animations weren't playing properly. Then your advice came to my mind so yeah, implemented that. Thank you! ⭐

rocky canyon
river pecan
#

I'm trying to save a list and I've found out that Unity's JsonUtility doesn't support arrays as a root element. Everything online says to use use a serializable wrapper class that holds a list but I don't know how to reference it. I don't know how I should be calling it in my save function.

    public static void SaveInventory(Inventory inventory)
    {
        string path = Path.Combine(Application.persistentDataPath, "inventory.json");
        // Add int to SerializableList
        File.WriteAllText(path, JsonUtility.ToJson(SerializableList.list, true));
    }
rich adder
river pecan
#

I did this and it's giving a null reference exception so

#

I can't be referencing it correctly

#
[System.Serializable]
public class SerializableList
{
    public List<int> list;
}
mint remnant
#

THat's jsut declaring a List, not initializing it

river pecan
#

Oh okay

#

I mean that's what I've seen in every example online

#

I haven't found an example of calling the list when saving

mint remnant
#

somewhere you have to say List = new List<int()

rich adder
#

unless its in the inspector its not auto initialized

raw token
river pecan
rich adder
river pecan
rich adder
#

are you just testing

raw token
rich adder
#

also these names are wild confusing

river pecan
#

I'm just testing out lists before actually trying to implement it

rich adder
#
SerializableList myList = new SerializableList();
        myList.list = new List<int>();
        for (int i = 0; i < 10; i++) 
        {
            myList.list.Add(Random.Range(0,101))
        }```
idk
river pecan
#

I mean I'm not getting any error but it's still just

#

Outputting {} in the file

rich adder
#

what the problem and why are you saving ints?

raw token
#

what does your code look like now?

river pecan
rich adder
#

does your list have anything

river pecan
# raw token what does your code look like now?
        string path = Path.Combine(Application.persistentDataPath, "inventory.json");
        SerializableList serializableListObject = new SerializableList();
        serializableListObject.list = new List<int>();
        serializableListObject.list.Add(1);
        serializableListObject.list.Add(4);
        serializableListObject.list.Add(9);
        File.WriteAllText(path, JsonUtility.ToJson(serializableListObject.list, true));
        Debug.Log(serializableListObject.list.Count);
rich adder
#

you need to ToJson the serializableListObject

river pecan
#

That makes sense

rich adder
#

thats the point of that wrapper

river pecan
#

I've never experimented with this before and there's no examples of using wrappers that I could find

#

All I could find online is that I should be using wrappers

rich adder
#

yeah its confusing at first, you'll get the hang of it

#

wait till you deal with properties and dictionaries 😄

#

more wrappers

#

actually props are fine iirc if you use backing field n Field: or is it auto-properties ?
can't recall, i just lazy out with Json.net

raw token
#

I'm... not sure. Lazying out is the way to go 👀

mint remnant
#

Haven't messed with Json in unity yet, but is NewtonSoft's a better or equal one to use?

river pecan
#

Gone

rich adder
#

also dictionary support without wrapper struct / class

#

esp if you pull items from web its good to have JObject and other cool stuff like that

raw token
rich adder
#

although in most cases you're fine with JsonUtility in unity tbh.
whatever unity can serialize you can use

woven crater
#

is this store an instance of Iattack inside SO?

#

this return null

languid spire
woven crater
#

the null happen after the debug

languid spire
#

But your debug tells you nothing. You need to check each element of the next statement

woven crater
#

ah i see. the character is having a diffferent gunSO, thank

opal zealot
#
                    {
                        Debug.Log("Mega Click Detected!");
                        interactObj.Interact();
                        // Log the detection of a double click
                        Debug.Log("Mega Click Detected!");
                        // Add your double click logic here
                        
                    }else Debug.Log("none");
                }```

Is there a problem with the IInteractable or is it just me?
short hazel
#

There are logs in your code, are you getting them, and if yes which?

languid spire
#

Also post the code for IInteractable

opal zealot
#
    public void Interact();
}```
opal zealot
languid spire
short hazel
#

Please post the full class containing this code

opal zealot
#

Ok

short hazel
#

Ah, AI generated code

opal zealot
#

I didn't AI generate it though.

#

Someone did help me a bit with the setup, I just add onto it.

short hazel
#

It has an awful lot of comments for this to be true

opal zealot
#

Oh

#

Oh dear, is that bad?

languid spire
#

Not as such but, it is a dead giveaway that it is AI generated and so likely to be complete nonsense

opal zealot
#

Oh

#

Welp

#

Got stuck for a week trying to solve it on my own thinking I missed something.

short hazel
#

If it's not passing the condition where you raycast, then the raycast didn't detect anything. Make sure the object you're attempting to hit has a collider and is at the right position!

#

And that you're firing the ray in the right direction, too

opal zealot
#

Which I made sure, the NPC I'm clicking on has both the collider and is in the right position.

robust dew
#

how can i make 2 enemies don't receive damage from other's bullet but both damaged by player's bullet ? Any idea without using Layers ?

languid spire
opal zealot
languid spire
short hazel
opal zealot
opal zealot
short hazel
#

Overrides button at the top, select Apply All

opal zealot
#

Done, overrided the OG prefab.

#

Is it normal for the NPC + Player to float via Capsule collider?

languid spire
# opal zealot

Colliders have no influence on position, only Rigidbody and CharacterController have that

naive pawn
#

wouldn't a rigidbody on a collider set too low affect the position

#

make sure your collider aligns well with your model

opal zealot
#

I planed them as 2D sprite assets like how Ragnarok Online does it.

#

Do we have a Cylinder collider?

#

Yeah, it really is my collider problem.

#

Somehow the capsule colliders are making them float.

opal zealot
#

Ok, let me try testing the Rigidbody and CC.

languid spire
#

your capsule collider is a trigger so has nothing to do with anything except being touched

opal zealot
#

Ok

#

Good news, the player doesn't float anymore but the NPCs still do:

#

Yeah, its a problem with positioning.

languid spire
#

The NPC doesn't have a Rigidbody or CC

opal zealot
#

Yeah, I noticed. I just need to keep all Y-axis to 0

eternal needle
opal zealot
#

Now back to the interactive.

naive pawn
eternal needle
silver girder
#

i have a script and i cant add camera bobbling when walking and running and a small shake when jump but i have tried lerping the camera but didnt work so i deleted it please help me in it

naive pawn
jolly temple
#

guys, i have a question. How do I understand C# Programming Language?

#

because it's hard to memorize the codes or functions

languid spire
#

Memorizing and understanding are not the same thing, learn programming concepts and they can be applied to any language. As for memorizing, there is very little you need to memorize, the docs are always online for you to refer to

ivory bobcat
#

Learn and use the concepts. Syntax looks intimidating but we've got Intellisense to auto complete/suggest those. You've simply got to be able to understand that certain tools (not their specific syntax) are available: conditional branches, loops and whatnot.

burnt vapor
daring quiver
#

Hello I need help with my game design, as everything breaks when I create a build for an android game on my macos. Everything is out of position and not set in the positions I placed them. Can someone please help me with this?

little seal
#

i have these 2 player cubes with an object attatched to them that i turn on and off to attack, it works for the most parts but sometimes when they are this close together the collisions dont register, does anyone know why? (green bar is the attack)
only once one of them moves again (even if its a jump and they land on the same spot) they can be attacked a second time

#

this is my script for checking if the player gets damaged

#
using System.Collections;
using System.Collections.Generic;
using UnityEditor.SearchService;
using UnityEngine;
using UnityEngine.SceneManagement;

public class damagableThing : MonoBehaviour
{
    [SerializeField]
    int maxHealth;
    int health;
    // Start is called before the first frame update
    void Start()    
    {
        health = maxHealth;
    }

    // Update is called once per frame
    void Update()
    {
        print(health);
        if (health <= 0)
        {
            health = maxHealth;
            print("died!");
            gameObject.transform.position = new Vector3(0, 10, 0);
            gameObject.GetComponent<Rigidbody2D>().velocity = Vector3.zero;
        }
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        damageSource damageScript = collision.gameObject.GetComponent<damageSource>();
        if (damageScript != null)
        {
            health -= 1;
        }
    }
}
ivory bobcat
little seal
little seal
# ivory bobcat You may need to show your implementation for >>> turn on and off to attack
    IEnumerator enableAttack()
    {
        attacking = true;
        gameObject.transform.GetChild(0).gameObject.SetActive(true);
        yield return new WaitForSeconds(0.2f);
        gameObject.transform.GetChild(0).gameObject.SetActive(false);
        yield return new WaitForSeconds(attackcooldown);
        attacking = false;
    }
    void FixedUpdate(){
        if (!gameObject.transform.GetChild(0).gameObject.active && Input.GetKey(KeyCode.E) && !attacking)
        {
            StartCoroutine(enableAttack());
        }
    }
ivory bobcat
little seal
#

alright, i thought id put it in fixed for consistency

#

do you have any idea about the hitting issue?

ivory bobcat
#

I'm not entirely certain with the information you've provided but I'm "assuming" that it's to do with you setting the object inactive before the trigger state completes. Thus it doesn't occur again on setting it active afterwards. Purely a guess though.

little seal
#

it only occurs after hitting the other player once already so that could be true

#

actually nvm

#

that might be it though

#

the person still enters the trigger even though the object is disabled?

#

any movement fixes it though

ivory bobcat
#

It hasn't ever exited so it cannot enter? UnityChanHuh

little seal
#

so if you stand in the trigger, then enable it it doesnt count as entering

#

maybe the first movement while inside causes the trigger, not actually just being there?

ivory bobcat
#
Try Trigger enter//Good
set object inactivate 
//Exit never occurs 
Try Trigger enter//Bad, hasn't exited so cannot enter again - it's in the "Stay" state?```
little seal
#

actually it seems more like this

#
object is inactive
go into trigger while inactive
set object active
trigger enter doesnt happen untill moving
ivory bobcat
#

Rather than guessing, use the exit message and see if it occurs between the two enters

#

Enter will not occur again if you haven't exited

#

If you want it to occur with Exit, use Stay

little seal
#

i might just make a list of all the things it hit, then use stay and then check the list if the person has been hit by the attack and if not, hit them

ivory bobcat
#

Disable the renderer and that script - faking an object being disabled. Problem solved.

fair sedge
#

Hey, have already someone used Kirurobo package (allowing windows transparency, grabbing etc)? I have some issues with it 😢

ivory bobcat
little seal
fair sedge
ivory bobcat
#

The person who made the asset or their dedicated server.

fair sedge
#

Yeah but he has not any discord server and his twitter messages are closed, thats why i wanted to reach someone that might have used its package before 😢 but no prob thanks anyway (if someone has used it before please reach out! OS_pepelove )

little seal
ivory bobcat
little seal
ivory bobcat
#

Stay should be checking every frame regardless of the enter/exit state

little seal
#

i dont know then, all i know is that it doesnt work

#

im holding e, the collider keeps popping up because of that, but im not getting any message from

private void OnTriggerStay2D(Collider2D collision)
{
    print("Staying");
}```
or any of my trigger methods for that matter
wintry quarry
ivory bobcat
little seal
fair sedge
#

Hey,
i'll detail an import problem that i encountered recently. My code tree is the following :

Assets
|___ Kirurobo
|       |___ Runtime
|               |___ Prefabs
|               |      |___ Controller.prefab
|               |
|               |___ Scripts
|                      |___ ControllerSc.cs             
|___ Scripts
        |___ MyScript.cs

I use a package to manage some things in my code. ControllerSc.cs is basically a big namespace Kirurobo{} and it is attached to Controller.prefab. This one is in my scene and works fine. However, ControllerSc.cs provides API with public functions that i would consider using for some tooling in my scene. But, when I try to get the script by doing this:

ControllerSc controllerScript = controllerPrefab.GetComponent<ControllerSc>();

It seems to not be able to resolve ControllerSc script.

Has any of you an idea of how to import properly a script from a package?

tidal kiln
#

is ControllerSc a component

slender nymph
languid spire
#

did you add a using for the namespace?

fair sedge
tidal kiln
#

if ControllerSc.cs is a filename with a bunch of classes there might not actually be a Monobehaviour named ControllerSc

fair sedge
fair sedge
languid spire
#

screenshot the top of the script

slender nymph
fair sedge
#

(i refactored names to make it simple but this is my controllerSc)

slender nymph
#

well i don't see a class named ControllerSc there

tidal kiln
#

GetComponent<ControllerSc> is gonna search for a class inheriting from Monobehaviour or a derivative attached to the gameobject

fair sedge
#

I named it controllerSc to make it simple, but its real name is UniWindowController. It has monobehaviour called by the same name

slender nymph
#

the comment also implies this isn't even ControllerSc.cs

fair sedge
languid spire
#

so not ConstrolerSC

slender nymph
#

again, that is not a class named ControllerSc. that is a class named UniWindowController

tidal kiln
#

whats the component thats attached to the gameobject

#

you have to use getcomponent on that

fair sedge
#

Yeah my bad guys, i named the files within my tree really quick to make it simple, but as we go deep into the files i have to clarify that controllerSc is a name i chose to replace UniWindowController.cs . The component attached to this prefab is UniWindowController (script)

slender nymph
#

you need to use the name of the actual type, not the name of the file

#

ControllerSc is just the file's name and has literally no bearing whatsoever on the code

fair sedge
#

so if my namespace is "kirurobo", i have to call it by kirurobo?

tidal kiln
#

no the class name

grand badger
#

Also, mono behaviour types NEED to reflect the file’s name 1:1

slender nymph
tidal kiln
#

the name of the component that inherits from monobehaviour

slender nymph
grand badger
#

Hm, ty til

slender nymph
fair sedge
#

I used using Kirurobo; at the top of my file (as the namespace in the file is), and in my script i cant manage to resolve it

grand badger
#

I’m on 2022.2 for a new project, does it still apply?

fair sedge
#

UIWindowController is my reference to the prefab

tidal kiln
#

its a method so you need ()

slender nymph
fair sedge
slender nymph
#

if you save it, does the error appear in the unity console as well or only in your IDE?

ivory bobcat
grand badger
slender nymph
#

incorrect, those new terms only apply to unity 6

slender nymph
#

that's not even remotely related to the line of code you are having trouble with

ivory bobcat
runic vortex
#

Hello I need help with this strange bug, i made a list but when i try to access the list from the same script i got a null reference error.

slender nymph
#

or rather, it isn't a compile error. it might still be related to that line for other reasons

slender nymph
languid spire
ivory bobcat
runic vortex
grand badger
fair sedge
#

This is when i print it with a Debug.Log()

slender nymph
grand badger
#

Nice

slender nymph
fair sedge
#

I'll still read asmdef page because it is interesting, thanks for the support guyz

tidal kiln
#

90% of the time i see someone having text editing issues its vscode lol

#

i like vscode but the trouble just isnt worth it for c#

slender nymph
fair sedge
tidal kiln
#

visual studio

#

rider is good too

grand badger
#

I’m not worried about hitting 1mil, but I don’t have time to read and agree to the terms atm :p

slender nymph
grand badger
lethal bolt
#

This dosent push the character forward but one direction

rocky canyon
#

Vector3.forward is the global forward.. (alwys one direction)

slender nymph
#

yes, that applies force along the world's Z axis. either use AddRelativeForce or use its transform.forward as the direction of force applied

#

also don't use deltaTime with forces

#

and why are you using an impulse force for regular movement? that should be ForceMode.Force and inside of FixedUpdate

ivory bobcat
# slender nymph eh, to be fair this issue they experienced is fairly common with visual studio a...

Tbf, I've tested the configuration process myself lately and it works for the most part (code completion for Unity types and whatnot) but the unity messages are completely missing with vsc (likely due to them not actually using inheritance but some other sort of binding/reflection for detecting usages of these magic methods). I've tried some add-ons to supplement this but am not too fond of the strange formatting with their auto completion.

lethal bolt
#

but Thanks!

slender nymph
languid spire
#

Absolutely, why would you use a jumped up text editor when you can use a fully fledged IDE for free?

slender nymph
#

beginners hear "it's lightweight!" and just latch onto that despite all of the extensions they are required to install making it more like visual studio in regards to performance

languid spire
ivory bobcat
languid spire
languid spire
gentle flint
#

I followed this tutorial: https://www.youtube.com/watch?v=sU5njx1jn8w&t=691s for Unity Ads Mediation and i couldn't install admob because it couldn't build and also adlovin because i don't have the app live but that's fine because i just wanted to test unity ads and ironsource but when i compile and i open the file in my phone the function onSdkInitializationCompletedEvent is never called, this is the code:

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

public class AdsManager : MonoBehaviour
{
#if UNITY_ANDROID
    string appKey = "1f41c9b05";
#else
    string appKey = "unexpected_platform";
#endif
    public TextMeshProUGUI totalCoinsTxt;
    private void Start()
    {
        print("Starting Debug");
        totalCoinsTxt.text = PlayerPrefs.GetInt("totalCoins").ToString();
        print(totalCoinsTxt.text);
        IronSource.Agent.validateIntegration();
        print("Validated");
        IronSource.Agent.init(appKey);
        print("Initialized "+appKey);
    }

    private void OnEnable()
    {
        print("OnEnable Run");
        IronSourceEvents.onSdkInitializationCompletedEvent += SdkInitialized;
        print("Sdk command run");
//Other stuff

    }

    void SdkInitialized()
    {
        print("Sdk in initialized!!");

    }
    void OnApplicationPause(bool isPaused)
    {
        IronSource.Agent.onApplicationPause(isPaused);
    }
//Everything else```

#unity #unitygamedevelopment #unityads #admob #applovin

"🎮 Master Unity Level Play Integration with AdMob, IronSource, AppLovin, and Unity Ads! In this tutorial, we'll guide you through a hybrid setup, combining waterfall and bidding strategies for maximum ad revenue. 🌊🏆 Whether you're a beginner or pro, follow along easily and supercharge yo...

▶ Play video
languid spire
gentle flint
languid spire
#

Use Android LogCat, that is what it is for

quasi hinge
#

hey guys, I'm trying to make a scoring system that sends the score in the console, but the score stays at 1, I'd be thankful if you help, thank you!

#

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

public class DetectCollisions : MonoBehaviour
{
private float playerScore = 0;

// Start is called before the first frame update
void Start()
{
    Debug.Log("Score = " + playerScore );
}

// Update is called once per frame
void Update()
{
    
}
//Destroy when Colliding
private void OnTriggerEnter(Collider other)
{
    Destroy(gameObject);
    Destroy(other.gameObject);
    playerScore += 1;
    Debug.Log("Score = " + playerScore);
}

}

eternal falconBOT
slender nymph
#

the issue is also that you are destroying the object that is storing the current score

quasi hinge
summer stump
#

That is how many people do it yes

rich adder
#

You need another script that wont destroy

languid spire
#

Also why is score float when you are only adding 1 ?

rich adder
#

and easily referenceable

slender nymph
# quasi hinge so i have to make a new empty object to store the scores?

not necessarily, you just can't destroy the instance that your score is stored on. because what is currently happening is each individual instance of this object has it's own separate playerScore variable. it starts at 0 for each one, then you increment it to 1, assign the text, then destroy this instance of the object

quasi hinge
west phoenix
#

!bug i didnt know where to write this but my unity wont fully download like it fully downloadet but it wont finish like it was like this for 6 houers.....

eternal falconBOT
#

🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.

📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!

💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.

For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting

languid spire
#

!install

eternal falconBOT
#
When Unity fails to install checklist
  • Make sure you have enough space including on C: drive.
  • Check that it's not being blocked by antivirus/security programs.
  • Look through the logs for a real reason why the setup fails they are pinned [here](#💻┃unity-talk message).

If you still have issues, perform a clean install in another location:

  • Install the Hub and Unity in a non-system drive or a clean new folder in the root of C: drive.
  • Failing that use the recovery Refresh option or reinstall OS entirely then repeat the previous step.
gentle flint
languid spire
#

use a paste site, I dont download files from discord

west phoenix
languid spire
rich adder
west phoenix
gentle flint
#

@languid spire "2024/08/05 17:12:06.704 17475 17513 Error IntegrationHelper Adapter - MISSING" This line seems scary idk

languid spire
rich adder
gentle flint
west phoenix
languid spire
rich adder
west phoenix
#

oh...

languid spire
#

Didn't even look

gentle flint
#

"2024/08/05 17:12:06.704 17475 17513 Info IntegrationHelper Adapter 8.2.0 - VERIFIED" i'm using ironsource to test and here i'm verified

#

aswell in Unity ads

slender nymph
# west phoenix oh...

didn't you specifically say you didn't find anything in the logs? why lie about it when you could instead ask how to find the logs if you don't know?

rich adder
west phoenix
languid spire
#

what a surprise, I don't help people who do that

slender nymph
rich adder
languid spire
gentle flint
#

alr thanks anyways

west phoenix
slender nymph
#

holy shit dude, do you just not bother reading any of the information provided to you?

west phoenix
#

you said logs in unity hub

slender nymph
#

i did not say "in" the unity hub. i said the unity hub logs. the location of which is provided in that convenient link in the embed you lied about following the instructions for

polar acorn
#

Where did anyone say they were "in" the hub

#

They are, in fact, in the location the bot originally mentioned they were

languid spire
#

reading comprehension, or rather lack of it, seems to have become endemic in the 'yoof'

west phoenix
#

ok bro i dont get any information out of this

slender nymph
#

why not share the last 100 lines from the hub logs like you were asked to

#

that way someone who actually will bother reading it can help you

grand badger
#

they left the server

rich adder
rich adder
grand badger
#

I mean you guys are kinda rude sometimes lol..

#

I just don't respond to low effort questions and be done with it 😆

languid spire
#

'cruel to be kind', never heard of it?

grand badger
#

yea no I get it 😛

frank flare
#

how can I get GameObject from hit?

polar acorn
frank flare
rich adder
#

do .gameObject instead of transform

polar acorn
#

you can't store a transform in that variable

polar acorn
frank flare
#

don't mind that it's public I'm messing with it

rich adder
#

that makes no sense

frank flare
#

that's why I'm asking how to get GameObject from hit

rich adder
#

I told you how

frank flare
#

how?

rich adder
#

scrollup

polar acorn
frank flare
#

wait this and gameObject are different things?

frank flare
#

ah yeah

polar acorn
#

this is the object that is running the code

frank flare
#

yeah

rich adder
#

the script basically

#

is this

#

it works outside of unity as well

frank flare
#

so gameObject is some property

rich adder
#

yea

#

same transform is

frank flare
#

ok

mint remnant
#

Optimized my code, broke everything, code far less readable now, but it runs faster...sigh

raw token
#

Fast and ugly, like my dad's Boston Terrier 👍

mint remnant
#

Was a good practice at least, hadn't used the profiler yet and now I know how to do that, but I'm guessing the fact that I borke everything in the process and it got ugly points to a poor initial design

slender nymph
#

Next step would be to refactor it so that it is readable, even if that is only including comments to clarify why you've written certain things the way you have

mint remnant
#

Switching to object pooling was a big improvement, but I think I need to go to the next level and consider threading to eleviate the stutter in the UI

rich adder
#

Jobs ig but doubt UGUI is part of it

mint remnant
ivory bobcat
#

The task needs to be long enough to be worthwhile else syncing the threads could impact performance.

mint remnant
#

It's a basic minecraft chunk, so there's a lot of heavy lifting in building a chunk, like is a face visible or not, adding bunches of verts, triangles, uvs. THinking something like hey thread I need a chunk, go build it for me tell me when it's ready

queen adder
#

Does fixedupdate happen before physics' position calculation, or after?

devout valley
#

hello. im making a game and following a tutorial and in the tutorial this guy has this thing pop up straight away and it writes the code for him. mine however did not have such option so instead i typed all the code out but it wont work.

heres the tutorial : https://www.youtube.com/watch?v=muAzcpAg3lg 12:32

In this series, I'll be going over beginner through advanced topics for building a complete player controller, both for 1st and 3rd person. We'll covers topics like movement, jumping, slopes, wall handling, step handling, animation, blend trees, Mecanim, Cinemachine, avatar masks, animation layers and multiplayer.

This is a free complete course...

▶ Play video
#

time stamp 12.32

#

Assets\CC\Final CC\Scripts\PlayerLocomotionInput.cs(27,32): error CS0246: The type or namespace name 'InputAction' could not be found (are you missing a using directive or an assembly reference?)

#

my error message

queen adder
queen adder
slender nymph
#

"internal physics update"

queen adder
#

uhh cant see it 🦯

slender nymph
#

well you've scrolled past the entire physics section

#

remember physics updates happen before Update on physics frames

queen adder
#

oh, the entire thing is unselectable, ctrl+F wont find it anyways

#

found it thanks! 🥹

slender nymph
#

yeah, unfortunately it's an image

#

and it looks bad if you use an extension to force darkmode because each of those blocks is surrounded by transparency but aren't transparent themselves

devout valley
#

@slender nymph is it possible u have a look at my issue

#

i just cant seem to find anything about it online

slender nymph
devout valley
#

or any help at all

queen adder
#

!ide

eternal falconBOT
slender nymph
#

and see #854851968446365696 for what to include when asking for help. you didn't even bother sharing your own code

queen adder
#

The problem is a syntax error, which your code editor should point out to you

devout valley
#

i didnt include my code becuase its identical to his as i got it from his download and i didnt want to fill up the chat box

queen adder
#

!code

eternal falconBOT
devout valley
#

ok

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

namespace Jiya.FinalCC
{
    public class PlayerLocomotionInput : MonoBehaviour, PlayerControls.IPlayerLocomotionMapActions
    {
        public PlayerControls PlayerControls { get; private set; }
        public Vector2 MovementInput { get; private set; }

        private void OnEnable()
        {
            PlayerControls = new PlayerControls();
            PlayerControls.Enable();

            PlayerControls.PlayerLocomotionMap.Enable();
            PlayerControls.PlayerLocomotionMap.SetCallbacks(this);
        }

        private void OnDisable()
        {
            PlayerControls.PlayerLocomotionMap.Disable();
            PlayerControls.PlayerLocomotionMap.RemoveCallbacks(this);
        }

        public void OnMovement(InputAction.CallbackContext context)
        {
            MovementInput = context.ReadValue<Vector2>();
            print(MovementInput);
        }

    }
}
queen adder
summer stump
#

But there you go, it is not the same

devout valley
queen adder
#

it's a requirement of the input system

devout valley
#

i didnt even think of that cause it was from the videos git hub download

#

god im so annoyed

#

thanks and sorry for not doing stuff correctly im just so confused by everything

wintry quarry
#

if you're not, you need to get your IDE configured

devout valley
#

i should be im doing it now but its probably wrong

#

ive got the external tools set to visual studio code 1.92.0

devout valley
#

yeah i think ive done that

#

ive followed the VS code segment of it

#

cause im not using visual studio just studio code

slender nymph
#

did you install the c# dev kit? and in doing so, did it install the .net sdk?

devout valley
#

yep and yep

slender nymph
#

have you restarted your computer since the sdk was installed?

devout valley
#

yeah ive had them installed for ages

#

well wait

slender nymph
#

show the output tab in vs code

devout valley
#

ive got .net is that the same as .net sdk

slender nymph
#

the .net runtime is not the same as the .net sdk, no. the .net runtime is used to run .net applications, the .net sdk is used to create them

devout valley
#

output tab? i can do the extensions tab? idrk what the output tab is

queen adder
#

Single button that configures your ide in a single press when? 😭

slender nymph
#

considering vs code now only requires the installation of one extension which installs all of the required ones, it should be simple

frank flare
#

how can I do something when button is just pressed? what's the code for detecting if button was just pressed?

slender nymph
#

but if that is too much to follow, consider switching to a real IDE like visual studio which is much easier to configure and won't just randomly break either

slender nymph
devout valley
slender nymph
#

my guy, please read the obvious error message in the bottom right of vs code

queen adder
frank flare
slender nymph
#

how do you not know how you are getting input?

frank flare
#

what

slender nymph
#

wtf is "input detector"

queen adder
frank flare
slender nymph
#

literally how the fuck should i know the answer to that? it's your project

queen adder
#

or better, public your method, then manually assign in inspector

slender nymph
#

i'm 99% sure they aren't referring to a UI button, but rather an input key

queen adder
#

do you mean if any button was pressed?

summer stump
slender nymph
#

that is only if they are using the Input System. they still have not said whether they are or not

frank flare
mint remnant
#

try some enclosing ()'s

queen adder
#

is that js syntax

slender nymph
twin bolt
summer stump
slender nymph
summer stump
#

Ah. Well why not just look it up?
This is incredibly basic with many guides.
Googling that psuedocode would give you an answer

slender nymph
#

that code does however rotate -10 degrees around the Z axis

twin bolt
#

If thats the case, then there is some other problem with my script.

slender nymph
#

if your intention is to rotate -10 degrees around the Z axis, then yes that is correct

frank flare
# slender nymph why did you not fucking do that the first time i asked?

I had no clue what means input system and what's the difference of it between input manager

also how do I check what exact thing is enabled? If I go to project settings there's Input Manager and and Input System Package but on both of them I can't see if I use input system or input manager

summer stump
polar acorn
slender nymph
frank flare
safe gust
#

Show the code tho?

polar acorn
slender nymph
# frank flare I forgot unity

then start with the beginner courses on the unity !learn site. you've been asking extremely beginner questions for several days now when you could have been learning instead

eternal falconBOT
#

:teacher: Unity Learn ↗

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

slender nymph
twin bolt
devout valley
slender nymph
#

-90 is the same angle as 270

twin bolt
slender nymph
#

you don't. stop relying on the euler angles displayed in the inspector because they are interpreted from the quaternion at the time they are displayed

analog moon
#

what dose the error mean i dont understand this

twin bolt
slender nymph
devout valley
#

ok well yeah im getting a new error message which i dont understand either. its says // Assets\CC\Final CC\Scripts\PlayerLocomotionInput.cs(28,48): error CS1061: 'PlayerControls.PlayerLocomotionMapActions' does not contain a definition for 'RemoveCallbacks' and no accessible extension method 'RemoveCallbacks' accepting a first argument of type 'PlayerControls.PlayerLocomotionMapActions' could be found //

devout valley
#

there hope that helps

wintry quarry
#

it does

wintry quarry
devout valley
#

yeah i did

#

im mega bad at coding i do game design at uni but not the coding part so im tryna learn it aswell

wintry quarry
#

I think the problem is your tutorial is using a different version of the input system than you are

devout valley
#

is it? how

#

asin its an old tutorial?

wintry quarry
#

if you do PlayerControls.PlayerLocomotionMap. and see what functions come up

#

what does it show?

#

they might have renamed RemoveCallbacks or something

#

this is the generated code so it's hard to see

#

If you can find your PlayerControls.cs file and share it that would also help

devout valley
#

nws

#

its autogenerated throught the unity actions

wintry quarry
#

I know

devout valley
#

i can send the tutorial too if it would help

slender nymph
#

you probably should

devout valley
#

i did earlier lemme grab the link

#

In this series, I'll be going over beginner through advanced topics for building a complete player controller, both for 1st and 3rd person. We'll covers topics like movement, jumping, slopes, wall handling, step handling, animation, blend trees, Mecanim, Cinemachine, avatar masks, animation layers and multiplayer.

This is a free complete course...

▶ Play video
wintry quarry
devout valley
#

really the video was released this year maybe its my fault for being on the wrong version

wintry quarry
#

instead of PlayerControls.PlayerLocomotionMap.RemoveCallbacks(this);

#

but yeah this would be due to a difference in the input system versions

devout valley
#

ok ok perfect let my try that

#

is this tutorial just gonna be impossioble becuase of this tho

#

ik you cant tell straight off the bat but like in general

#

omggg it works thank you so much

humble owl
#

How do I make a vr game

frigid quartz
#

I'm making a 2D turn-based card game, and I'm feeling strongly compelled to run the whole game within a GameManager script, like just one long async (yeah?) start function that awaits deal cards, and awaits players' turns. This is a bad idea though right? I've struggled to learn the observer pattern, and my brain doesn't really work like that to compose a complete game, components feel too disconnected for me. I just want to write the game out like a scripted play, all right in front of me on one document.

wintry quarry
#

To the extent that your game is a linear, uninteractive script, you will get readability benefits.

#

Otherwise, you will have spaghetti.

frigid quartz
wintry quarry
#

I will say that a turn based card game is inherently very complicated yes.

wintry quarry
#

I don't think poker would do well with a single script either

frigid quartz
# wintry quarry I don't think poker would do well with a single script either

Well, I'd only being using the GameManager to call every gameplay related function, should've clarified. But I think that keeps things the same. I just need to figure out how to connect things better and understand things better. Obviously that comes from practice.

Here's my previous grand plan, Right now I'm just doing a simple poker practice run, but I always get stuck at the point where I've dealt the cards and need to start actually playing the turns

#

The idea behind using extra Scriptables than I really need to was so that I could serialize them, once I set up cloud save.

#

anyway, thanks for the advice

tawdry agate
#

I want to move my player with a charancerController and I use the Move() method for that, but I noticed that when I stop pressing W for example the player still moves a bit and only stops after a quick delay

wintry quarry
#

GetAxis has built in smoothing

tawdry agate
#

so better use getButtonDown?

wintry quarry
#

No

#

GetAxisRaw

tawdry agate
#

is there a GetAxisRaw("Jump")?

wintry quarry
#

The parameter is your own of course

#

There's a GetAxisRaw

#

I wouldn't recommend things that don't exist. I'm not ChatGPT

tawdry agate
#

is there a built in parameter for pressing space bar for GetAxisRaw? like there is for Horizontal or Vertical? I think not cause you get a float and not a boolean back right?

lethal elbow
#

I guess I'm back with my problem again. This is where I got to last time. I've added AddRelativeForce instead of just AddForce but no difference. For context, I have a problem with my arrow shooting sideways if the character isn't facing towards either direction of the x axis

wintry quarry
tawdry agate
#

ok thx

wintry quarry
lethal elbow
#

        if (Input.GetButtonDown("Fire1"))
        {
            
            GameObject Arrow = Instantiate(projectile, transform.position, transform.rotation);
            Arrow.GetComponent<Rigidbody>().AddRelativeForce(transform.forward * launchVelocity, ForceMode.Force);

        }  
rocky canyon
tawdry agate
rocky canyon
lethal elbow
#

prefab is sorted as per last time as well

rocky canyon
#

if ur using AddForce() you need to use transform.forward

#

the prefabs transform.forward not the spawner's forward

wintry quarry
raw token
# lethal elbow ``` if (Input.GetButtonDown("Fire1")) { ...

transform.forward is relative to the spawning object. AddRelativeForce() applies the force relative to the arrow's orientation, which is already facing the same direction as the spawning object.

Imagine that your character is facing a bearing of 45 degrees. Your code would instantiate the arrow to face 45 degrees, then apply a force pointed 45 degrees from where it's facing - so towards 90 degrees

#

(or 0 degrees? one or the other 👀 )

wintry quarry
#

But note all of these names are determined by your InputManager settings @tawdry agate

rocky canyon
# lethal elbow ``` if (Input.GetButtonDown("Fire1")) { ...
        if (Input.GetButtonDown("Fire1"))
        {
            
            GameObject Arrow = Instantiate(projectile, transform.position, transform.rotation);
            Arrow.GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward * launchVelocity, ForceMode.Force);
        }  
``` or ```cs
        if (Input.GetButtonDown("Fire1"))
        {
            
            GameObject Arrow = Instantiate(projectile, transform.position, transform.rotation);
            Arrow.GetComponent<Rigidbody>().AddForce(Arrow.transform.forward * launchVelocity, ForceMode.Force);
        }  
#

^ both of these would propel the arrow on its forward axis (Z, Blue)

lethal elbow
#

Ah well all I can say is thank you because the suggestions worked.

lethal elbow
wintry quarry
#

but yeah you would only know that by being familiar with those things before or reading documentation

#

it's a good idea to read the documentation when you are using an unfamiliar thing.

lethal elbow
#

I understand that part which is why I changed it to addrelativeforce

wintry quarry
#

Which part? If you understood it then you would realize it's not right

lethal elbow
#

I didn't get my point across haha, I meant I should have read the documentation because I wouldn't have used transform.forward instead of vector3.forward

#

I don't think I got it across, ignore this confused man 🤣

rocky canyon
#

common issue when first learning how to use physics engine..

#

i typically swapped around all the time..

#

normal -> relative, transform -> vector

#

once u get familiar w/ it u know what to use and when

#

theres also things you'll learn about AddForce vs rb.velocity =

#

and then forcemodes..

#

Impulse, Force, Acceleration, VelocityChange etc

raw token
#

It'll become more intuitive with practice, and as you empirically see the effects of things :)

rocky canyon
#

tbh, i made the mistake of not catching this.. you were using transform.forward but that was the gameobjects forward.. (not the actual arrows)

wintry quarry
#

since it's instantiated with transform.rotation as the rotation?

rocky canyon
#

it'd be bakwards right?

#

if he's using the spawners (forward) and not the arrows forward.. but yea i see what u mean

#

since he's matching the rotation

wintry quarry
#

I'm saying transform.forward and Arrow.transform.forward are guaranteed to be the same

#

yeah

rocky canyon
#

just giving him a headsup.. incase it wasn't the same..

#

for future stuff.. (thats why i mentioned the other day. i like to run my physics on the projectil itself..)

lethal elbow
rocky canyon
#

yea, nothing wrong with that..

#

trial and error is a really good way to learn

#

if someone tells you to wear ur seatbelt.. you may or may not listen..
if u get into a car crash while not wearing one.. you might be more likely to buckle up next time..

#

(having first hand experience of what its like w/o it) ;D

#

point being.. its more important to you.. when u figure it out urself..

#

than just being told

lethal elbow
#

I guess it becomes common sense the more you're used to the environment

rocky canyon
#

even after several years of learning.. sometimes u just pick the wrong one lol

lethal elbow
#

Would you say it's better to learn programming while making just projects or maybe doing projects and tutorials on the side? (as in tutorials that show good practice etc)

rocky canyon
#

doing both. + reading and searching documentation for things that are new to you

lethal elbow
#

I've been doing programming for years but I never seem to get anywhere because I'm never consistent so I always end up becoming a beginner again and end up doing tutorials (then getting bored)

rocky canyon
#

ya, tutorials are boring.. its not really fun until u start creating things on ur own

#

but theres always pros and cons.. if ur only following a tutorial.. odds are you wont come across errors or stuff that you can't figure out

#

but if ur doing things on your own.. sometimes its a PITA to figure out why its not acting the way you want it to..

rocky canyon
mint remnant
#

Having soem weirdness with profiler, it's like reporting code executed in the caller class and not heirarchically in the subordinate class.
I have no BeginSample() calls in the World class, yet it shows parts of the Chunk class under it. And not sure why Mesh.Physics.Bak is showing under both.
https://gyazo.com/ebb3ebd591b8e8fe1241c381a4206489

lethal elbow
#

Now I need to actually use an arrow and make it shoot like an arrow

#

That's for another day though, Thank you for the help @rocky canyon, @raw token and @wintry quarry

rocky canyon
#

de nada mi amigo

#

twas alot easier fix today than the other day

lethal elbow
#

I don't know why it was, I don't think I changed anything except addrelativeforce 😭

#

Maybe loads of prep before hand reason being

mint remnant
#

Typical, typing it all up and stepping back and looking at it, I now see why profilrer is doing what it's doing, and and it's doing exactly what I told it to do lol

grave forge
#

how do i import assets from the asset store to my project again

languid spire
grave forge
rocky canyon
#

true, but still

polar acorn
languid spire
#

yes, one you could easily have found on google

queen adder
#

I know this isnt the right place but does anyone know why all the sprites go missing when I run the game on my some of game objects?

rare socket
#

Upon building and running my project, my camera is quite jittery, movement is slower, and scripted animations jitter. Anyone know what could be causing this or what is happening?

grave forge
#

ok i got an warning saying that the package has dependencies uhhh should i worry about that?

summer stump
grave forge
slender nymph
rare socket
grave forge
slender nymph
# rare socket Player Camera Controller: https://gdl.space/onalinanaw.cpp Camera to player tele...

there are several things wrong here

  1. in your PlayerCam class don't multiply mouse input by deltaTime. mouse input is already frame rate independent so doing that multiplication just leads to stuttery camera controls
  2. in that same class you are updating the camera's position and rotation, this should be done in LateUpdate or else it will appear to stutter if it updates before the object it is supposed to be focusing on
  3. same for your CameraMovement class (if that's supposed to be updating the camera's position, it isn't quite clear)
summer stump
grave forge
rare socket
slender nymph
grave forge
slender nymph
#

this is a code channel

#

but like with every material issue, you need to make sure that the materials on those objects are using shaders designed for your render pipeline

queen adder
#

how can I stop my object if a certain condition is met the way I am moving is _verticalInput = Input.GetAxis("Vertical"); transform.Translate(Vector3.up * _verticalInput * _speed * Time.deltaTime);

polar acorn
queen adder
#

here is basically the core of my code

#
        transform.Translate(Vector3.up * _verticalInput * _speed * Time.deltaTime);

        if(_camBottom.y < 0.0)
        {
            Debug.Log("Bottom right hit screen bounds");
        } else if (_camTop.y > 1.0)
        {
            Debug.Log("Top right hit screen bounds");
        }```
polar acorn
queen adder
polar acorn
raw token
#

"Not moving when condition" is the same as "moving when not condition"

jagged vapor
#

i have an isometric camera and a canvas positioned to cover the screen with some text. i also have a click event for game objects. if i try to click an object that is below the text it doesnt register the click. how can i fix this by still making buttons clickable?

queen adder
#

I just switched the if statement to be the opposite

#
        {
            transform.Translate(Vector3.up * _verticalInput * _speed * Time.deltaTime);
        }```
#

so if it is in range move

mint remnant
jagged vapor
wintry quarry
#

Or wait you want text to be click-through-able but not buttons?

#

You can just set the Raycast Target thing to false for anything you want to be able to click through

mint remnant
jagged vapor
wintry quarry
#

It might also be called "blocks Raycast"?

jagged vapor
#

ooh found it. thanks

warm raptor
#

why is my sound not playing ? I want the sound to play on the grenade

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

public class Grenade : MonoBehaviour
{

    [SerializeField] private AudioSource GrenadeSound;
    [SerializeField] private float FuseTimer = 4f;
    private float CurrentTime;

    void Start()
    {
        CurrentTime = 0f;
    }

    void Update()
    {
        CurrentTime += Time.deltaTime;

        if (CurrentTime >= FuseTimer)
        {
            GrenadeSound.Play();
            Destroy(gameObject);
        }
    }
}
slender nymph
#

let me guess, the AudioSource is on the same gameobject as this component?

slender nymph
#

because you are destroying that gameobject

#

how can the audiosource play sound if the audiosource no longer exists?

warm raptor
slender nymph
#

put your audio source on a different gameobject that doesn't get destroyed or use something like AudioSource.PlayClipAtPoint which will spawn a new audio source for the duration of the clip you play

warm raptor
#

oh thx I didn't know AudioSource.PlayClipAtPoint exist and I already love this thing 😆

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

public class MonsterBehaviour : MonoBehaviour
{
    public float walkSpeed;
    public float jumpHeight;
    public float gravity;

    public Transform groundCheck;
    public float groundDistance = 0.4f;

    public Transform player;

    private Vector3 velocity;
    private bool isGrounded;

    // Start is called before the first frame update
    void Start()
    {
        // Find the player in the scene by tag (assuming the player has a tag "Player")
        player = GameObject.FindGameObjectWithTag("Player").transform;
    }

    // Update is called once per frame
    void Update()
    {
        // Perform a raycast downward from the monster's groundCheck position to check if it is grounded
        RaycastHit hit;
        isGrounded = Physics.Raycast(groundCheck.position, Vector3.down, out hit, groundDistance);

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

        // Calculate the direction to the player
        Vector3 direction = (player.position - transform.position).normalized;
        Vector3 move = direction * walkSpeed * Time.deltaTime;

        // Move the monster towards the player
        transform.position += new Vector3(move.x, 0, move.z);
        Debug.Log("Monster Position: " + transform.position);

        // Apply gravity
        velocity.y += gravity * Time.deltaTime;
        transform.position += velocity * Time.deltaTime;
    }

    private void OnDrawGizmosSelected()
    {
        // Visualize the raycast for ground check in the Scene view
        Gizmos.color = Color.red;
        Gizmos.DrawRay(groundCheck.position, Vector3.down * groundDistance);
    }
}

tryna make an enemy follow the player, but it vibrates than goes through the ground

summer stump
#

Oh, missed the Gizmos.DrawRay. I assume you verified the raycast then?

wintry quarry
silk fossil
#

alr ima add a rigid body to my thing

wintry quarry
silk fossil
#

ya, also should I add rigid body and colider to the empty or the child 3d object of the empty

#

or does it not matter?

summer stump
#

It needs to be on the parent, the same object you move

So likely the empty? Not sure about the hierarchy. Assuming that is Monster?

silk fossil
#

Monster is an empty

#

alr tnx guys

#
using System.Collections.Generic;
using UnityEngine;

public class MonsterBehaviour : MonoBehaviour
{
    public float walkSpeed;
    public float jumpHeight;
    public float gravity;

    public Transform groundCheck;
    public float groundDistance = 0.4f;

    public Transform player;

    private Rigidbody rb;
    private bool isGrounded;

    // Start is called before the first frame update
    void Start()
    {
        // Find the player in the scene by tag (assuming the player has a tag "Player")
        player = GameObject.FindGameObjectWithTag("Player").transform;

        // Get the Rigidbody component
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        // Perform a raycast downward from the monster's groundCheck position to check if it is grounded
        RaycastHit hit;
        isGrounded = Physics.Raycast(groundCheck.position, Vector3.down, out hit, groundDistance);

        if (isGrounded && rb.velocity.y < 0)
        {
            rb.velocity = new Vector3(rb.velocity.x, -2f, rb.velocity.z);
        }

        // Calculate the direction to the player
        Vector3 direction = (player.position - transform.position).normalized;
        Vector3 move = direction * walkSpeed * Time.deltaTime;

        // Move the monster towards the player using Rigidbody
        rb.MovePosition(rb.position + new Vector3(move.x, 0, move.z));

        // Apply gravity manually if needed
        rb.velocity += new Vector3(0, gravity * Time.deltaTime, 0);
    }

    private void OnDrawGizmosSelected()
    {
        // Visualize the raycast for ground check in the Scene view
        Gizmos.color = Color.red;
        Gizmos.DrawRay(groundCheck.position, Vector3.down * groundDistance);
    }
}
#

the rigid body solved everything

#

it works now

#

without breaking the laws of physics

#

tnx

silk fossil
#

was

#

wait why is saying "*" + "was" blocked from the server

summer stump
#

MovePosition is for kinematic bodies for the most part

#

Is this gpt generated code?

silk fossil
#

Yes

silk fossil
summer stump
#

Ok, that is why it is not super good. Some oddities I did not understand
I STRONGLY recommend never using gpt for code

silk fossil
#

ya ik it is just the first game i ever made so i just wanted to use gpt

#

too lazy for tutorial

silk fossil
# summer stump Ok, that is why it is not super good. Some oddities I did not understand I STRON...

Response to Aethenosity:
You can acknowledge the feedback and explain the improvements made:
"Thanks for the feedback, Aethenosity. I've updated the script to only use velocity for movement and gravity, and removed any conflicting logic. Your insights were very helpful!"

This should provide a more straightforward and physics-friendly approach for moving the monster and handling ground detection, aligning with best practices and ensuring proper behavior in Unity.

#

💀

raw token
#

It'll give you some bits which work, sometimes. But without experience, neither you nor ChatGPT will be able to weave those bits into a coherent piece of software

eternal needle
#

are you really using gpt to respond as well

silk fossil
#

😭

#

It was only that message

summer stump
#

It will take a lot longer and more effort to use gpt

#

Because it will give you shit that you need to fix and eventually rewrite

#

It is also against server rules to get help with gpt code

eternal needle
#

well simply put, if you're too lazy to learn now then you wont ever do it later. Just another person that we'll see quit game dev

silk fossil
#

You think tutorials better?

silk fossil
eternal needle
#

it should be quite obvious. whats better
learning how to code and learning what you're doing
or
copying a spam generator and directly pasting in the code

silk fossil
#

ill watch a tutorial for npc jumping then ig

summer stump
queen adder
#

Hello everyone. I need help. How to correctly write in code to disable an element using a trigger? For example, when a player approaches something, Box Collider2D turns off and if there is an enemy, it turns on.

teal viper
queen adder
#
        if(other.tag == "Player"){
           
        }
    }```
#

but i don't know how correctly disabled on this object collider

teal viper
#

colliderReference.enabled = false

wintry quarry
queen adder
#
boxCollider.enabled = false;``` this ok?
vocal wharf
#

I'm having a slight problem. I am making an endless runner game with 3 different obstacles that spawn at a slightly variating interval and I want the code to randomly choose 1 of the 3 obstacles to spawn when the method is invoked. I did this by generating a new random number every time the method is invoked and checking if it is either 1, 2, or 3, and depending on the number, it will spawn different obstacles. This is working for 2 of my obstacles but not the third one for some reason. I have all of them assigned in the inspected. Can someone help?

teal viper
wintry quarry
wintry quarry
#

but - Random.Range(1, 3) can only give you 1 or 2

vocal wharf
raw token
#

The float version is inclusive of the max, the int version excludes it
(presumably for ease of use with collections, whose length is always one greater than the index of the last item)

teal viper
wintry quarry
#

read the docs

wintry quarry
#

Anyway with arrays look how much simpler it would be:

public class ObstacleSpawner : MonoBehaviour
{
    public GameObject[] obstaclePrefabs;
    public Transform obstacleSpawner;
    public float startDelay = 1f;
    float spawnInterval;
    void Start()
    {
        Invoke("spawnObstacle", startDelay);
    }

    void spawnObstacle()
    {
        Instantiate(obstaclePrefabs[Random.Range(0, obstaclePrefabs.Length)], obstacleSpawner);
        Invoke("spawnObstacle", Random.Range(1f, 2f));
    }
}```
wintry quarry
#

it only knows that you passed in two ints

#

Also with a float it will never be == 1 == 2 etc

#

it will be like 1.324423

vocal wharf
#

oohh so I have to put the letter f after the numbers in random.range

wintry quarry
#

yes but that's not going to make your code work

#

it will break it in a different way

vocal wharf
#

how

wintry quarry
#

I just explained

wintry quarry
#

I highly recommend learning to use arrays here, it will simplify your code greatly

vocal wharf
#

ok I guess I'll look up a video on arrays

wintry quarry
#

videos are usually not the best learning tools for coding... in my opinion

vocal wharf
wintry quarry
#

when you pass in integers

#

Have you read the documentation for it?

vocal wharf
#

no

#

what documentation

wintry quarry
#

....the unity documentation, for Random.Range

vocal wharf
#

oh that

wintry quarry
#

"That" contains all the information you need.

raw token
vocal wharf
#

@wintry quarry I learned how arrays work and I have to admit it is easier and it works well

steep rose
#

how can i get the opposite of a negative number?

slender nymph
#

multiply it by -1?

#

or do you mean you want to get a number's absolute value? because that would just be Mathf.Abs

steep rose
#

i have a vector and i need to apply a force opposite to that but it can be negative.

#

i just need the opposite of whatever it is

#

at that time

slender nymph
#

mulitply it by -1

#

1 * -1 == -1 and -1 * -1 == 1 so it always produces the opposite. and to get the opposite of a Vector3 you also just multiply it by -1

tawny eagle
#

Hello can someone help me plz, i have my project where my play spawn and can move between tiles but i want to convert this in a endless runner but when i adjust the mouse controller to move automatically my player gets stuck in a tile and dont move and dont respond to controller:

raw token
eternal falconBOT
tawny eagle
mint remnant
#

spawn the new areas ahead of where the playre is, not when he gets right on top of them

tawny eagle
#

Hmm let me try

mint remnant
#

create a viewDistance, then calculate a small grid of distances to ficticious spots where a grid would land and if in range you spawn them, then loop over ones that already exist and despawn ones that went out of veiwer distance

#

https://gyazo.com/7ea3972a90ada0e2636ed46e533bf37e
It's quite a bit of work to get it all setup, but once its done it works great, you get areas in the direction spawning and trailing ones despawning. Which can be taxing if not optimized. I suggest using an object pool for the areas to avoid the alooc overhead

tawny eagle
#

Hmm, isnt what i was thinking

#

I was trying to do something simple like this web game, you think its to difficult for a begginer?

tawny eagle
mint remnant
#

well if your player is getting stuck when a tile spawns in, you are probably not spawning it early, but rather late

#

the concept is still the same even if the scale is smaller

raw token
tawny eagle
#

The only way i get it working is by simulating a constant right input, but this blocks the other controls

#

Excuse my bad english...

raw token
tawny eagle
#

I was also thinking in not move the player but the terrain simulating a treadmill but idk if thats more difficult

raw token
# tawny eagle Yes, the way it works before is that you can use the mouse to clik a tile or the...

I don't see any code in here for movement without mouse or keyboard input, except SimulateRightInput()... But I am confused because you said that SimulateRightInput() works... But you said earlier that your changes cause the player to be stuck and not move at all?

So does SimulateRightInput() work except for the ability to move in other directions, or does it cause your player to sit in place and not move at all?

tawny eagle
#

Oh maybe i send it wrong

#

Yes simualdted input makes the effect i want witch is basically that the player moves in the right direction constanlty as the world keep generating

#

But i dont know how to move it without simulating the input tile by tile

#

But like i said i haven't found a good tutorial on this, there isn't a lot of info

brazen canyon
#

Hello

#

Excuse me

mint remnant
#

looks like you already have the spawn around in a view distance thing in three, how is the player getting stuck? Are you spawning a tale in on top of hime?

brazen canyon
#

Why does this error occurs ?
"Failed to create agent because there is no valid NavMesh"

raw token
# tawny eagle But i dont know how to move it without simulating the input tile by tile

I think what I might do is make direction and previousDirection class fields. I'd create an UpdatePath() method which would determine a path from the direction (like how it's currently done at the end of HandleKeyboardInput()).

If the player presses a directional key, update direction. If the player clicks somewhere, update direction.

Each frame, if path.Count is 0 or direction != previousDirection, then UpdatePath(). Then set previousDirection = direction.

This way, you always have an intended direction from which to calculate a new path, and all the input does is change the direction. And better - a new path is only calculated if the direction changes or the player reaches the end of the path

tawny eagle
#

Hopefully it will work

#

I’ll let u know

#

Let me try

#

Thks :)

raw token
half egret
#

That's usually the case, when instantiating the agent I usually raycast down to the navmesh for the transform to make sure they're actually on it.

raw token
tawny eagle
#

Now it constantly moves on the direction and it change when you make and input, the terrain glitch a little bit strange but that could be fixed

#

Now I only need to make the movement always right and thats it :)

#

Thk u so so much

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

public class Summoning : MonoBehaviour
{   public GameObject Barbarian;
    public int Points;
    private GameObject Barbarian_Clone;
    public Transform BarbarianClone_Transform;
    public List<GameObject> BarbarianCloneList = new List<GameObject>();
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space)){
            SummonBarbarian();
        }
    }

    void SummonBarbarian(){
        if(Points >= 5){
            UnityEngine.Vector3 PlayerRotation = transform.eulerAngles;
            Quaternion PlayerRotationX = Quaternion.Euler(PlayerRotation.x,0,0);

            Barbarian_Clone = Instantiate(Barbarian,transform.position,PlayerRotationX);
            BarbarianCloneList.Add(Barbarian_Clone);
            Debug.Log("Works");
            Points -= 5;
        }
    }
}
``` how do i make PlayerRotation and PlayerRotationX update all the time
summer stump
#

Put it in update? Not behind the conditions

native hill
#

oh okay, thank you ill try that

#

ill just make PlayerRotationX a variable so i dont get an error, thank you

sweet sierra
#

Is this acceptable:

highScore = PlayerPrefs.GetInt("highScore", 0);

I heard/read that PlayerPrefs is more suitable for settings or user preferences but... I just have to store the High Score 🤷.
Or should I read from a txt file from dataPath?

mint remnant
#

try both, see if one has issues?

summer stump
#

I pretty much just always just custom files, usually Json, because it is about just as easy and way more flexible

sweet sierra
#

For currency and level accessibility, I've used text files.

summer stump
#

Wait, so if you are using custom files already, why even consider player prefs?
It is just another text file but stored poorly and inflexible

sweet sierra
#

That's why I asked 🫠. I'm also using PlayerPrefs for sensitivity value

summer stump
#

Basically the only reason to use playerprefs is if you don't know how to use json or binary serialization and don't want to take the half hour to learn imo

sweet sierra
#

Got it. I guess I'll store in a text file too then

void thicket
#

PlayerPrefs is, as the name, for player preferences not save data

sweet sierra
#

@summer stump Alright so for now... I'm doing this with all my persistent data:

filePath = Path.Combine(Application.dataPath, "HighScore.txt");

if (!File.Exists(filePath))
{
    File.WriteAllText(filePath, "0");
}

highScore = int.Parse(File.ReadAllText(filePath));

if (score > highScore)
{
  File.Write(filePath, score); 
}

Is that good enough?

sweet sierra
void thicket
#

I think you'd want little more complex data type than that 🤔

sweet sierra
#

Such as?

void thicket
#

Think about what other data you'd want to store? High score per stages? Clear time? Exp? Idk

sweet sierra
#

I only need HighScore 🤷

#

At this point, I only have to store 3 things : High Score, Currency, LevelAccessibility

#

That's it

#

Or I'd have used something like a database idk

#

I used to use SQLite in AppDev

tiny plaza
#

hey i'm having a hard time untangling my code can someone help please?

sweet sierra
tiny plaza
#

well i think it's better if u see the mess yourself

sweet sierra
#

Ok so... The first if can be simplified by:

isStanding = (!isJumping && !isCrouching && !isGrounded);

But... why !isGrounded? 👀

teal viper
languid spire
sweet sierra
#

Right...

tiny plaza
tiny plaza
sweet sierra
#

Got it. So yeah change the while to an if I guess. Since it's already in update

#

No. In update, just use if it will do the same thing as it's checking every frame

#

While loop will put it in an infinite cycle or... just memory inefficient cycle every frame

languid spire
teal viper
sweet sierra
#

I actually made that mistake in my first days 😭😂

#

But after that, just developed the logic that it's checking every frame so Update is already a loop 🌝

tiny plaza
#

but i'm changing it since it's inefficient anyway

languid spire
tiny plaza
languid spire
#

while is, generally only useful in a Coroutine. In your case you just need to change while to if because FixedUpdate is already a loop

tiny plaza
languid spire
void thicket
umbral rock
#

do u guys think a game like roblox or fortnite will destroy gamedevelopment bcs u can make ur own games within that game and everyone would be able to do it so gamedevelopment would no longer be rewarded?

teal viper
glossy turtle
umbral rock
teal viper
#

You can't make "any" game. You're limited a lot by what you can make in it. Especially when it comes to lower level stuff like rendering features and platform compatibility.
You can make any simple game, sure.

#

But then again, you have ai tools that can make simple games even easier now a days, so Roblox is not gonna last long.

umbral rock
#

hmm yeah, havent rly thought like that lol

#

your right

glossy turtle
jaunty bay
#

on Awake, i want to:

scan across all Spawn objects,
if one has the correct String spawnID,
return that object's transform.

how can i achieve that?

teal viper
jaunty bay
#
        foreach (Spawn spawn in spawns)
        {
            if (spawn.spawnId == spawnId)
            {
                return spawn.transform;
            }
        }

will this work?