#💻┃code-beginner
1 messages · Page 491 of 1
you'll have to open the scene again once it reloads. do not worry, it is not lost or anything
i'm constantly adding a force to an object, yet it's not constantly speeding up. i'm confused because i thought constant force = constant acceleration = constant speed up?
Check the Drag property on your Rigidbody. If it's not zero, the force will continuously be counteracted by drag, which might limit how much the object speeds up.
but you are correct.. constant force will continually speed up, once it breaks thru friction
I made a trail renderer attach to the mouse, similar to fruit ninja – where it only slashes on clicks – but it only works in orthygraphic camera (because it omits the z-value to create the trail). But the problem is it ONLY works in orthographic camera. is there a way to get it to work with perspective camera? I am making a 3d game in unity and i am trying to use it to attack 3d monsters to progress through the stage
Im rusty with unity, i normally use ue, but i can clarify better if i need to
Hello,
I don't understand when I declare the variable and assign it the instance, when I call the input function, it doesn't work but call directly with the instance, it works well
using UnityEngine;
using UnityEngine.InputSystem;
public class DialogueTrigger : MonoBehaviour
{
[SerializeField] private Dialogue dialogue;
private bool isInRange;
private DialogueManager dialogueManager;
private void Awake()
{
dialogueManager = DialogueManager.instance;
}
public void InputDialogue(InputAction.CallbackContext context)
{
if (isInRange)
{
//dialogueManager.StartDialogue(dialogue);
DialogueManager.instance.StartDialogue(dialogue);
}
}
When I use the dialogueManager variable, I have this error ```c#
NullReferenceException: Object reference not set to an instance of an object
DialogueTrigger.InputDialogue
how to you attach code like that
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
presumably a script execution order problem, try changing Awake to Start
How do I learn without being in tutorial hell
read the docs and experiment
depends on how much you already know
it's usually recommended to do 3 simple tutorial games so you learn what unity can do
then after that just think of a simple game you want to make, keep it short & small, then build your game, you can watch tutorials, but don't follow them anymore, watch first, then do yourself after you're done watching the tutorial, if you just keep following tutorials you will never actually learn how to do it
tutorial hell is really not a thing unless you allow it to be
But what if I just remember the code?
Is that tutorial hell?
you need to understand code, not remember it
you use tutorials to understand how you do something
then you use your own brain and look up how tools & functions work to use them yourself
for example, you want to spawn 10 monsters
you go find a tutorial that shows you how to spawn monsters, the tutorial uses a for loop
it's critical that you do not learn that for loop by hard or copy/paste it, once you know you need a for loop, you close the tutorial
then you open google and look up how a for loop works in C# and you write it yourself, that's how you learn
the reason you do it like this is because the next time you need a for loop for something else, blindly copy/pasting it or typing it from memory won't work, since you don't need it for exactly the same thing
you need to understand why you're using a for loop, what that for loop does and how it works
so the next time you need one, you know what it's for and how to use it
if you dont understand the fundamentals, you'll struggle the entire journey spending a day for something that should be an hour of work.
think of even like learning math. for example if you're asked to solve the area of a circle you're not just gonna remember "radius 1 means its pi" and so on for every number. you would learn the actual equation
if you understand what the code does, you can apply it elsewhere
I remember watching tutorials some time ago, and trying so hard to remember the shown multiple times line of code "text.SetText(scoreText.ToString())". It's much better if you understand how this code works, rather than what it does
guys, is there a way to make isTrigger work on specific objects only, and not the others?
i was told to ask it in this channel
show the code you are using for the trigger at this point
i am not using code for the isTrigger, i want it to only work on specific objects
i want the isTrigger off, except for a certain group of objects
.. this is something i would do in code. maybe there are layers, or some other way, but i am not aware of it
it can be code or not, i just want it to work
i saw that, don't think it's what i'm talking about tho
well, pretty sure it is. i think you just do not grasp the basics yet?
in that discussion, he wants to check if it triggered objects, i don't want it to check, i want it to make the collision isTrigger for some objects only
or the opposite
i want the player to have isTrigger while colliding, but not with the floor
ok, i think it is going to trigger (barring layers or some other technique) on anything that it is capable of triggering with. then, what you want to control is what it does with that info. lets say your trigger opens a door. well, then you could use if statements in your code to say, 'pseudocode' if that thing that just trigger the trigger was the thing that i Want to be able to trigger the trigger that Open the Door. else, Do Nothing, or something else
beyond that, i will leave it to people who know more than me, and your own googles
if i understood correctly, you are telling me to use raycasts?
no. a trigger is a trigger. who cares what triggers it. but if the thing that registered as triggering it is not the thing you want, then tell the trigger to do nothing
or i am just not understanding what you are trying to accomplish
basically i want the object to have isTrigger selected in the rigidbody section, but not fall through the floor
Multiple colliders perhaps then? i do not think it can be both, by my experience there is very limited. and probably back to the regular chat room, since yeah, this did not go the code route as expected
i was thinking about a collider at the bottom of the object, but it would be able to noclip through walls and floors
just add a secondary empty object to your rigidbody object that functions as the trigger?
what's the usecase anyway for needing a trigger? why not just use the collider functions?
another option is to turn off gravity for that object
i'm talking about isTrigger in the collider section
... yeah this confused me
so just add a secondary empty object with a trigger collider
what about it falling trough the floor
oh wait
you keep the original collider?
i think i understand what you mean
but I don't understand why you don't just use the collision functions instead of the trigger functions then?
do you mean like, make the first object ignore collisions for specific objects, but the second object which is at the same location acts as a trigger?
is that what you mean
if that's what you need? I don't know what this is for
and it seems like bad design
why do you need a trigger instead of a collision?
Just wondering, what is the virtue/benefit (If any), of using a list of Transforms over using an array of Transforms?
making objects able to move through the object, but it still colliding with the floor and not falling through it
Arrays cannot be resized once they are created (you need to copy the elements over to a new array when you need to add more elements), lists resize as you add and remove elements
so use layers
use a collider, remove all the layers you don't want it to collide with
Right okay, so if the number of entries is always 'static' an array is fine?
Yes
Okay, cool. Thank you 🙂
forgot to mention that the objects that move through it also collide with it, just those objects are still able to move through it
so yeah, just keep the regular collider, remove everything except the floor
then add a secondary trigger collider
i think this idea will work, but it will be slow, so if you have any ideas, tell me
why would it be slow?
if i have many instances of the objects, each one will have it's own trigger clone
might cause some lag
what is many?
maybe 200
maybe more
i still don't know exactly how much
hmm, really depends on what you're doing, could be fine
you may want to look into #1062393052863414313
ok, will check that out later bc i gtg now, thanks tho
I'm building a 3d tower defense game.
I have a hex grid, monsters use A* to find their way to the target walking over the hexes
When I click a hex, I build a tower on it, making it unwalkable
What's a good way to make all my monsters recalculate the path?
Is the event system a good usecase for this? Is it fast enough?
if you are using the unity built in AI nav you can do that built in
i dont think its really that clear what you're asking, or maybe you have a weird structure planned for this.
the event system would just be used to build a tower, nothing about its efficiency should matter here. the grid being modified should call a method to possibly recalculate paths. if its fast enough can only be answered if you profile it.
hmm need to think about it some more
each monster can be at different location, so they might have different paths after a tower is built
so I need a way for each monster to individually calculate their new path
My idea was to draw a main path and then recalculate that when a tower is placed
Monsters will then just try to find the quickest path back to that main path
What I'm asking for is how to have each individual monster recalculate their path when I place a tower
I was thinking of throwing an event when I place a tower
All monsters would be listening for that event and recalculate their path when it's triggered
Throwing an event is the best way to do it
Yea you could do an event, though I'd make it a "grid updated" event rather than anything specific to your tower. Incase you have other features later which might need it to recalculate.
Really if theres a performance issue itll be from recalculating the path rather than design choices here. A bunch of objects constantly subscribing/unsubscribing might not be too pretty though for your GC
Could you test me with something random?
find the 3rd object of an array
array[2]
That's the third???
unless an array counts 0
Indices start at 0
Oh but could you test me with a game mechanic thing lol
No, itd be pointless. I have no clue what you know or what you need to learn.
Start experimenting, learn and try to understand what things actually do
Oh alright
I don't like trigonmetry lol
public?
🤷♂️ I never mentioned trig but if that's already your attitude on something that's really not even entry level for game dev, dont expect to get far.
Oh my bad
And I dont use trig at all really, everything I've done can be solved using built in vector or quaternion math
I meant to ask do you know any good trig tutorials?
Ohh
btw do you know the difference between transform vector and vector math?
I dont know what you mean. A vector is a vector
vector "math" just uses a vector, so it is a vector
how to hide unhide a canvas with a bool
literally type that in google
They are game objects like others, so you should be able to call .SetActive(true) on it to activate and with false to deactivate
In mathematics, vector has both magnitude and direction and is usually written as AB, with the start at A and end at B, whereas Unity uses vector as a tuple with 2 to 4 axes: x, y, z and w, to, usually, represent a point
I'm kinda confuse on what is direction
Are you referring to the mathematical version of vector?
Yeah and also transform direction, sorry for asking so many questions
In mathematics, as previously mentioned, since vector is written as AB, with the start at A and end at B, you can clearly read its direction. Unity's Transform doesn't have the direction property, although it has forward, right and up to represent its direction based on its rotation
Is there a visualize video on this type of stuff?
nvm I think I'm just confusing my self
It's just where something is pointing right?
I suppose, there should be
how can i get a varible from a other script it is public
Vector3.right is (1, 0, 0), and transform.right is current transform.rotation multiplied by it
create a variable
You need a reference to the object with a public variable
how
public className varName;
Google how to access variables from another classes in C#
go to pinned mesages and check the first link under General . . .
not true. it's one of the most asked questions . . .
i didnt uinderstant that
If it's inside of the MonoBehaviour, you need to either make is a Singleton, if it's some kind of Manager (e.g. GameManager), make it static, this way no object reference is needed, or get the reference to your MonoBehaviour in another class by e.g. serializing it in the inspector or getting the Component from another object
so transform.right is the right side of the gameobject facing direction?
And it will rotate if the player rotates?
From my experience, most frequently, non-singleton scripts don't have variables to be accessed by other scripts
Please do at least a modicum of research before asking questions
from the pinned messages, check the first link under the General section . . .
Yes, that's right
So for vector direction, it's like where B point's direction from A point's perspective?
it is always the GameObject's local right-facing direction (based on its rotation) . . .
So I can imagine the unit circle on the player from the top angle
guys is there a way for me to pause my script for 5 seconds? like the script doesent do anything for 5 seconds
that is not 'in more detail'
but i have the script do nothing for 5 secs how do i explain that
you can use a coroutine to pause execution of a script . . .
to start with are you talking about a script or a method on a script?. Little details like that
you cannot pause a whole script
you can pause sections
ill try the coroutine
you can make another script to turn off the script using a coroutine
if you want, but theres no need
even then public methods are still executable
you'll need a bool variable to flip in order to stop execution . . .
-# NOTE: you can only stop Update methods from executing; any outside script calling a public method or accessing a public member will still take place.
So you would need to add a bool into every method to stop it's execution
anyone know good beginner tutorials for unity c#
Not sure what you mean
I can't recommend one specifically but you could ask the c# community that as well
!csds
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
click pinned messages and check under the Tutorials and Courses section . . .
i need exactly unity c#, i know a bit of c#/.net
If you already know a bit of C#, you may start directly from learning Unity on their official learning site !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
how can i change that text in the code
gameObject.name = "New Name";
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
are you trying to change text on the TMP text or are you trying to change the gameobject name?
i am trying to cgange the text
click on the TMP text in the heirarachy and just change it
use text.text = "something";
i believe thats how you do it
but i suggest you !learn how to use unity
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
what was?
TextMeshProUGUI
you have to give the class of the variable TMP_Text
not TextMeshPro
then use #💻┃code-beginner message
ok so now i just cant test my game
and its still not working
should i restart?
How do you make a grid layout group not start in the exact corner but offset a little
if that's even possible
public class Fruit : MonoBehaviour, IGrabbable
{
public event EventHandler onThisGrabbableCollected;
void OnCollisionEnter2D(Collision2D other)
{
if(other.collider.TryGetComponent(out Player player))
{
player.GrabbableHandle(this);
}
}
public void Collect()
{
StartCoroutine(OnGrabbableCollectedCoroutine());
}
private IEnumerator OnGrabbableCollectedCoroutine()
{
onThisGrabbableCollected?.Invoke(this, EventArgs.Empty);
yield return null; //somehow managing to wait until the animation is played using the above invoked event
Destroy(gameObject);
}
}```I have two scripts, one for logic and one for visuals attached to the same object, I want to call the animation playing method in visual script by invoking the onThisGrabbableCollected event but, the catch is the fruit will immediately be destroyed as soon as the animation even starts to play
If there is a better way than using Coroutines, I will be glad to hear!
the animation will not play if you destroy the GameObject. just destroy it after the animation finishes. you can use an animation event that calls a method on the logic script, which in turn, invokes the event . . .
@torn marlin a coroutine will work as well, but you'd need to know the length of the clip to yield the coroutine. an animation event will automatically call the (public) method on the script when the time reaches the event . . .
If deleting library didn't help, I would try making a new project in a newer unity version and testing that. Then you can just import all of your assets from your old project into your new one
I did it’s working now but I did it on the same version
feels good to me but Animation events feel better as the code is entirely seperated
the only drawback is the script with the callback method (from the animation event) must be attached to the GameObject with the Animator component; but usually, that's not a problem, and you can easily workaround, if necessary . . .
animation events are simple and easy to use. i'd try that first . . .
how do you refactor your code?
I most of the times get in the headache of refactoring which takes away all the fun of programming a game
sed
lol
both the scripts are in same gameobject btw
uhh but I still need to return the total time of animation
i only refactor when i need to, but my style is a bit different. i like building systems and mechanics—or at least, learning how to. it's use a modular (component-based) approach when creating scripts called composition. you stack individual scripts to create the entity . . .
thanks!
it's fine to have both scripts on the same GameObject . . .
i would subscribe to events in OnEnable and unsub in OnDisable . . .
i meant that it was as easy as referencing the Fruit class in the start 
now it will be better to use an action rather than an event
ohh
thanks
grabbing internal references (components on the GameObject) is best done in Awake and grabbing external references (components from other GameObjects) is best done in Start . . .
I really didnt knew that difference
an action is an event, they are basically the same thing; most people use them interchangeably. there is a difference between using the event keyword. that only allows the script holding the action/event to invoke it . . .
I always had this in mind that awake and start had something to do with call time difference
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://gdl.space/sedobetabu.cs https://gdl.space/ipoxixilal.cs https://gdl.space/edonutibux.cs why isnt this code working
"isn't working" is a pretty vague statement.
Elaborate.
the item thing isnt working sorry
the e interact on the item doesnt do anything
And what are you trying to do and what is the result?
that de text changes from the canvas
Does the Interact() method from NPCInteractable get called?
i think so
Don't think so, check it
if (collider.TryGetComponent(out NPCInteractable npcInteractable))
{
npcInteractable.Interact();
}
Add a Debug.Log into it and confirm it
Is the uiText located on a GameObject under Canvas1?
Because you're explicitly setting it inactive one line above changing the text
And?
but i cant ad scripts
[SerializeField] private ItemInteract itemInteract; this is that little code
Obviously, you can only add instances of this class, not scripts
Same as with your Canvas1, Canvas2 and uiText
how can i ad scripts
You cannot.
oke
What you're looking for is referencing a specific class instance
If it's somewhere on your scene / is a prefab and always the same, then just drag it into the field
Otherwise think of a method to provide your NPCInteractable instance with an appropriate instance of ItemInteract
Hi! I've got an question that I'm not sure about how to solve it the best. I have an chunk generation for my game that works async with the unity job system. Once a chunk is finished generating I instanciate all the corresponding gameobjects in update() the next time it gets called. However, Instanciating multiple chunks at the same time causes some major laags in that frame because instanciating is very expensive. My approach would be to use coreroutines to only generate one chunk at a time. My question is, is there a way to automatically determine how long the current frame took and pass depending on the frametime the work to the next frames? So as many objects get instaciated at the same frame as possible without risking to cause laags?
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class HoleScript : MonoBehaviour
{
[SerializeField] GameObject ball;
// Start is called before the first frame update
void Start()
{
ball.SetActive(true);
}
// Update is called once per frame
void Update()
{
if (Physics2D.Raycast(transform.position, Vector2.down, 0.51f, LayerMask.GetMask("Hole")) && ball.activeInHierarchy)
{
ball.SetActive(false);
}
if (!ball.activeInHierarchy && Input.GetKey(KeyCode.Mouse0))
{
ball.transform.position = new Vector2(0, 0);
ball.SetActive(true);
}
Debug.Log(ball.activeInHierarchy);
}
}
im trying to get a ball to spawn in when the mouse clicks after it goes in the hole in a golf game
the ball going into the whole works find but then i can get it to spawn back
If that script is on the ball then it is also obviously deactivated alongside the ball
Has anyone got htis problem before when enterling playmode? and if so, does anyone know how to fix it?
It was completely out of the blue
i swear i haven't done anything to cause this
PlayerInteract this one doesnt work
Explain "doesn't work"
i dont know what but it doesnt sent the singnal to the other classes
if (collider.TryGetComponent(out NPCInteractable npcInteractable))
{
npcInteractable.Interact();
this 1
Then debug it
Also consider printing out text that actually means something
foreach (Collider collider in colliderArray)
{
Debug.Log($"Player interaction detected {collider.gameObject.name}");
...
}
Check if it's detected first
If it is, check if the detected object actually has NPCInteractable component on it
If it doesn't, check if it has a detectable collider
Did you add that into the code?
yes
And it's not detecting it I guess
wait in the wrong spot
ohhh that makes sense
So is it detecting it or not?
Yes, because your itemInteract is null.
Exactly what I just said
the npc is detected
You're trying to call CanGetItem() on itemInteract but itemInteract is not assigned to anything
Dear lord
Are you even reading?
I'm talking about itemInteract, not npcInteractable
You even sent a screenshot of the field being unassigned earlier
yea i am reading its just i am trying fikxing myselff also
Then start with assigning that field to something
to what i cant do the script and i cant at the item
Screenshot the item you're trying to drag into that field
Seeing the inspector would be nice.
Then drag that into the field
i did
Show it
Meaning?
the text doesnt change but i think i know how to fiks
yea i know
did you follow what I said?
but there i accedently delted the function
deleted what?
the change text function
Text.text = "something";?
yea
i am doing that
good
Could someone please take a look and see if they can see where I'm going wrong please? Cause this is driving me nuts, been stuck on it for about 6 hours now. 😦
https://hastebin.com/share/uhocanarow.csharp
The 'forward' part of the piston (bit that should be attached to the wheel(s) is losing it's position (staying static in world space by the looks of it), which causes the 'root' part of the piston (part that's connected to the body of the rover)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
why doesnt this work
what dosent works
How are you calling Interact?
first time it works the second time it doesnt and it is beacause my level shit doesnt work
i fikset it nerver nind
how do I make a list of normal gameobjects
you add GameObject to the type for List
like this?
like wat?
private List<GameObject> Maps;
and how are you going to initialize that?
what do you mean
exactly, if you dont know how to use something go and read the docs, that is what they are for
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapSwappingTrigger : MonoBehaviour
{
private List<GameObject> MapLeaving;
private List<> MapJoining;
private void LeaveMap()
{
void OnTriggerEnter()
{
MapLeaving.SetActive(false);
}
}
}
oof
I'm literally asking for help
idk I forgot how to do gameobject lists
you literally have it done above it
the one above it would not give you errors no
how do I turn off the entire list of things
thats assuming they even know how to read this
this is the documentation for it, also any other C# related content
you have to loop through them
always need a loop to do something in each one
how so?
for loop or foreach loop over the collection
idk how to do that i'm dupid
while loops can work too
for loop is just a fancy while loop
nice to know
actually read this page it shows all you need to know
i could actually use that page 😂
int i = 0;
int items = targets.Length;
while (i < items)
{
var target = targets[i];
i++;
}
or
while (i++ < items)
{
var target = targets[i];
}```
for loop it just basically makes everything inline
im just starting to learn loops and arrays due to me makng my own AI for unity game
so im not the best but i kinda understand them
while (i++ < items)
don't need the separate i++
ah yes I always forget we can do that
so many things I used to have individual scripts on single objects but with loops/arrays you can just loop through all of them to control at once and its more performant
imagine 100 crystals/coins pickup items spinning... now you have 100+ update loops running (assuming they're near by player)
Thats insane
Instead of 1 update loop that rotates all of them, all you need to offset each one beginning rotation so they all spin with variance
when i set up the basic AI movement using arrays and such to pick a point randomly, i was estatic
very fun to mess around with
yeah very good usecase is also AI for almost all things lol
valid points / targets, actions
yeah currently i have a random int and it uses that int to give the Bot a position to rotate to and to go too
im thinking of making it so if the point is higher on the y axis than a threshold and the current position of the Bot, then make the Bot jump to reach the point
Im trying to filter for specific enum types, but it's giving me a console error. How do I...?
well whats the error
I got it :D
SlimeType.Green
Anyone? Please? Quickly losing the will to live. lol.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Guys my gun is stuck in the reload and I have no idea why. here is my code: https://gdl.space/baqelabuyi.cs
please help guys
Stuck how?
screenshot your console so we can see your debug logs
it just says cannot shoot bcoz of the cooldown or reload or when I press reload key it says already reloadin
like doesnt turn on or off
it should show a great deal more than that
ok wait
the reloading state is on
ik but it shoudnt turn on on the start
apparently it does
uh why?
Show the GunData script
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[CreateAssetMenu(fileName = "Gun", menuName = "Weapon/Gun")]
public class GunData : ScriptableObject
{
[Header("Info")]
public new string name;
[Header("Shooting")]
public float damage;
public float maxDistance;
[Header("Reloading")]
public int currentAmmo;
public int magSize;
public float fireRate;
public float reloadTime;
[HideInInspector] public bool reloading;
}```
ah, your SO is being updated when you play in editor. you need to reset it's values
so I just set it in start to 0?
The SO shouldn't store the reloading state at all, it should be in the gun script
its just the data
yeah and the state is not data
ok ill try rn
Same with currentAmmo
thx it worked
im trying to format code for cs in discord but whenever I do the and then the cs, it just treats the cs as normal text and doesnt format it
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ya i got that, just the cs part isnt working for me
its not as good as your ide
but does some basic highlighting
private async UniTask Shoot()
{
_fxParticle.Play(true);
await UniTaskTools.AwaitSeconds(0.5f, CancellationToken, awaitCancelBehaviour: UniTaskTools.AwaitCancelBehaviour.CancelAndStop);
_viewPool.Despawn(this);
}
the cs needs to go right after the ` things
```cs
not
```
cs
not in the next line
ya i was doing that
How do i get a gameobjects position and then set a different gameobject to that position expect make the x vale a little behind and not directly on top?
private void
Copy paste this:
```cs
public void Test(){
int x = 0;
}
```
do you want it to follow?
- Yes: SetParent
- No: objectToPlace.transform.position = objectToTarget.transform.position
Because it's actually code
private void as the entirety of a line is not code
[SerializeField] private Transform object1, object2;
float offset = -1f;//example number
var targetPos = object1.position;
targetPos.x += offset;
object2.position = targetPos;```
example
i have c# code i took from VS but its not working
.transform.position. Set an object's transform.position to another object's transform.position plus whatever offset
nvm
i made a fruit ninja tutorial for a blade slashing in Unity3D, but it only works with a orthographic camera and i was wondering if there was a way to get it working with perspective camera
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
please use one of the paste sites 😄
You put cs on a different line again and also that definitely should be in a bin
yea i got it working earlier, then tried again and its not working, sorry
i realized and deleted it
well it already has the code to do the following I got it to where it takes gameobject1 position adn the sets gameobject 2 to that position but i just couldnt get it to place gameobject to a little behind gameobject1 instead of being directly on top
Im unsure on how to set the offset
Add an offset
Literally, with +
add whatever displacement you want
mikey.transform.position + new Vector3(x, y, z)
https://hastebin.com/share/oxutakajeg.csharp
ill just do this
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
sorry for the spam
So when i do this code and subtract some on the x to make it go behind it puts the dog too far down and not level like the first picture
why you put transform.position in new ()
I thought that would be the same as before as i didnt need to change y and z
rofl
ohh i would just do 0
float offset = -3f;//example number
var targetPos = mikey.position;
targetPos.x += offset;
ralph.position = targetPos;```
after spending an hour and a half reading libraries and docs i got the look script to work and the move script to work
this stuff easier than making roblox games though
C# to me makes more sense than La
Lua
except for like vectors and stuff
can we see the scripts so we can learn from the master
using System;
using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;
public class plrCharCam: MonoBehaviour
{
public GameObject plrCharCamera;
public float vertRtLim = 90.0f;
public float verticalRotation = 0.0f;
public float lookSens = 90.0f;
void Start()
{
//Check
Debug.Log("plrCharCam working.");
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
//Get Axis
float xAxis = Input.GetAxis("Mouse X") * lookSens;
float yAxis = Input.GetAxis("Mouse Y") * lookSens;
transform.Rotate(Vector3.up * xAxis);
verticalRotation -= yAxis;
verticalRotation = Mathf.Clamp(verticalRotation, -vertRtLim, vertRtLim);
plrCharCamera.transform.localRotation = Quaternion.Euler(verticalRotation, 0, 0);
}
}
second one unfinished because im adding jumping
how come your doing var instead of a vector3 or transform?
what is the system.security.cryptography for?
why do your class names start lowercase
var is just a shorthand when the type is already inferred. in this case its a Vector3 because .position returns Vector3
i thought you were a master
code works until it doesn't then you question your sanity and skills
wait till you get imposter syndrome
wait bruh what is the security thing
Contains the common language runtime implementation of the Authenticode X.509 v.3 certificate. This certificate is signed with a private key that uniquely and positively identifies the holder of the certificate.
does bro know my maiden name and location 💀
you added that , remove the using
why did you add that?
yes FBI is breaching now..
all i added was the main code
which you copied from where?
wherever you copied it from had that or VS deduced it somehow from a class..
bull shit
on my life
i didnt copy it
i read libraries and docs and wrote it
i copied a couple lines in the main script
but not that
that is standard code from 99% of beginners tutorials
libraries and docs
and i didnt copy it
which libraries would that be
one sec
we didn't need the whole pastefest could've just said where
just giving links
at least he didnt multiply mouse movement input with time.deltatime, like brackey's tutorial where he specifically said that its necessary 😄
thank heaven for small mercies
because YOU told it to
we weren't there how should we know
is there like a reason it would do that by default?
if you paste code visual studio tries to find a matching class / namespace for that class
maybe you got the code from chatgpt and it decided to add those for some reason
not by default, these thing happen when people who dont know how to code dont pay attention to what they are doing
to be fair n give benefit of doubt VS does add some ridiculous shit sometimes
Got it working, but what would be the reson that the animations isnt working after it gets teleported?
when he was configuring VS he could have added smth
by accident
we have no way of knowing that without seeing it..
maybe but sometimes it adds namespaces for me that i have no clue it added and when i try compile code is usually sitting there grayed out like a using UnityEditor namespace
weird 😅
i downloaded like icons for vs code earlier
sounds productive
idk i looked it up and it said extensions or copying code
he could also have gotten weird things from a suspicious VS download
or another program downloading VS
whatchu doing on your PC 
im gonna make a fresh file and see if it adds it
nothing lmao (well other than configuring my flight stick)
now it doesnt add it 
I just want to preface this by saying, I get that people get busy etc. and people may not have an answer.......but.....
I haveta ask, have I done something wrong? Is there something wrong with the way I ask questions etc. ?
I only ask because the last few questions about problems that I've asked (apart from a simple one this morning), have gone completely unanswered.
I get that I may be over-reacting, but if I'm doing something wrong, I'd prefer to know. 😕 (The questions I've asked recently have been long, but that's just to try and provide as much info as possible. 🙂
a purple monkey is probably going to pop up on my screen soon
could just be hard questions that nobody knows how to answer?
either people dont know the answer they cant / dont want to answer
you didnt do anything wrong though 🤔
Can I suggest you look at the code you posted and then look at the code posted by lemon a little while after you. then think very hard about the difference
i suggest thugging it out and learning to code
also i see you posted in the physics channel, maybe try unity-talk cause more people look there
yes its over-react because I have no idea what issue might be, so I rather not comment if I don't know something
then delete your other post, try not to crosspost
I made a fruit ninja mechanic but it only works with orthographic camera and not perspective camera and I dont know how to get it to work with perspective
Ah crap, that one is my bad, I thought I'd deleted the other one.
use a plane
use a paste site
can you ellaborate?
also this ^
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you zerod out the Z already I see that should help already, but because propsective you're dealing with depth / frustum projection
Okay, but tbh, I was told to use Hastebin cause it's easier to read on mobile. 😕
yeah in the tutorial (im really rusty in unity), it said it zeroed it out helps with orthographic since it basically omits the z axis
i know how to do it in unreal but struggling with unity
that is not what I meant. Look at the actual code
which part is messing up btw
first one showing that it works before teleport then second showing it doesnt but the jump anim and ide still work just not the run
it works fine in ortho, but it perspective camera, it either doesnt show up at all, or is locked in the center, neither of which are affected by the mouse
give me 2 numbers below ten
a = int(input("enter a number"))
b = int(input("enter a number"))
def whichone():
if a + b > 10:
return "nuggets"
else:
return "spaghetti"
whichone()
it will decide what i ear
eat
I honestly have debugged it, but they were no help at all, they just showed what I can see in the game view (I do tend to delete the lines, cause I find the code easier to read without (I know that sounds stupid).
try using the plane, I usually do that for prospective cameras. Check the link I sent has example how to make a plane raycast
alright ill try to figure it out, i understand kinda just suck with script
that is stupid because it makes it impossible for us to read without having any idea whatsoever of the paths taken through the code and the values used
we can do without shitposting unrelated to unity stuff
wait ididnt add print lmao
no
its code related
is it not
Its not a unity related code question/topic . no
allergic to fun
Ask questions and discuss anything related to beginner coding concepts in Unity
for unity only
I mean.. rules are there for a reason.
I suggest you check #📖┃code-of-conduct
no memes in general chat 🤓 👿
better me telling you than a mod believe me lol
Enough noise already.
😂, you said it just in time
Move along @balmy dagger
move along pal, dont make the alpha angry 👿
!mute 1062436270581743616 14d spam
rip
mbmma._. was muted.
i knew that was coming
I got it(:
Okay, here's a new video of the issue with Logs.
If you watch the video, at the end I go through the affected objects. The logs say that the positioning is correct etc. but the inspector and the scene view tells a different story. I'm really confused as to what's happening.
(Apologies for the bit of faff before I switch to 'local' mode, Unity keeps defaulting back to global.
I've split the code up a bit (seperated out the input controls and the suspension control into seperate scripts for later)
Here's the suspension script.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
im kinda confused on how to use OnTriggerEnter2D... why is this not working?
this is the code
You have it inside of another function
its inside another method
Okay moving on from the suspension thing cause it's driving me nuts.
However I have a new question.
A while ago I was given this code to use for an interaction system...I'm struggling to remember by whom I was given it by, but I think it was @rich adder
public class Interactable : MonoBehaviour
{
public UnityEvent OnInteract;
public void Interaction()
{
OnInteract.Invoke();
}
}
My question is, has something changed with the way Unity does events in c# because this is no longer working that way I remember (I could be remembering wrong and missing something completely obvious, but it no longer works in my old project where I first used it. 😕
what exactly do expect to happen? there is nothing in this code that wouldn't work
No, my bad, wasn't navarone, it was @wintry quarry
bare with me, sorry, just having another look at my old project. Sorry, very tired atm.
Yep, me being a collosal part of the male anatomy. lol. Sorry.
Think it's time for bed.
Hello, i need help i try to learn Unity i make a tower defense but i can't move the ennemy to my tower because is not assigned but i can't assigned it, if sombody can help me i am good to to a voice chat
can someone tell me why my cylinder isnt appearing when i click a button like a soda machine? https://paste.ofcode.org/rTQZ34Lvi8aq8iimYA9aQs
im trying to fix this
I dont know if its for beginner, but my methods dont work when I build my game but they are perfectly fine in the editor
do you have a log shown? for Debug.Log("Cylinder enabled.");?
if (cylinder != null && spawnPoint != null)
{
// Enable the cylinder and move it to the spawn point
cylinder.SetActive(true);
cylinder.transform.position = spawnPoint.position;
cylinder.transform.rotation = spawnPoint.rotation;
isCylinderEnabled = true; // Set flag to prevent re-activation during cooldown
Debug.Log("Cylinder enabled.");
}
else
{
Debug.LogWarning("Cylinder or SpawnPoint is not assigned.");
}
no, im trying to figure out is this validation return false?
cylinder != null && spawnPoint != null
or even does this function is called? EnableCylinder();
if ((other == leftHandCollider || other == rightHandCollider) && !isCylinderEnabled)
{
if (other.gameObject == cubeButton)
{
EnableCylinder();
}
}
ok when you run the games does one of this debug. is shown on your console
Debug.LogWarning("Cylinder or SpawnPoint is not assigned.");
Debug.Log("Cylinder enabled.");
ok then we can add another debug on the collider.
// Example
Debug.Log($"Other : {other.name}")
if ((other == leftHandCollider || other == rightHandCollider) && !isCylinderEnabled)
{
if (other.gameObject == cubeButton)
{
EnableCylinder();
}
}
on this part of code, Add Debug for this
other.name
and also add this
!isCylinderEnabled
as long as you dont add a new logic/validation that related to your problem in your code that you shared earlier it's fine.
wdym?
nothing just shared your recent code in here.
yes correct, now when you run, can you show me the debug result
now you need to check does your trigger works on your character.
errmm is this for AR/VR thing? i havent got to playaround with it. so i dont know how to answer it.
yes im aware and i dont know how to answer it, cause i dont have any experience with it 
frick
but i assume it's same like 2D or 3D one, then you need to make sure your gameobject collider works first. the one that have MyActor Script. once you do that then make sure the Debug Log shown on your console. 
should i do the soda machine after cause im making like a chipotle type of game
if this is AR/VR please take this to #🥽┃virtual-reality or #🤯┃augmented-reality
ok my bad
someone that is more knowledgeable in this type of stuff will help you better than we can 😅
ok sorry
you're not in trouble, dont be
ok
so uh lol when I try to move the car forward it just flips
private Rigidbody otherPlayer_rb;
public Rigidbody Wheel1;
public Rigidbody Wheel2;
public Rigidbody Wheel3;
public Rigidbody Wheel4;
void Start()
{
// otherPlayer_rb = GetComponent<Rigidbody>();
}
public void move(float speed)
{
if (Wheel1.angularVelocity.magnitude < 2) {
Wheel1.AddRelativeTorque(Vector3.right * speed * 100f);
}
}
public void rotate(float speed)
{
Debug.Log(otherPlayer_rb.angularVelocity.magnitude);
if (otherPlayer_rb.angularVelocity.magnitude < 1f)
{
otherPlayer_rb.AddRelativeTorque(-Vector3.up * speed * 100f);
}
}
Here's a video with details on what's going on.
I guess it's a problem of fixedjoint setting or something because the whole model rotates with the wheel, meaning the whole model and the wheel are depending on each other
could be because I don't use wheelcollider which I highly doubt
personally its best to either use a wheelcollider or make your own raycast/spherecast based wheels and suspension. But to fix your problem i would suggest using a configurable joint and locking the angular constraints to whatever
https://docs.unity3d.com/ScriptReference/ConfigurableJoint.html
but like i said you probably want to look into using a wheelcollider or raycast/spherecast based wheels
you could use hinge joint as well
ooooh didn't know we have OnBecameInvisible and OnBecameVisible, this is handy
does using wheelcollider fix it?
because before messing with wheels I want to have at least something working
I tried using configurable joint but there's too much of stuff there
what means pita?
pain in the ass
it depends tho tbh.. if u want a realistic car controller u might want to use wheel colliders and just brute force thru tuning them to work for you
if ur going more for an arcade feel i'd definately do raycasts and forces
my example is super primitive tho.. theres alot u could do to make it more realistic.. i was just having fun w/ the bouncey spring suspension lol
well I don't even really know how to make a game so I guess everything working somewhat nice would be ok for me, I will just use hinge joint then add wheel colliders on wheels
yea, then ur still in the learning process.. try out everything
get a feel for what works for u.. and try to lean into that
the configurable joint should fix your problem, just enable the angular lock and use those and nothing else
i gave you the Documentation for it
how do i scale my game to a normal scale? Each time i create a object such as a scroll view its always 100x bigger than my character.
you should create a default cube object in your game, if thats also 100x bigger then all the other stuff isnt big, your character is tiny
My character is the default cube 😅 it’s a learning project so I didn’t make some 2D character. I went to 2D -> sprites -> cube
I think the default cube is just 1x1 pixel
And if you import an image that will be huge compared to that 1x1
thats because thats UI
so it will be bigger
you need to zoom out to edit UI
your game is inside the camera view, the Canvas (ui) is a lot bigger
UI is in pixels. the size is huge because 1 unit = 1 pixel. that is normal . . .
Nothing more I hate than Unity wheels
What docs say that it does have?
@teal viper
private void Update()
{
if (Input.GetMouseButton(0) && canShoot) Shoot();
}
public void Shoot()
{
var b = Instantiate(bullet, shootPoint.position, shootPoint.rotation);
b.AddForce(shootPoint.forward * bulletSpeed, ForceMode.Impulse);
}
I removed the fire rate code because its irrelevant
did you read the example given and how it needs to be done? youre missing a lot of steps
https://docs.unity3d.com/ScriptReference/Texture2D.ReadPixels.html
This is Texture2d, not a RenderTexture.
Try drawing a debug ray and see if the issue affects it as well
From what exactly and when?
From the shoot point in the direction of it's forward right after you instantiate.
Yes, the ray is doing the same thing as the bullets
Where does shootPoint position update?
Its attached to the gun
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
xRot -= mouseY;
yRot += mouseX;
cam.transform.rotation = Quaternion.Euler(xRot, yRot, 0);
Theres other code in the camera but its irrelevant
It is relevant - Where is it called from?
This is called in Update in the player movement. The other code is just clamping and head bobbing
Im assuming im gonna have to find a way to make the gun update before the camera somehow
Okay.
Here's one possible explanation:
The bullet instantiation runs before the camera update. Then the rendering on that frame happens.
After probably.
One thing you could try is modifying the execution order of the scripts such that the camera is updated earlier.
Okay, thats probably it
Yes im gonna figure out how to do that now
Thanks
That actually worked, changing execution order is very simple.
I am new to unity, but have professional experience as a software engineer. I'm struggling to find guides or tutorials for implementing a fps character controller that look high-quality (everything looks very simplified and poorly structured sot that beginners can understand). And tutorials that are up to date, i.e using the latest input system and delta time usages.
tbh if you're a professional software engineer you are much better off forgetting about tutorials and just going through the Unity Manual and API docs
there is the kcc asset on the asset store if you're looking for a good premade solution. otherwise you wont really find tutorials that are exactly what you want. theres tons of different ways to make a player move, and will be specific to your game
how can i see the script in kcc
cant find it on github repo
the api docs aren't going to be enough to see how everything fits together
i dont know what I dont know
why is there not just an official "make an FPS controller using newest input system" guide from Unity
why must i rely on amateur youtubers for this
its on the asset store, https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131
steve specifically is saying you dont need to. though we dont really know what your struggles are here. theres a ton of resources out there on this topic
yes they are, you should not need to learn how to learn
so first time ever unity user, which api docs do I read on how to make an FPS WASD controller
i have read the input system doc.
the obvious ones to start with are the docs on Transform, Rigidbody and CharacterController. Also not just the API docs but the manual as well so you learn the Editor side of things
Also Camera and/Or Cinemachine for your camera control
As I said, you should not need to be told how to learn
When i was just starting out, I'd skim over a few tutorials just to see what exists relevant to what I want. You're at the stage where that's pretty much all you should be learning. What exists, and what it's used for.
It's so incredibly unlikely to find any guide on making exactly what you want for movement. Unity's docs will have very simple examples to show the methods. A lot of the time that code isnt even great
i and WASD movement, with camera rotation on mouse, and jumping, using newest input system
have you looked at !learn ?
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Steve did list above a bunch of relevant things for that too
void Update() {
Vector3 move = new Vector3(moveInput.x, 0, moveInput.y) * speed * Time.deltaTime;
controller.Move(move);
}```
this happens every frame, which seems inefficient
is there a different callback to put this on
and do I have to do this * Time.delta thing? I heard that was old
What inefficient about it and what kind of other callback are you looking for?
why would I move the controller if no movement occured?
You need delta time here if you want to keep it frame rate independent.
Well, if no movement occured it wouldn't move, since a vector of 0 would be passed.
yeah I get that, still feels cheap
"move by the amount of nothing"
There might be some overhead. You can make a check and not call it of you want.
what would the check me?
the input system docs clearly state that they can be event driven
If the input is 0, then don't move it
I don't think that's a component..? You'll need to clarify what you mean.
The camera is not locked, I tried to do it manually and through a script
oh i meant it
That's a property of the camera, not a component.
But you should be able to modify it.
If you can't, then something else is resetting it.
maybe its bcs CinemachineBrain?
Not brain, but yes, cinemachine virtual camera would overwrite most camera settings, including clipping planes. You should be able to modify the parameter on the virtual camera
what's wrong with the car? why does it fall slowly and why is it flipping? yesterday it would do high jumps when it would touch the ground with it's wheels
oh yeah if I'll put rigidbodies values on these wheels to 5 or 20 it will jump
ok it falls slowly because of wheel colliders
why cant i get the public var i treid 2 thibngs
Is there any naming convention for static equivalents of methods? I'm creating some grid utilities and I want to be able to call those from the base class instance or from a particular grid type class that doesn't have an instance.
public override Vector2Int[] Rotate(Vector2Int[] initialVectors, int rotation) =>
RotateStatic(initialVectors, rotation);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2Int[] RotateStatic(Vector2Int[] initialVectors, int rotation)
{
// code
}
can I write an extension method for MonoBehavior? to have globally for all new scripts
Yes you can put any type for an extension method
where do I put this?
In your case the parameter would be this MonoBehaviour mb
I have a folder Utilities/ with a file MonobehaviorExtensions.cs
Put it in a static class, you cannot put extensions elsewhere or you'll get a compiler error
it is not finding the extension
I have it in a static class
still, my script files dont find it
If you're calling the extension from a MonoBehaviour itself, you need to do this.TheExtensionMethod()
Because extensions are lowered down by the compiler to YourExtensionsClass.TheExtensionMethod(this)
./Utilities/MonobehaviorExtensions
using UnityEngine;
public static class MonobehaviorExtensions
{
public static void Log(this MonoBehaviour monoBehaviour, string message)
{
Debug.Log($"{monoBehaviour.GetType().Name}: {message}");
}
./Assets/MyScript.css
public class MyScript : MonoBehaviour {
void start() {
this.Log() // not found!
}
}
Not found as in you get a compiler error? Or you don't get the log
does not contain a definition for 'Log' and no accessible extension method 'Log'
also it is crucial that I can type this as Log and not this.Log, otherwise I will just abandon the approach
is that not possible?
Ah yeah it's probably because you're calling it from MyScript, so it searches an extension that is declared as this MyScript.
You can make the method just static (non-extension), and put using static MonobehaviorExtensions; at the top
Then you'll be able to use Log() directly
works perfectly
public static class Extensions
{
public static void Log(this MonoBehaviour monoBehaviour, string message)
{
Debug.Log($"{monoBehaviour.GetType().Name}: {message}", monoBehaviour.gameObject);
}
}
public class MyScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
this.Log("Steve");
}
}
Yeah that actually works, so your issue is somewhere else
ugh csharp keeps formatting my curly braces
I have editorconfig turned on
which normally takes priority
@short hazel @languid spire OK but i actually need this to be a property, like a getter. No () invokation
unity is complaining about that
A property that logs when you set it? Like Log = "my message";?
no its not actually parameterized and isnt a log
its a constant number
well not a constant numbe
im making an alias delta for Time.deltaTime
I want to write delta instead.
delta => Time.deltaTime
so in a script
movement * speed * delta```
so whats the probllem
float delta { get { return Time.deltaTime; } };
Take your static class and make a public static property: public static float Delta => Time.deltaTime;
Then with using static ... it'll work
public static class CustomExtensions {
public static float delta { get { return Time.deltaTime; } }```
Note that this hurts readability since people not used to your codebase now have to look where delta comes from. I wouldn't recommend doing these things
but how does it know that it is for monobheaivor
I guess it doesnt need to be for monobehavior, but just globally accessible?
It doesn't. You have to do using static CustomExtensions; everywhere you want to use it
right... in C# you make static classes with static methods to have toplevel functions. If forgot
you seem to have a woeful lack of C# knowledge/experience
Yes I'm not a C# developer
Compiler will resolve and lower it down to CustomExtensions.delta wherever you use that
so maybe learn it first
that is what i'm doing
if your suggestion is to stop what im doing, tell my game dev team to pause for a few weeks while I go read a dry textbook on general C# constructs... then I think we have different learning styles and priorities
we're doing C# just to get unity working. we have no prior experience in it
but have worked in other enterprise OO languages.
I think we have a different concept of what being a 'professional software engineer' actually means
i've never found that sort of resource an optimal learning strategy
learning as I build has always been what works for me. Can't just read books on a programming language in the abstract, never works (for me)
how dare you be a beginner in a beginner channel... 🤔
Wasn't aware all beginners are professionals
I've worked professionally as a software engineer, I'm just new to Unity and C#. I can transfer most of my knowledge from other languages (typescript, scala, kotlin, python), just need to translate and google a bit. For sure, going through an entire C# course from scratch would not be optimal in my opinion (in terms of time spent)
you probably know more than me, and if you're not welcome, I sure as hell wouldn't be.
I think he's confusing this channel with #archived-code-advanced
i agree the tone became abrasive quickly out of nowhwere, i appreciate your reassurance
anyway i probably contributed to it too.
it made me feel unwelcome, when in reality I think a "beginner" channel is meant for us.
this is a beginner channel for using C# with Unity. It is not a channel for learning C#. There are other servers for that
if you re-read this I think you'll see the validity in my question here actually
in order for the extension method to hook onto MonoBehavior, there needs to be a this parameter in the signature
so I was confused when the other guy got rid of that
but then realized he was suggesting to ditch the "monobehavior extension" approach, and just create a global function
right, so go learn monobehaviours in a NON-unity discord? ok 👍
but this is C# basics, nothing to do with unity specifically which is why I directed you to the C# documentation
no, extension methods are not Unity specific
pauseSound?.Play();
Does anybody know why I'm getting this error even though I have a null check?
https://docs.unity3d.com/ScriptReference/Object.html
This class doesn't support the null-conditional operator (?.) and the null-coalescing operator (??).
it also only happens when changing scenes as the script that causes the error isn't even in the scene where the error occurs
ahh
right mb
do you know why this might happen though?
anyone have like a general direction for me to how to create a level system in a turnbased combat game?
if the script isn't even in the scene, how is it causing the error?
because this isnt using unitys null check, and the object isnt really null internally. unitys null will be true if its destroyed.
but the script isn't in the scene, how is this line of code even running if the script doesn't exist in the scene?
You've shown only one line so no one can really answer why its running. Could be a ton of reasons
It's not really possible to say without seeing more of the code. But put this line before the line that throws the error and see what it says right before the error:
Debug.Log($"{name} in scene {SceneManagement.SceneManager.GetActiveScene().name} is trying to play audio");
"SceneManagement"?
Actually this is better:
Debug.Log($"{name} in scene {scene.name} is trying to play audio");
Yes, that's the namespace where SceneManager is
wait ok, now it says that the scene which isn't even loaded is trying to play audio?
what's the reason for this?
Note that if you have code like this:
Debug.Log(1);
SceneManager.LoadScene("otherScene");
Debug.Log(2);
The second log will run before the scene is loaded. LoadScene schedules the new scene for loading, which won't happen until next frame, meaning the rest of the code across the objects finishes executing first.
wait even though this is really simple let me just double check, I'm loading the scene correctly here right?
SceneManager.LoadScene(0, LoadSceneMode.Single);
oh wait actually i think I understand
private void OnEnable()
{
if (!animatorManager.animator.GetBool("Death"))
{
if (playerControls == null)
{
playerControls = new PlayerControls();
playerControls.Misc.PauseMenu.performed += ctx => PauseGame(); // Subscribe to the PauseMenu input event
}
playerControls.Enable(); // Enable the PlayerControls
}
}
private void OnDisable()
{
if (!animatorManager.animator.GetBool("Death"))
{
playerControls.Disable(); // Disable the PlayerControls
}
}
So I have this code for my input system, would I have to call playerControls.Disable(); before unloading my scene or no?
because I only get the error when I try to pause
If you don't want to respond to the event while the script/object is disabled then yes you need to unsubscribe
This will also ensure a proper cleanup when the object is destroyed when you call Destroy or the scene unloads
Why is this script working in the editor but it's not working when I build the game?
using UnityEngine.Experimental.Rendering.Universal;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
public class Resolution : MonoBehaviour
{
public GameObject cam;
public PixelPerfectCamera pixelPerfectCam;
void Start()
{
if (cam != null)
{
pixelPerfectCam = cam.GetComponent<PixelPerfectCamera>();
if (pixelPerfectCam == null)
{
Debug.LogError("PixelPerfectCamera component not found on the camera!");
}
}
else
{
Debug.LogError("Camera is not assigned in the Inspector!");
}
}
public void LowRes()
{
if (pixelPerfectCam != null)
{
pixelPerfectCam.enabled = true;
pixelPerfectCam.assetsPPU = 4;
pixelPerfectCam.refResolutionX = 320;
pixelPerfectCam.refResolutionY = 180;
pixelPerfectCam.upscaleRT = true;
}
}
public void MediumRes()
{
if (pixelPerfectCam != null)
{
pixelPerfectCam.enabled = true;
pixelPerfectCam.assetsPPU = 8;
pixelPerfectCam.refResolutionX = 512;
pixelPerfectCam.refResolutionY = 288;
pixelPerfectCam.upscaleRT = true;
}
}
public void HighRes()
{
if (pixelPerfectCam != null)
{
pixelPerfectCam.enabled = false;
}
}
public void StartGame()
{
SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex + 1);
}
}
Look up 👆
I'm making wall detection system based on the normal vector.
public bool IsWall(RaycastHit hit)
{
float dotProdMapped = MathAE.Remap(-1,1,0,1,MathF.Dot(hit.normal,down.normalized)); //MathAE is just a static class with a remap function in it among other functions
return dotProdMapped < 1-(tolerance / 360) ? true : false; //tolerance is an angle in degrees
}
though for this to work I'd need a bunch of raycasts sampling normals from all over to get an average.
is there an easier way to sample multiple normals in a given direction?
void DisableRagdol()
{
for (int i = 0; i < parts.Length; i++)
{
Destroy(parts[i]);
Destroy(colliders[i]);
Destroy(joints[i]); //Line 30
}
}
This causes Index was outside the bounds of the array, at line 30, but its working as expected
Well, what exactly doesn't work? And did you debug it at all?
Look , I have 3 buttons when low res high res meduimres when i click one of those the camera gameobject options should be changed
in the editor it works perfectly
when I build the game it doesn't work at all
- It could be that some of these properties only have effect in the editor. Did you check the docs?
Can you run it with a debugger so you can see what the iteration it's throwing the exception on? And maybe check the length of the joints array, if I had to guess, it'll be off by one
- Did you confirm that the code is executed at all?
In the build. Not the editor.
Wdym? There can only be one normal in a given direction.
You confirmed that the code is called in the build? How?
debug
The length is correct
This is where its throwing, if this is what you mean
What debug?
What's the value of i when it's being thrown?
Can you tell me what to do?
How can I know if the code is being called in the editor
The easiest way would be to use the debugger. You'll need to learn how to attach and use the debugger with a build.
I need to sample a bunch of normals at different points on the terrain, sampling 1 normal would make the wall detection very inconsistent. it might think the ground is a wall because of a rock on the ground or so.
I will search that up
the only way I know how is to do a bunch of raycasts
If rocks can ultimately have the same properties that a wall has, like the same normals, then you'd need a different way to differentiate the two. For example, tags or layers, or even a specific component.
Ah I see now, everything is 10, joints are 9, I guess the length wasnt perfect after all, my bad
But if you have to, then multiple raycasts are a viable option. Is there an issue with it?
To understand what's happening intuitively:
If you have two things and you wanna connect them, how many joints will it take?
Yeah, I know, I forgot about that part
But im wondering what I can do without making another loop
doing i-1 doesnt have an effect for some reason
I mean there's spherecasts but I didn't find anything about them letting you sample all the normals inside so I just wanted to ask if someone has had to do a similar thing and found a better solution than multiple raycasts
Modify the loop condition so that it's only incrementing if it's less than all the relevant array lengths.
It might be a little ugly, but you could make the loop iterate till parts.length - 1 then add Destroy(parts[^1]) and Destroy(colliders[^1]) after the loop
That causes issues with the parts
I think ill just do separete loops, far easier
And I dont want to trouble any of you
Or if you expect that all three arrays are the same lengths, and that it's not normal otherwise, then you could add an if statement before the loops that checks the lengths and throws an exception if that's not the case.
Or use a Debug.Assert() call to do that in one line
Hey, Im trying to add characters in the project but for some reason it wont show in the sprite section and I cant add it as an component. Any idea what im doing wrong?
Sorry if the picture isnt really clear I took it from my phone cuz otherwise you wouldny see it all
not a code question. also https://screenshot.help
and you need to make sure your texture's import settings are correct
i can take a screenshot but then you wouldnt see the sprite thing bevause it clicks away
where do i ask my question?
Ok ill ask it there
if you plan to ask your question in a more relevant channel, then be sure to show the import settings for the sprite you are attempting to use
hi yall
i turned on Convex for the MeshCollider, and now my player cant get inside of the mesh? its like when I turned Convex it covered the hole part......
not a code question, but that's exactly what happened.
correct. you need to split it into multiple different objects, each being convex (like each wall separately)
gulp
guys help im trying to make the bullet go to the midle but it goes a little left. here is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerShoot : MonoBehaviour
{
public Transform gunBarrel;
private float bulletSpeed = 100f;
public Camera playerCamera;
[HideInInspector] public Target target;
public void Start()
{
target = GetComponent<Target>();
}
public void ProcessShoot()
{
Debug.Log("Player Shoot");
GameObject bullet = GameObject.Instantiate(Resources.Load("Prefabs/Bullet") as GameObject, gunBarrel.position, gunBarrel.rotation);
bullet.transform.Rotate(0, 0, 90);
Ray ray = playerCamera.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
Vector3 targetPoint = ray.GetPoint(1000);
Vector3 direction = (targetPoint - gunBarrel.position).normalized;
bullet.GetComponent<Rigidbody>().velocity = direction * bulletSpeed;
}
public void DamageTarget(int damageToTarget)
{
target.life = target.life - damageToTarget;
}
}```
and here how it does please help
why not use the bullet.transform.forward as the direction for setting the velocity
because I dont have my gun barrel in the center of the cam
so you need your bullet to Look At the targetpoint first
but how? set the rotation?
yes
how do I get it?
thx
Let’s say I am trying to use post processing… the glow effect shows on the scene but not on the game screen… any idea why?
not applied to the camera maybe?
maybe if u press play?
i have no idea but why is my MeshCollider not moving with the object?
Smh post processing wasn’t checked in the camera setting
You could also just make the shape out of couple box colliders, 5 in your case should do
can u show video?
is there like no better solution than that?
No. non-convex dynamic bodies are not supported so you must make the collider out of multiple colliders, those can be convex mesh colliders, box colliders, etc.
oh make sure to check collision detection to continous in the rigidbody
maybe continous collision detection will work with convex collider
mesh collider
what difference would that make in this case?
ive had that sometimes i just go through colliders and with continous collision that never happens
he is not suffering from any tunneling issues as far as I'm aware
ah ok sry i understood the issue wrong
Having trouble with one of brakeys tutorials, https://www.youtube.com/watch?v=jvtFUfJ6CP8
In the tutorial, I can't get the grid box to appear TS: 3:10
Does anybody know what could be going wrong?
Let's learn how to make 2D pathfinding using A* with and without code!
● Check out Skillshare! http://skl.sh/brackeys17
● A* Pathfinding Project: https://arongranberg.com/astar/
····················································································
❤️ Donate: https://www.paypal.com/donate/?hosted_button_id=VCMM2PLRRX8GU
► Join...
Show a screenshot of your editor
private bool spoilable = true;
private void Update()
{
if (this.transform.rotation.z == -90 & spoilable == true)
{
spoilTrash(1);
spoilable = false;
Debug.Log("spilled");
}
if (this.transform.rotation.z == 90 & spoilable == true)
{
spoilTrash(2);
spoilable= false;
Debug.Log("spilled");
}
}```
Im a bit confused, this did work before without the spoilable bool
the spoiable is true in the beginning, at first i thought i used it wrong since i only wrote & spoilable
that will never have worked
Weird, it did use the function though just unlimited
Whats wrong with it? Okay tbh it was >= 90 and <= 90 before
nah, rotation is a Quaternion not Euler angles also never check a float for equality
Yeah the description of Quaternion already scared me but i just wanted to check if it rotated
rotation.z will not contain the values you are expecting
Give me a hint where to look
Oh i thought im completly wrong with my approach
hi ive tried playing with the code but i didnt manage to do double jump can u plz help me fix it ?
https://paste.ofcode.org/bEQtdgYgUf772Z4ynCpvRJ
im using rigidbody for the physics
and the new controls script
playerInput.CharacterControls.Jump.started += onJump;
playerInput.CharacterControls.Jump.canceled += onJump;
to
void onJump(InputAction.CallbackContext context)
{
isJumpPressed = context.ReadValueAsButton(); //if jump press true
}
void handleJump()
{
if (isJumpPressed)
{
if (grounded)
{
rb.AddRelativeForce(Vector3.up * 10);
countJump = true;
//ChangeAnimationState(PLAYER_JUMP);
}
else if (countJump)
{
rb.AddRelativeForce(Vector3.up * 10);
countJump = false;
//rb.AddRelativeForce(Vector3.down * 3000 * Time.deltaTime);
//ChangeAnimationState(PLAYER_JUMP);
//Debug.Log("JUMP!");
}
}
}
private void OnCollisionEnter(Collision collision)
{
grounded = true;
countJump = false;
}
private void OnCollisionExit(Collision collision)
{
grounded = false;
//countJump = 1;
}
Thank you, this did work!
Please properly share your !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Also, your question is very vague. What exactly does not work? Does it not call a certain method? Please try pinpointing what exactly doesn't happen as part of debugging
For example, try logging isJumpPressed, countJump and grounded
Try logging methods in general to see if they are called
Please share those results so we can continue pinpointing the issue
still didnt work
saying it didnt work doesnt solve anything
this is the last ver ive worked on
https://paste.ofcode.org/GRRcmYeU8SEKFr4GxXb2Mu
ive tried working on the ground fuction
private void OnCollisionEnter(Collision collision)
{
grounded = true;
//doubleJump = false;
}
private void OnCollisionExit(Collision collision)
{
grounded = false;
}
didnt work
ive tried working on void handleJump() function didnt work
ive tried working on void onJump(InputAction.CallbackContext context) didnt work
did you not see what Fused even said? #💻┃code-beginner message
im at lost
show your debug results
and still, saying "it didnt work" solves nothing, tell us how it didnt work, what didnt work
i got no debugs
you just said you debugged
i mean at the console
what, what did you debug to the console?
https://prnt.sc/3getjPH8_zFg all this debugs are diffrent script that not in use
mine called testerMoveSet