#💻┃code-beginner
1 messages · Page 240 of 1
this object should be a singleton
ok
Oh my bad I missed that part
Yes but that means you always have to start in scene 1
ik
you could properly set this as a singleton so you'll be able to add it in every scene and always have one available wherever you start from
really they should hit the introductory learning content and understand references better
it sort of works i think
let me explain
my player is not moving
set force is equal to 2000
well double check your player is correctly being referenced by this
since am 99% sure it is not
And does your player actually use the setForce variable from this object
i think it is but the problem is foward force is 0 but setforce is 2000
no
so then why are you expecting it to be using setforce when it's not using setforce
because i said in my code that setforce is equal to foward force
Just started my first project with Unity and my Object doesn't jump with space bar. Can you guys find out why?
`public class birdscript : MonoBehaviour
{
public Rigidbody2D myRigibody;
public float flapstrength;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) == true)
{
myRigibody.velocity = Vector2.up * flapstrength;
}
}
}
`
where and when
i think ur trying to ride a horse after you've seen one for the first time in ur life 😄
Show the inspector of this object
Okay, so the very first frame that this object exists, you set the current PlayerScript's forward force to whatever setforce currently is
Is this object's setforce equal to 2000 on the first frame this object exists
yep
yes
Really? How?
no. That's why I'm confused
anyone knows how to do this?
Show the console after you start the game and press space
okay its not actually but i dont know why
The real question: Why do you think setforce is 2000 on the very first frame this object exists
So there is an error but I don't know how to fix it
i just told u
read the error message
assign it
because why not
Okay thank you guys
drag the object with the rigidbody into the slot for the rigidbody u created
The variable myRigidbody of birdscript has not been assigned. You probably need to assign the myRigidbody variable of the birdscript script in the inspector
i mean on the previous scene i set the object already to 2000 so i would expect it to stay like that
That's not how code works. It doesn't just do things for no reason
How are you setting this to 2000 before the first frame this object ever exists
Start runs on the first frame this object exists and that is the only time you set the player's force
oohh u mean it like that
Yes of course I meant it like that that's why I said it
multiple times
I though u meant it as the first frame this object exists in the second scene
Thank you
Thank you
well doesnt void start() run every time a new scene starts
no
it runs the first frame this object exists
that's why I am very specifically using those words in that order
no.. it doesnt run its start ever again. just the first frame it exists
ahh digi beat me to it
oh i think i could get away with that since i was using 2 different objectc for 1 script but now with that ddol it doesnt work like that
ok well now that u have helped me with that
what do u suggest i do
nope.. thast whats magic about it.. u can have ur gamemanager exist thruout the project
Use a singleton
and then have your player just use the value from the singleton directly
and not have its own copy of the variable
whats a singleton
Look at the singleton page
That thing I sent you a link about and told you repeatedly to use but you said you didn't want to
ok
its a script that exists (only once) can't have copies.. soo therefor u can make a reference to it. that any script can access at anytime.. anywhere
but before i read it would u also reccomend i put PlayerScript.fowardForce = setforce; on a void Update
like would that also work
yea ig
Stop trying to staple bandaids to this system and instead consider actually doing it right
Game Settings are kind of the poster child use case for a singleton
mate chill im just asking for future reffernce im not trying to stick bandaids into anything
so read the article I linked and learn
im just trying to become more familiar
Yes it would work
well, i'll suggest when u see these new words... like DDOL, additive scene loading, singleton, etc u look them up
reading about them yourself is gonna be the best way to become familiar
ok
Probably you shoudl learn a little bit more about C#, that would answer many of your question because they dont have anything to do with unity but more like programming
anyways thanks for the help and i will update u guys soon
good luck 🍀
forwardForce is a public property that can be assigned to a certain value
tbh i knew what a bunch of these things where but i quite programming for like 4 years and im trying it again but i kinda forogt everything
should be easy to refresh urself then
well, if you don't know if you can assigne a value of a property it seems that youre knowledge, regardless how many years you did this before, equals to zero 😅
so... maybe get a quick code of c# on youtube
electrocutes it
think of static as meaning that thing is part of the class itself rather than a property on an instance of that class
how would you check if there's something between two objects? basically, i want to make an enemy script and if the enemy can clearly see the player the enemy follows the player
use a raycast!
Or a linecast if you're using two objects specifically
or, in this case, consider using Linecast
A raycast shoots a ray from a point in a direction
A linecast draws a line between two points
Both look for colliders that hit the ray or line
Ah, there is a difference -- the Raycast page says it ignores colliders that you start inside of, whilst Linecast doesn't say that
I wonder if that's actually the case, though...
I should definitely be using Linecast more. I have a fair number of places that calculate a ray between two points
What's the ideal setup for interface component searching in Update()? Layer masking a gameobject with a single component and interface? It shouldn't matter what this script contains beyond the interfaces, right?
I was also thinking doing it by unity tags and doing lookups.
oh and getting interfaces from that
really would just do it the easy way and see if you have any issues
like get your stuff and look for the component you need or interface type of what ever
if it causes a problem would then implementing some caching
The script is by far the worst performant one I've got, but this ability system is kind of the main feature so it's expected.
like for rapid fire weapons in the past i would have a dict that maps colliders to components
btw overlapsphere make sure you're using the nonalloc version, the former is hella expensive
that way i am not doing constant GetComponents
So you've got a persistent area of effect that's hitting tons of stuff?
Yeah, my ide yells at me if I don't use them
also for a persistient area i would use a regular collider
good ide!
Consider using trigger enter and exit to keep track of what is and is not being affected
then keep track as things enter and exit
jinx
ah need a good fist bump emote
that does seem smart, but say a fireball that doesn't collide but does constant damage every 0.1 seconds
and moves forward
just make sure the fireball is moving in a way that the physics system can understand!
and adds thigns to a hashset to do damage to
so, don't set its transform directly
and removes them on exit
Sound like an idea. I do like queueing my own physics checking methods, but if that's more performant I'll look more into them
i have, the ai (basically starting point) and the player (end point)
so i should use linecast?
if you are really deadset on the checksphere, would use the non alloc version, would make sure its not checking more objects then required using the masks and would create a mapping of collider to component to access that way it avoids repeated GetComponent calls
but i think the collider approach is better overall
I tried this mapping thing once, was surprisingly not more performant than GetComponent if I have just 1-2 components... but it was a long time ago and I may have messed it up
May end up throwing rigidbodies on them anyway just for the interpolation checking
All in all, the profiler is your friend (or the Stopwatch guy)
yeah maybe dict has too much overhead, in the case of a machine gun type weapon what i have done in the past was on first hit, save both the collider and Damageable component to fields, then on each hit, check if the collider matches first if yes skip the get component
📃 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.
oh
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEngine;
public class PlayerShip : MonoBehaviour
{
public float shipSpeed;
private GameObject enemyShip;
private float _distance;
private Rigidbody2D _rb2d;
// Start is called before the first frame update
void Awake()
{
_rb2d = GetComponent<Rigidbody2D>();
enemyShip = GameObject.FindWithTag("enemy");
}
// Update is called once per frame
void Update()
{
Move();
}
private void Move()
{
//transform.LookAt(Vector2.up);
_distance = Vector2.Distance(transform.position, enemyShip.transform.position);
Vector2 direction = enemyShip.transform.position - transform.position;
direction.Normalize();
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg - 90;
if (_distance > 10)
{
_rb2d.AddForce(direction * shipSpeed, ForceMode2D.Force);
transform.eulerAngles = Vector3.forward * angle;
}
else if (_distance <= 10)
{
float randomNumberX = UnityEngine.Random.Range(-50, 50);
float randomNumberY = UnityEngine.Random.Range(-50, 50);
Vector2 movementsmth = new Vector2(direction.x + randomNumberX, direction.y + randomNumberY);
float angle2 = Mathf.Atan2(direction.y + randomNumberY, direction.x + randomNumberX) * Mathf.Rad2Deg - 90;
for (int i = 0; i < 4; i++)
{
_rb2d.AddForce(movementsmth, ForceMode2D.Force);
transform.eulerAngles = Vector3.forward * angle;
}
}
}
}
alr so basically
is there a way to make it so that the things in the if statement dont happen while the things in the else if statement are happening?
why when i instantiate an object, it creates a clone?
yes
is there an example? i think im doing something wrong, the enemy just always follows the player
like can i make it so that it finished doing the else if statement
even if the if statement is true again
thats already how it works
it doesnt though
what is the (clone) item
dunno
then set a bool and add it to the condition
where
Fen shared the docs for linecast up above
after the for?
explain what you want better, with a if/if else only 1 or 0 branches of it will run at a time. if you want it to only run a branch only ever once. you set a boolean saying you run it, then check for that in the future
so basically what i want to do is that while the else if statement is working, the if statement doesnt work even if its true again
i have this code but for some reasone the enemy moves when i am inside him???? i am clearly dumb
so in the if else branch set something like hasRun = true
then in the if add a !hasRun && _distance > 10
obviously use names that makes more sense for what it means to your game
but the idea of it
it can jsut be a field on your class
private bool _hasRun; or something like that at the top of the class
iirc if both the start and end of a line or raycast are inside the same collider
it will not detect the hit
Probably wanna use a layermask and validate what hit is.
As fen said, I believe that both the player and enemy can trigger the linecast
you're not doing anything when the linecase doesn't hit here
so if it was previously able to see the player, and now isn't hitting anything, it will continue to folow
there are basically three cases:
- Your linecast hits NOTHING
- Your linecast hits something that IS NOT the player
- Your linecast hits the player
you need to handle all three cases, not just two of them
i really need help ngl
do you have a separate Capsule Collider from your CC?
Yeah
There's one on the playerobj and one on the emptyobj named "Player"
you should not
there should only be the CC, not a separate capsule
oooh alrighty
the playerobj still seems to be in the same place and not come back up with the CC
and the radius seem to be skinnier for some reason
after crouch i mean
using System.Collections;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
public Sprite tile;
public int worldSize = 100;
public float noiseFreq = 0.05f;
public float seed;
public Texture2D noiseTexture;
private void Start()
{
seed = Random.Range(-10000,10000);
GenerateNoiseTexture();
GenerateTerrain();
}
public void GenerateTerrain()
{
for (int x = 0; x < worldSize; x++)
{
for (int y = 0; y < worldSize; y++)
{
if (noiseTexture.GetPixel(x,y).r < 0.5)
{
GameObject newTile = new GameObject(name = 'tile');
newTile.AddComponent<SpriteRenderer>();
newTile.GetComponent<SpriteRenderer>().sprite = tile;
newTile.transform.position = new Vector2(x,y);
}
}
}
}
public void GenerateNoiseTexture()
{
noiseTexture = new Texture2D(worldSize,worldSize);
for (int x = 0; x < noiseTexture.width; x++)
{
for (int y = 0; y < noiseTexture.height; y++)
{
float v = Mathf.PerlinNoise((x + seed) * noiseFreq, (y+seed) * noiseFreq);
noiseTexture.SetPixel(x,y, new Color(v,v,v));
}
}
noiseTexture.Apply();
}
}
"tile" not 'tile'
Can someone explain how to get rid of the clone object "DataManager(Clone)" that is coming from this method:
`public class MenuController : MonoBehaviour, IDataPersistence
{
[SerializeField] private List<GameObject> persistentObjectList = new List<GameObject>();
[SerializeField] private List<string> persistentNames = new List<string>();
public static DataPersistenceManager dm;
private void Awake()
{
if (GameObject.Find("DataManager") == null)
{
GameObject newDm = new GameObject();
newDm.name = "DataManager";
newDm.AddComponent<DataPersistenceManager>();
newDm.GetComponent<DataPersistenceManager>().GetInstance().SetFileName("game_data.json");
Instantiate(newDm);
}
else
{
GameObject temp = GameObject.Find("DataManager");
dm = temp.GetComponent<DataPersistenceManager>().GetInstance();
}
}`
why Instantiate if you dont want a instance of it then?
The Instantiate(newDm) is what's doing it
Instantiate creates a copy of the object you pass to it
basically i want to check the scene is there is a datamanager
then if there isnt, create one
If you don't want to clone it why are you cloning it
Doing new GameObject() already creates the object in the scene for you
i still need help with this please , i was jsut following this tutorial https://youtu.be/-XNm7dPVVOQ?si=2T1G51VgZE91fn3e
Welcome to part 4 of this on-going first person controller series, int this episode we're going to be covering how to crouch and stand effectively while also amending our movement speed WHILE we're crouching and also taking into consideration any obstacles above us before we stand back up!
Join me and learn your way through the Unity Game Engin...
You never change the center back to 0,0,0
You've cropped those out of your video, what are those set to in the inspector
oh my god , it was 2f and not 0 😭
these type of mistakes are the death of me
It's also serialized so the value in the code doesn't matter, what is it in the inspector
i put it to 0 dw
it works nice now so thats good
now how do i shrink the player when crouching and then the player grows back up , i already tried these
That should work but it's instant, you're not doing any sort of smoothing on that, which means you can probably take it out of the loop
Which one of the pics should work tho
Do you want a condition or not
Does it matter if it's a condition or not?
I literally cannot answer this
Do you want it to be conditional or not
Nope
This is not a "good code bad code" thing this is literally "what do you want the code to do"
If you don't want to conditionally change the height, then don't change the height conditionally
If a kinematic and static body collide, will OnCollisionEnter be called?
Thanks!
Darn, that creates an issue, I have something that I need to manipulate like a kinematic body (only explicit movements, no physics simulation), but also doesn’t go through a static body
Then you'll need to slap a rigidbody on the other thing
On the static body?
The non-kinematic one will need to have a rigidbody on it as well. If you're in 2D I think that rigidbody specifically needs to be "dynamic" but in 3D a "static body" is just a collider with no rigidbody
Is there a way to stop all of the physics simulation from occurring on the dynamic rigidbody? I need it to be able to collide/not go through other physics bodies, but nothing else
You could try freezing all position constraints
That would work. So if I have a wall and a ball that would bounce off it, but neither do physics simulation, I make the wall a dynamic rigidbody, freeze position contraints, then make the ball a kinematic body?
Possible. 
Will do, thanks

so I'm trying my hand at a character creator app for a table-top rpg and I'm trying to deal with abilities ("Competencies & Specialisations") - I've got an issue where my list of Competencies is being called multiple times (the list is initialised in an Awake method) & I can't think of how to debug it. I've got another issue where the competency variable is supposed to be 'got' from the list index, but my debugs are generating Null Reference Exceptions on the variable and I again can't figure out how to check for the variable having an assigned value. Not posting code until I'm asked for it
Any insight welcome
I simply just want the player scale to shrink to 0.5 and then go back to the normal scale
So do what you're currently doing to change the Character Controller height, but change the scale instead
The scale of the playerobj , right?
If that's what you want to change the scale of yes
Alrighty then
https://i.imgur.com/JqEiDTG.png
https://i.imgur.com/eq3RThV.png
the errors are only appearing at run-time
https://i.imgur.com/RwjEgEc.png
oops
sorry
!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.
Show Competencies.cs
define "Large Code Blocks" XD
this is all from Competencies.cs
If it's more than about three lines
Just send the full class on a bin site
I'd have to organise a bin site to dump it to
sorry
https://hastebin.com/share/etuhezuwos.java
apologies - I'm kinda sure it's the competency variable that's the culprit
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
how can i make arrow point towards the velocity direction? considering its face is not the arrow tip
So, line 128 is a curly brace. Is that the most recent error? Clear the console and run it again, what line does it show the error is on?
You can set transform.foward, transform.right, or transform.up to a direction and it'll rotate the object in that direction. Find out which direction of the object you want to face "forward" and set that direction to the velocity direction
https://i.imgur.com/YbH0H7G.png
I hope this helps
So, if the error still says line 128, either you're missing something from the bin or you haven't saved a change because that line doesn't have anything on it
i would need to multiply rb.velocity with transform.up?
As I said, you can just set one of those direction vectors to velocity and it'll point that vector in that direction
Which direction of the arrow do you want to point in the direction of velocity
https://i.imgur.com/2widwwT.png
it's the debug line itself - if I use 'competencyTitle' by itself the code runs fine, but the debug logs have a blank space where the title should be
the tip
i dont know exactly how to explain
Is that Up, down, left, right, forward, or backward
up
Then set transform.up to velocity
So competency is null which means there's a null in the list somewhere. The list is public (and static) meaning it can have an element added to it from anywhere and the issue might not be in this script. Try logging the index and competency as you get it in the loop
is there a way to make it turn a little more smoother?
Instead of setting it to the value, Slerp it towards the value
https://docs.unity3d.com/ScriptReference/Vector3.Slerp.html
ooh thanks
"Try logging the index and competency as you get it in the loop"
There's a loop?!? A sound suggestion, tho
Sorry, the if statement. I lost Internet on my PC so I'm on mobile and it's difficult to switch back and forth
Although looping over it and printing them all would be a good debugging step
int he editor for sprite renderer, is "Order in layer" the same as <SpriteRenderer>().sortingOrder
bummer about your connection - it be like that sometimes
a debug returning the index works, returning 0 - but the competency.competencyTitle still returns void
So that'd mean that the first thing added to this list is null
In Awake, add this:
foreach(Competency c in competencies){
Debug.Log(c);
}
See if anything's in it before you add all the other stuff in awake
gotcha
oh, dear - that's a lot of null XD
So, something is adding in a bunch of nulls before any instances of this script are added
look for other scripts that reference the competencies list
Wait, hang on a tick:
Why is your competency object a child object of your Competencies list
Competencies is a Monobehaviour, you can't create instances of it with new
You should have been getting a ton of warnings about that
you'd think so, but no
Can you send a screenshot of your full console, including the bit at the top and the scroll bar
the full console generates 720-odd reaferences by the time I reach the relevant debugs, but sure
https://i.imgur.com/Bnwe3az.png
more, or less?
Hm, there should definitely be warnings about creating a MonoBehaviour with new. Still, there's zero reason for your Competency objects to extend Competencies. You can't create them with new, so you're going to get null out of it
yeah, I think I see what you're getting at...
so I changed the code to make the Competency child class redundant, but I'm still getting null for my debugging c
As Tank Girl so elegantly said "this might take me a really long time"
So is Comptency no longer a MonoBehaviour
as I said, Competency is no longer an issue; I'm working with Competencies only
I commented out the Competency class
Then what is the list of
the list is now a list of Competencies - there's no child class of Competency anymore
not that that's helping me...
that is confusing naming
You'd think it's plural of the same object
why
generaly if giving something a plural name, it will be for a collection
or a object that contains many of something
Why does this object contain a list of itself
How are you adding itself to the list since you can't create itself with new
...you think I shoulda stuck with the child class?
What do you want this list to contain
I would like the list to be a list of skills that a character can acquire
I want this list to contain functional code XD
Okay, so what is a skill that a character can aquire
what represents that concept in your code
so want each one to be able to define some functions?
I'd hazard a guess & say that the skill a character can acquire is an object..?
I dunno. You tell me
yeh
Is it a GameObject, a ScriptableObject, a string, a POCO, an enum
it can be a lot of things
also how much stuff is the same between skills
wtf is a POCO?
sorry, I'm still fresh out of noob-school
just a regular C# object
Plain Ol' C# Object
not a monobehaviour
As in not inheriting from anything, just a class with data and maybe some functions
how much do skills have in common vs not in common
more not in common than in common, from my experience
not to say that they have nothing in common...
so make a base class that repersents the most generic version of a skill
then have other classes extend from it, for the more concreat versions of the skills
that can override methods
that would be my Competency class
kinda what I had in mind
I need a break - thanks for your input, @shell sorrel , @polar acorn
"You've given me a lot to think about" XD
its always good to take breaks, gives you time to think about stuff in the back of the mind
how to I reference this aka add a new item to this in event trigger via script
purpose: when unit health reaches 0, it should get destroyed
error: as soon as i start the game, literally all the units get destroyed aka the game objects get deleted. does anyone know why this is happening?
debug.log everywhere you set health
^ as soon as i start the game
its happening to both player n enemy units
idk where the problem is
if you want to post the script on a pastebin site, go for it because there's nothing here that shows you setting the health
wait i kinda found the error still need help tho
problem is, base health has values but when game starts the current health is still 0, it should be equal to base health
what's the solution for this?
time to debug baseStats.health then
it's less likely an editor error and more that you're setting it incorrectly in your code
not sure if this part of the code is the problem but i'll just put it here anyway
so your baseStats is a scriptable object, where are you referencing it and how are you using it
here
right, but you aren't setting baseStats.health at all right? You're just serializing it to the script and using that exact instance?
I don't see where you're creating an instance of base though
oh, that could be a problem
just to test something, remove everything from Base and put it directly into UnitStatTypes
otherwise, create an instance of Base inside of UnitStatTypes
and serialize that
help please
public class UnitStatTypes : Scriptableobject
{
[field: SerializeField] public Base BaseData { get; private set; }
[Serializable]
public class Base
{
[field: SerializeField] public float health { get; private set; }
}
}```
what do i do with that
its a multiplayer package
Beat me to it. Remove that
thats wrong.. the syntax is wrong
its multiplayer
thanks, what's next
doesnt matter... its written wrong..
Yes but randomly writing the name of the muliplayer package doesn't make sense
We know. Photon is very popular
debug the health that it's set in start
But that is not how you use it
What does it matter? It being multiplayer package doesn't change C# syntax
namespace Photon.VR
{
[CustomEditor...
there shouldnt be random text between two opening brackets like that
like this?
No
now ur brackets missing..
Just the word photon needed to be removed
You should... probably learn c# before attempting multiplayer
gettin these errors can u refine the code u made a bit
I super highly strongly recommend to stop right there and do some C# basics learning before even thinking about multiplayer.
alr
If you keep doing what you do with your current level, not only you're gonna fail, but people would refuse to help you too.
using UnityEditor;
using UnityEngine;
namespace Photon.VR
{
[CustomEditor(typeof(PhotonVRManager))]
class PhotonVRManagerGUI : Editor
{
private Texture2D logo;
}
}```
make sense??
my code is fine, if you've more variables add them or hide them for now
ya
I'm always trying to beat u to the punch... u always sooo fast >8)
now this showed up
I guess you didn't listen to what I said...
😔
same error
Wherever you're setting the SO can you write this:
public UnitStatTypes statTypes;
public void Start()
{
Debug.Log("Health is: " + statTypes.BaseData.health);
}```
yeah 1 sec i have to amend the code
there's a reason I've got private setters there
how would you amend this?
Dont return by UnitStatTypes, just send the full reference
oh ok you're writing to the SO it seems?
im guessing you were just writing to a single instance of an SO and reusing that single instance everywhere
👍
so why exactly are you setting the stats in the inspector, but then set them to another value in code?
wait no im not tryna do that im just setting em in the inspector and then making another variable and setting the current health as the base health when booting the game
currentHealth = baseStats.health; ```
just like this
that's the aim anyway but it doesnt seem to be working
Set the return type to just UnitStatTypes for GetUnitStats
okay, still with the code u provided above?
yeah
then change your PlayerUnit to have a field of UnitStatTypes
instead of Base
so this way they get the instance of the SO instead of just the nested class
gotcha, what am I replacing in the red swiggles
basically, serialization issues with the nested class and you're trying to access it directly instead of using the actual instance of the SO (or rather you're creating independent instances of the inner class? idk but you shouldn't need to reference by these inner classes)
so if unit has Base instance it needs a UnitStatTypes instance
ah okay
does it need to be a nested class of an SO?
its 2am rn gotta wake up at 8 so ima go now but i appreciate the help and ill let u know once i solve so u wont be left hanging @timber tide thanks for the help
probably not for their requirements but I just wanted to show a better way to serialize it if that was the problem
how do I make 2 seperate events, right now im getting the hover and down function when i mouse hover
public void AddEventData(GameObject newObj)
{
List<EventTrigger.Entry> events = new List<EventTrigger.Entry>();
newObj.AddComponent<EventTrigger>();
EventTrigger trigger = newObj.GetComponent<EventTrigger>();
EventTrigger.Entry entry1 = new EventTrigger.Entry();
EventTrigger.Entry entry2 = new EventTrigger.Entry();
events.Add(entry1);
events.Add(entry2);
entry1.eventID = EventTriggerType.PointerEnter;
entry2.eventID = EventTriggerType.PointerDown;
entry1.callback.AddListener((data) => { OnPointerEnterDelegate((PointerEventData)data); });
entry1.callback.AddListener((data) => { OnPointerDownDelegate((PointerEventData)data); });
foreach (EventTrigger.Entry e in events)
{
trigger.triggers.Add(e);
}
}
public void OnPointerEnterDelegate(PointerEventData data)
{
Debug.Log("OnPointerDownDelegate called.");
selectorController.Hover();
}
public void OnPointerDownDelegate(PointerEventData data)
{
Debug.Log("OnPointerSelectDelegate called.");
selectorController.Select();
}
Are you sure you want to be adding both delagates to the same event entry?
im not sure how it works
if (result == 1 && bacResult.banker == 6 && history.bac_type == int.Parse(BacOption.nonCommision))
{
Text text = gameObject.GetComponentInChildren<Text>();
gameObject.GetComponent<Image>().sprite = BW6Hframe;
text.text = LanguageDataScript.Instance.AssignJsonKeyToContent("BANKER_WIN_6_HALF");
if (LanguageDataScript.Instance.LanguageCode == LanguageDataScript.LanguageCodeRes.ENG)
{
text.fontSize = 42;
}
else
{
text.fontSize = 36;
}
}```
this code has a "invalid AABB in AABB" error
and that error wont even tell me why and whats wrong
What line?
this is the error, very special, no stacktrace at all
thats all of it
and because of that, the function has broken
i know where it is just because it happened after i made the code above
It's coming from a scroll rect. Does that give any clues? Anything in that code related to scroll rect?
not at all, the UI with this script doesnt even have a scroll rect
and all related base class and subclasses dont even involved in doing scroll rects
Do you have a UI that does have it?
I've been plagued by this before in a UI-heavy game, it's a very unhelpful error message - disabling/enabling UI elements at runtime can help locate what's causing it
can you ignore or suppress this warning?
this doesnt make sense in my case, because all i added is just a boolean to the code
and that boolean is checking a server data (integer) , and comparing it with an enum
the times I've had it, it's been some scroll rect/UI element set to a width of -0.0008 or something silly
before i added that boolean, everything works fine
yo WTF
git sourcetree has new commit
Finding the scroll rect that causes the error would be the first step to fixing it.
Maybe.🤷♂️
the commit has a change in one of the main UI
nope
that commit doesnt even do anything
i reverted or pulled the changes , both not working
i gonna delete the boolean, to see if a checking of an integer really screw this up
ok
cant
You don't just check bool/int though, you set sprite, text and font size. All of these could be related.
the error happened only 20 min ago, the changes of the sourcetree might be the biggest suspect
because the UI it changes are the parent of this one
and that change commited 10 min ago
Well, ui elements can affect each other depending on the setup.
So, even small changes like adding text, could be affecting elements on the other side of the canvas.
I'm in a situation where I have to use NuGet to install a package for a Unity project. I've never used the package manager before, and I'm confused as to what checkbox I need to tick to install the package
If I don't have anything checked, it won't let me install it. Do I have to check everything (Project)?
My capsule flickers and shakes when it goes on the side
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class ColliderTrigger : MonoBehaviour
{
public LogicScript logic;
void Start()
{
logic = GameObject.FindGameObjectsWithTag("Logic").GetComponent<LogicScript>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
logic.addScore();
}
}
This code tells me :
Error CS1061 'GameObject[]' does not contain a definition for 'GetComponent' and no accessible extension method 'GetComponent' accepting a first argument of type 'GameObject[]' could be found (are you missing a using directive or an assembly reference?)
Not sure what this is telling me. I've used GetComponent often and never ran into an error like this.
Read it carefully
You're trying to call GetComponent on an array
Which naturally doesn't make much sense
I'm following a tutorial and this is the exact code he wrote and worked though. Hmm
It's not
You wrote it wrong
You used the plural version of FindGameObjectsWithTag
👀 scary . . .
I'm using coroutines to time movement between transform.Translate, but when I stop it upon colliding with ground, it moves once more before stopping, code below.
using System.Collections.Generic;
using UnityEngine;
public class FallingBlocksScript : MonoBehaviour
{
public bool DoneMoving;
public bool CanMove = true;
public float BlockFallDelay = 2.0f;
// Start is called before the first frame update
void Start()
{
StartCoroutine(FallDelay(0.0f));
CanMove = true;
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
{
CanMove = false;
Debug.Log("BlockTouchingGround");
StopCoroutine(FallDelay(0.0f));
}
}
IEnumerator FallDelay(float v)
{
if (CanMove == true)
{
yield return new WaitForSeconds(BlockFallDelay);
transform.Translate(0, -0.5f, 0, Space.World);
StartCoroutine(FallDelay(0.1f));
}
}
}```
I can provide a video if needed
well yeah you start a new coroutine
you have a parameter for the coroutine, but it's not used within the method. also, you start the same coroutine with a different value for the parameter inside of the coroutine . . .
You should store it in a variable of type Coroutine if you want to stop coroutine
Alright
so theres a checking being faulty, resulting a variable become 0
the width and the posx of the UI depend on this variable
ty
so if posx or width / 0 , they become infinite
Although I thought it should be stopped as soon as it touches the collider because of StopCoroutine?
You have to store it inside a variable to stop it, otherwise it doesn't know which to stop.
You can do either IEnumerator or Coroutine.
Dividing by 0 is bad obviously
boxWidth = ((m_BGRectTransform.rect.width - 10 * 2) / m_columnNum) - 3;
winnerHighlightWidth = boxWidth + 20;```
m_columnNum is 0 , because bool failed
Maybe use a Max with (1, m_columnNum), to avoid this kind of situations. Or just don't set the width at all if it fails.
{
m_columnNum = m_betDetails.GetComponent<BacBetDetails>().m_columnNum;
}
else
{
Debug.LogError("m_columnNum error! value cannot be 0");
}
``` i gonna pop an error instead
so i know whats wrong
ok ty
Am I doing it right?
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class FallingBlocksScript : MonoBehaviour
{
public bool DoneMoving;
public bool CanMove = true;
public float BlockFallDelay = 2.0f;
private IEnumerator crouton;
// Start is called before the first frame update
void Start()
{
CanMove = true;
crouton = FallDelay(BlockFallDelay);
StartCoroutine(crouton);
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
{
CanMove = false;
Debug.Log("BlockTouchingGround");
StopCoroutine(crouton);
}
}
IEnumerator FallDelay(float v)
{
if (CanMove == true)
{
yield return new WaitForSeconds(BlockFallDelay);
transform.Translate(0, -0.5f, 0, Space.World);
StartCoroutine(crouton);
}
}
}```
nope
wait nvm u did it in start
normally i wont cache it into a variable, i will just call it like a function with startcoroutine ,
wdym
do it directly like this
how do you stop it then
doesn't have to be endless, you can stop if something is taking 7 seconds but you want to interrupt in 3
oh nvm your msg disappeared lol now minelooks out of context
dw im here , thats enough lol forget about the disappeared text
don't worry, i seen it. i'll vouch for you . . . 😆
so what's happening now instead?
you forgot to assign it again to StartCoroutine(crouton); in FallDelay
I ended up rewriting it a bit differently and it just seems to be working
using UnityEngine;
public class FallingBlocksScript : MonoBehaviour
{
public bool CanMove = true;
public float BlockFallDelay = 2.0f;
public float BlockFallDistance = 0.5f;
private Coroutine fallingCoroutine;
// Start is called before the first frame update
void Start()
{
fallingCoroutine = StartCoroutine(FallRoutine());
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
{
CanMove = false;
Debug.Log("BlockTouchingGround");
StopCoroutine(fallingCoroutine);
}
}
IEnumerator FallRoutine()
{
while (CanMove)
{
yield return new WaitForSeconds(BlockFallDelay);
transform.Translate(0, -BlockFallDistance, 0, Space.World);
}
}
private void Awake()
{
CanMove = true;
}
}```
seems fine, though if you have a rigidbody you should prob use its movements not translate
also instead of == tag use .CompareTag()
I should, but I won't lie, it works therefore I will not touch it if it breaks again.
Is it faster?
much
What is happening here? This is so out of context!
https://paste.ofcode.org/U5aPjSGbmNLeVQ2BwWqy6J
Hello again, im getting this error from Unity. I followed an inventory system tutorial that was really well documented. I checked line for line for anything different, and he also had serialization and save issues, but at the end he solved his issues, but I got this issue he didnt have.
anyone help me with Lerp within coroutine, i dont get why its not working:
{
Debug.Log("Lerp");
startPos = obj.transform.position;
Vector3 target = new Vector3(4f, 8f, -1f);
float timeElapsed = 0;
float totalLerpTime = 5;
while (timeElapsed < totalLerpTime)
{
obj.transform.position = Vector3.Lerp(startPos, target, (elapsedTime/ speed));
timeElapsed += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
Debug.Log(obj.transform.position);
}
nvmd i forgot to add a file save path for my equipment inventory
why are you dividing elapsedTime by speed? that is not one of the variables created within the coroutine . . .
to get a percentage, you divide the current value by the total value . . .
speed — in this context — does not appear to be the total value. we don't even know what it is set to . . .
but even changing that to totalLerpTIme it still doesnt work
also, set the position to target after the while loop to ensure it's at the final position, because when timeElapsed is not less than totalLerpTime, it will not run the code to set it to target . . .
do you need to WaitForEndOfFrame? using null will wait until the next frame . . .
i dont think it matters
do both of the logs appear?
yes
within the while loop, log the elapsedTime or the position to see if the values update . . .
then you need to check startPos and target . . .
or make sure you're updating the correct GameObject . . .
i mean it looks all good
so is the second parameter in Vector3.Lerp the final position you want to get to?
ah fuck
i think i used the wrong variable
yes . . .
it doesn't matter if it looks good. it needs to be correct and work properly. always check every variable used. the program will do exactly what you tell it you. never guess, always confirm . . .
Hi there, I am currently making a tile based game where the player's movement is discrete, which means that the player will move from (0,0) to (0,1) instantly, without going through any decimal points and stuff. Since this is the case, collision detection must be done manually whenever the user gives an input for the player to move in game, and I have a question regarding this:
Question
What is the best way to implement this kind of tile based system where data and information about the block can be accessed easily without too much spaghetti?
My Current Approach
I created a new monobehavior class called "Tile" that stores data about the tiles (like isMovable, isInteractable,tileType etc..), and stuck that on my different tile gameobjects, and in a manager, there would be a long if else just to identify the object (which, of course, is definitely not the best method, and the brains in my braincells really hate it), then, I would create a large 100x100 Tile 2d array to store all the tiles (this was created based on the assumption that my game level will not exceed the 100x100 range).
My small idea
Use inheritance child classes to store the different required data on the tiles, and retrieving them would be quite nice. However, the problem is that, since my array is an array of tiles, so I can only get the tile class, cant really get the child classes and their properties
Any help about this matter is really really appreciated! (I have been losing my mind concerning this problem for the past 4 days and I haven't found a solution myself by experimenting, or searching through the internet). Thanks!
Ideally, you wouldn't need to get the child class. You'd use polymorphism to define different behavior for different tile types. In your manager you'd just need to check tile.IsWalkable or something
But if you really want to, you can cast the base type to the desired type and if it's not null, you would be able to access the child class properties
this is a Unity port of a package that I need for my project, but I'm unsure how to download it to include in my project. Usually I'm used putting the git url in the package manager or downloading a unitypackage file, but this repository doesn't have any of those https://github.com/WulfMarius/NAudio-Unity.git
I tried downloading the zip and putting the files into my assets folder, but that resulted in namespace errors everywhere
ah, so can I assume that I will need to still include those if else to do the collision detection stuff, but I can use polymorphism to change the properties of the tile individually in those child class, and access the already existing properties from the base class tile?
Looks like its for modding unity games, not unity game development
I see, that's a shame
I used the main NAudio package, which worked in editor but webgl builds don't support dlls
how to make box collider be the same shape as mesh?
use mesh collider
There's an option to resize collider
Wouldn't recommend it if it got lots of polygons
For most use cases using simple colliders is preferable
what they want, what you give, it's not that bad anyways
thank you yappy, sexy
I was using a low poly for mesh
Not sure I understand your intention correctly. Maybe sharing some code would be helpful.
ahh, I'm currently outside now, maybe I'll ping you when I get back home, is that alright? Thanks for your help!
It's fine, but I might not be available at that time, so it's better to just ask your question again and provide more details(like code).
ok!
is there correlation between the animation/animator and a Movement State machine? I want to start implementing some animations, but im worried how ill implement it into my state machine
hi, anyone knows why OnMouseDown() doesnt work for me? it does nothing when i click on object with box collider (3d unity)
whats the code look like for that method?
Send the code
public class Card : MonoBehaviour
{
private CardGameManager gm;
public int handIndex;
public bool HasBeenChecked = false;
public GameObject PlayButton;
public GameObject BackButton;
private Vector3 originalPosition;
private Vector3 enlargedScale;
private void Start()
{
gm = FindObjectOfType<CardGameManager>();
originalPosition = transform.position;
enlargedScale = transform.localScale * 3; // 300% enlargement
}
private void OnMouseDown()
{
Debug.Log("Card clicked!");
if (!HasBeenChecked)
{
transform.position += Vector3.up * 5;
HasBeenChecked = true;
gm.availableCardSlots[handIndex] = true;
}
else
{
PlayButton.SetActive(true);
BackButton.SetActive(true);
transform.position = Vector3.zero; // Move to position 0,0,0
transform.localScale = enlargedScale; // Enlarge by 300%
}
}
public void BackOnHand()
{
transform.position = originalPosition; // Move to the original position
transform.localScale /= 3; // Decrease size by 300%
PlayButton.SetActive(false);
BackButton.SetActive(false);
}
public void PlayCard()
{
// Different outcome for every card
Invoke("MoveToDiscard", 2f);
}
public void MoveToDiscard()
{
gm.discardPile.Add(this);
gameObject.SetActive(false);
}
}``` not finished one, but this function should work
Does Debug.Log("Card clicked!" work?
Actually yeah, that's weird
im not finished with the script yet, but it has no effect on clicking
OnMouseDown is called when the user has pressed the mouse button while over the Collider.
i know
Not 100% sure but you may need to add a Physics Raycaster to your camera
i can click on buttons
but buttons are UI objects, your Card is not
doesnt work
Is the event system recognising your card?
can I use hit.transform instead of hit.collider?
or different uses
confused because different tutorials uses different things, but I want to fuse the functions
hey im trying to create a character controller, currently the player moves up and down as well even though there are no key binds for it. I want to limit the movement to only move left and right, and i tried accessing the x value of the readvalue but doesnt work
You can use whatever makes sense in the context of your use case.
why would you not just set the y component of move to zero?
wouldnt that affect the jump of im continiously setting Y to 0 and I add a jump button / function ?
yes, of course, so you would need to do that conditionally
so like if jump button not pressed, y = 0 ?
!OnJump() 
im using new input system btw
Not really. it will depend how you code your jump logic, will Input[move] play a role in that?
i dont think so. I plan on using addforce, I think thats the most straightforward way
and limiting it to one jump so its not spammable and add too much force
Ill answer later, i had to chase the bus lol. I think ill just have enough and make every card a button with the same function lol.
then always setting move y to zero will have no effect on your jump as it is merely zeroing out the input from the Move action
would it be better if I use AddForce instead for everything and just set a cap of how high the addforce can go ?
that way if I continiously hold the analog stick it doesnt endlessly get faster
you dont need to do that. you can try using the IPointer interfaces or add an OnClick Event
that depends entirely of the mechanic you are trying to implement, this is why making character controllers should only be done by people who know what they are doing
:(
Ill answer when i will start unity on school PC lol
Is there a way to detect when user has clicked mouse, without using update?
(Click doesn't have to be necessarily on the gameObject with script attached)
Doesn't event triggers only respond when you click on the gameObject that has the script?
tbh I've not used this for a while, I seem to remember that if you attach the script to the EventSystem then it will pick up everything
my jump method makes my character jump immediately, I tried Forcemode2D.Impulse, but that doesnt apply any up force to the character.
what would be best networking for an fps multiplayer?
One that you implemented yourself.
what do you mean?
Exactly what is sounds like.
so a server that you setup yourself?
Server, or peer to peer setup. Depends on what you need.
allright so better setup a server then just using fishnet or photon
If you can do it and the time and effort is worth it, sure.
so when setting up a server do you need like a regular old computer to make it ?
No... It depends a lot on how you're connected to the internet(provider), the project requirements, desired scale and 100500 other factors.
Networking is an advanced topic and even major developer studios don't get it right.
My point is: if you're a beginner, don't even think about networking. Do the learning, develop a single player title. Once you're at least intermediate+ overall, you can maybe start a networking project.
allright thanks a lot
Networking is the ultimate Catch-22 situation, you can only do it well if you already know how to do it well
is there anyone that could help me with my problem when i press E or mouse0 on the weapon i want to pick up it just goes invisble when its picked up and it still shoots and stuff
Share your setup and code.
A video of the issue might be helpful as well.
is there any way to change the tag of clones of an object. This script is for spawning circles in random coordinates to the right of the screen so that the main player(the square) has to dodge them. The scripts creates clones of the circle just fine but for some reason the clones dont keep the istrigger is true from the original circle. The clones also dont keep the tag of the original circle either. I was able to fix the is trigger part by just always setting it to true but I'm not sure how to fix the tag problem. I tried just typing Gameobject.tag = Rock(the tag i want it to have) right after line 25 but it came up with an error.
this is the error that occured
Occured where?
Why would you delete the part that you're asking about..?
so you didn't use a.tag = ?
delete what?
does that look like a.tag ?
GameObject is the class, not the instance of the class you are trying to change
oh
!ide
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
• Other/None
so what would i do to fix it
I have told you already, twice
okie
oooooh, sorry my brain is so slow. I just understood what you said
thank you
so my debug.log of the move goes to -1 the first time I move left, but when I turn right, it stays at positive 1 even if I have the left analog stick going left. Im trying to add a dash function and thought it'd be easier if I just add a force in the direction of the analog stick, but not sure how id be able to get it to dash left if the move.x never goes negative aside from the first time
Hello guys, i follow the Little Adventurer: Learn to make a 3D action game with Unity tutorial of Single-Minded Ryan in udemy, to make a 3d action game and i have an issue about raycast hit for damage system.
I added a box collider to another object on child of my character and set the box collider, i just wanna create raycasthit but raycast hit is stuck some point and doesn’t work like i wanted.
It doesn’t go through z-axis of box collider, why it happened? Here’s my gizmos method:
private void OnDrawGizmos()
{
damageCasterCollider = GetComponent<Collider>();
if(damageCasterCollider == null)
{
Debug.Log("a");
}
RaycastHit hit;
Vector3 originalPos = transform.position + (-damageCasterCollider.bounds.extents.z) * transform.forward;
//Debug.Log("Transform Position: " + transform.position);
//Debug.Log("I dont know wtf is it: " + (-damageCasterCollider.bounds.extents.z));
//Debug.Log("Standart transform forward value: " + transform.forward);
//Debug.Log("Original position: " + originalPos);
//Debug.Log("I dont know wtf is it: " + (damageCasterCollider.bounds.extents));
bool isHit = Physics.BoxCast(originalPos, damageCasterCollider.bounds.extents / 2, transform.forward , out hit, transform.rotation, damageCasterCollider.bounds.extents.z, 6);;
Debug.DrawLine(originalPos, hit.point);
Gizmos.color = Color.yellow;
Gizmos.DrawSphere(hit.point, 0.3f);
if (isHit)
{
Gizmos.color = Color.yellow;
Gizmos.DrawSphere(hit.point, 0.3f);
}
}
does anyone know an asset for sound occlusion?
Right so I have a array for some cards, I would like 5 cards to display on the screen at a time. Currently the player can scroll through the displayed cards. But I want it so when it gets to the end of the displayed cards, It removes the first displayed card and then adds a new displayed card from the array.... But I'm not sure how I'd code that?
so lets say I have 15 cards, I only want 5 to display at a time. Just need to be able to cycle through the array
and when I get to the end of the array, It starts from the beginning again
I can do it with 1 card easily
but not sure how to do it with 5 cards and then adding cards which are not currently in the scene
you need a sliding window
btw you will never show (magnify) the last card
For example 1,2,3 is displayed
Sliding window, How is that used?
or cicular buffer (queue)
you cant use c# built-in one since its doesnt support random access
eg if you have an array and you want to show 4 cards at once
1 2 3 4 5 6 7 8
h t
then you show the card from h to t, each time to you turn left: h-- and t--, turn right: h++ and t++ and mod the queue capacity
I could add the cards onto the Scroll view UI element and scroll to only show the cards in which I want displayed?
hm yeah, that is something I'll probably look into
how do u change that camera size to a different resolution size
All right guys I have big issue in my mind. So let's imagine it, I have created two scripts; first one calls "Gun" and other one is "GunController". And I didn't write anything into "Gun" script. As you can see I writed these codes that i sended in picture. But I have question in my mind. As you can see there is parameter calls "startingGun", also I have prefab weapon. I didn't understand how can I assign this weapon prefab as "Gun" type parameter. prefab is gameobject but "Gun" is just script.
Are you saying that you dragged your prefab object to the StartingGun in the inspector and are confused how you can assign a prefab to a variable that isn’t “gameObject” type?
Yes exactly
If so, the answer is just that Unity is smart enough to find the correct component on the prefab you drag in in the inspector.
If your prefab has a component of the variable type you are assigning, Unity will just assign your prefab’s component to that variable.
I didn't put anything on this prefab. Literally nothing
Do you have a gun script on the prefab at all?
and I'm suprised that i didn't get any error. Also as you can see, when I created the new gun i signed as Gun
Even an empty one?
Can you show the inspector for your gun prefab?
I'm not able to reach the inspector bcs im on another pc
so basically "Gun" script type can store prefabs?
Come back when you have the project open and you can check what you actually have
I can't get my keyboard WSAD movement to work. It doesn't detect when the buttons are pressed. Any ideas?
using UnityEngine;
using UnityEngine.InputSystem;
public class WSAD : MonoBehaviour
{
public GameObject GO;
public CharacterController characterController;
private InputAction movementInput;
private Vector2 movementDirection;
[SerializeField] private float movementSpeed = 5f;
private void OnEnable()
{
movementInput.Enable();
}
private void OnDisable()
{
movementInput.Disable();
}
private void Awake()
{
GO = GameObject.Find("Model");
characterController = GO.GetComponent<CharacterController>();
// Initialize the movement input action
movementInput = new InputAction("Movement", InputActionType.Value, "<Keyboard>/wsad");
movementInput.Enable();
// Register the movement callback
movementInput.performed += ctx => movementDirection = ctx.ReadValue<Vector2>();
movementInput.canceled += ctx => movementDirection = Vector2.zero;
}
private void Update()
{
// Move the player based on input
Vector3 movement = new Vector3(movementDirection.x, 0f, movementDirection.y) * movementSpeed * Time.deltaTime;
characterController.Move(movement);
Debug.Log("Update - movement: " + movement);
}
}
Okay my bad, my prefab had "Gun" script. So basically when the prefab has the script, so this script parameter can store this GameObject?
what do you mean by script parameter?
I mean this parameter calls "startingGun" which is the parameter of "Gun" script right? or is this my fault to describe it.
If you have a variable in a script that has a gameobject OR component type, then Unity will let you drag a prefab with that component on it to the component type.
Then that component variable effectively has a reference to your prefab although what it really has is a reference to the specified component on your prefab.
All right, thank you so much
a prefab is a GameObject stored as an asset in project folder. if that GameObject has a Gun script attached to it, then you can assign it to a variable with a Gun type . . .
a script attached to a GameObject is a Component. a Component is a Type. if the GameObject has a component matching the variable type of a script, you can drag it as a reference into that variable slot . . .
thank you for everything and I'm sorry if i bothered with my question but I'm new at this. So it's hard for me the understand the all concept
not a problem, good luck!
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//See where a ray from mouse position hits our invisible lever plane, and have lever look at that point
if (Physics.Raycast(ray, out hit, 10, leverPlaneMask))
{
Vector3 lookPosition = hit.point - transform.position;
lookPosition.z = 0; //We can zero out one of the axis because the lever cannot move in all 3 axis
Quaternion lookRotation = Quaternion.LookRotation(lookPosition);
transform.rotation = lookRotation;
}
}``` how to clamp? I know I should put xrotation on x so it knows where to clamp, but where is x?
I want to learn how to break this down so i can adjust, if ok, can you help me understand what is happening in the computations
I am trying lookPosition.x = Mathf.Clamp(lookPosition, -90f, 90f); but it doesnt work

Hi guys how would i get an object to spawn in front of another object when its enabled? in my case i have coins spawning every so offten randomly. and i want a cloud to cover them when they are enabled? my game is 2D
I’m a little confused about what you’re trying to do. Should there be one cloud per coin?
so you want to have a little "poof" as the coin spawns in
and then the poof goes away
the reason in doing this is beacasue i have object pooling in my game. and if i was to spawn the cloud/ make it a child to the coin. it will get destroyed and not come back when enabled again if that makes sense
Okay, so you'll want to spawn a cloud prefab in the coin's OnEnable method (or fetch one from another object pool)
ill show you a clip of the game. so it make more sense. im just popping out now so ill send it in a second
how can i activate a particle system from a prefab with the script in another?
public GameObject prefabFogo;
ParticleSystem fogo;
void Start()
{
rb = GetComponent<Rigidbody>();
fogo = prefabFogo.GetComponent<ParticleSystem>();
if (fogo != null)
{
Debug.Log("Particle System Found");
fogo.Play();
}
the debug log is appearing, but the particle is not playing
why are you trying to play a particle system on a prefab?
prefabs don't exist in the scene
I fixed the clamp 
but transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 5.0f); is it ok to multiply time.deltatime to 5?
or no
I wanted to make it faster, but I might be making x5 more calls?'
the numbers you plug into the parameters have nothing to do with how many times this code is running
Time.deltaTime * 5.0f so this is just how fast it moves or reacts?
or no
You're not really using Slerp correctly in any case
so it's kind of esoteric
what is esoteric
mysterious
not clearly defined
The third parameter in Slerp is supposed to be the percentage from A to B you want the result to be
but you're misusing Slerp (in a very common way) in a way that makes the units or meaning of that parameter very hard to define
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//See where a ray from mouse position hits our invisible lever plane, and have lever look at that point
if (Physics.Raycast(ray, out hit, 10, leverPlaneMask))
{
Vector3 lookPosition = hit.point - transform.position;
lookPosition.z = 0; //We can zero out one of the axis because the lever cannot move in all 3 axis
//lookPosition.x = Mathf.Clamp(lookPosition, -90f, 90f);
Quaternion lookRotation = Quaternion.LookRotation(lookPosition);
if (Quaternion.Angle (lookRotation, baseRotation) <= maxAngle)
{
targetRotation = lookRotation;
}
//transform.rotation = lookRotation;
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 5.0f);
Debug.Log(hit.point);
//transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.deltaTime * 5f);
}
}``` it is like this, but not sure if I did it right
but it works i think
also, i dont really know how to use it much since I am just starting, everything will be wrong, but I want to learn 
It will work it's just not easy to adjust or think about the speed in any sense
like it's not "meters per second", it's not going to swing the lever all the way in some defined number of seconds.
There's no concrete measurements to reason about - you just kind of adjust those numbers and see if it "feels" right
and it's also going to slightly have different behavior based on framerate. But it will generally feel "ok"
If you used for example Quaternion.RotateTowards(current, target, Time.deltaTime * 5f); then you could confidently say "the lever will rotate at 5 degrees per second"
Also Slerp used in this way will theoretically never completely reach the end state
I also checked, it doesnt fully go to the end 
so first one is current and 2nd is target?
for RotateTowards it's (current, target, speed)
for Slerp/Lerp it's supposed to be (start, end, percent)
but you're doing (current, end, some arbitrary number)
which gives a nice effect and is used commonly, it's just a little bit odd to work with
ah I see I see
, I never knew about RotateTowards
I think it is what I need
thank you praetor
What is the point of multiplying by Time.fixedDeltaTime instead of 0.02?
Fixed timestep can be changed (in code or in the editor)
it's not always 0.02
that's just the default
!ide
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
• Other/None
Is your cloud prefab at 0,0,0?
Oh, that makes sense. In my case why do I need to multiply acceleration by Time.fixedDeltaTime. Here is what I mean:
Velocity.x = Mathf.Lerp(velocity.x, inputVelocity.x, acceleration * Time.fixedDeltaTime)```
Well you're misusing Lerp here, but in general the third parameter to Lerp needs to be between 0 and 1 or it's pretty meaningless
Because you're using Lerp wrong
https://unity.huh.how/lerp/wrong-lerp
in this case it's a bit wired because of the whole lerping business. but the short answer is that when dealing with physics based movement, most of the time you need to use the time component in one of the kinematic formulas. and using a constant time derivative like FixedDeltaTime makes it infinitely easier to deal with getting the calculations 'correct'
Sure but I want to point out in this case that's completely irrelevant and this used of fixedDeltaTime is merely a constant mul;tiplier into an awkward misuse of Lerp
I totally agree, hence the preface of my message. but thought it might be helpful to know / understand why people and tutorials will keep telling you to use FixedDeltaTime when dealing with physics movement 😄
Also to be clear, when I hear "physics movement", I think AddForce and setting velocity (and not MovePosition or setting transform.position, which are not physics).
For physics based movement you do NOT want to include a time component like FixedDeltaTime because that is already included behind the scenes, or in the case of ForceMode.Impulse, it is unnecessary
It IS needed in NON-physics-based movement though
fair enough, but I think you're arguing semantics at that point, because when I hear non-physics based movement. I think of stuff that doesn't use the kinematic formulas at all, and are just about feeling good. often not even using fixed update
nah its not symantics.. if ur setting velocity directly in fixed update theres no need for scaling
I don't think this is semantics. Physics based has a specific and defined meaning. The way I described it is what it means..
Physics based means it moves via the physics engine and reacts to physics forces.
ur just compressing the multiplier
leading to higher values to achieve the samething
if ur doing ur calculations in update then yea it might be necessary
private void ApplyGravity()
{
Vector3 gravityForce = new Vector3(0f, -gravity, 0f) * rb.mass;
Vector3 gravityAcceleration = gravityForce;
rb.velocity += gravityAcceleration * Time.fixedDeltaTime; // this is when i'd use fixedDeltaTime
}```
anytime i do += or *= i include either Time.fixedDeltaTime or time.deltaTime depenind on where it is
cause position change is velocity * time
ya i think ur right tbh
b/c velocity only gets calculated during the fixed time step
if u were calculating the velocity in update.. w/o scaling that.. now that would be an issue i would assume
no velocity in general
like custom calculations
no time scaling
Velocity is in meters/second, so it is already scaled by time
Maybe I should have said physics ENGINE based earlier, and that would be clearer. Now that I think about it
depends on where ur calculating that velocity
Velocity and AddForce are handled by the physics engine directly
physics are always fun 😄
im guilty of modifying the velocity.. i rarely use AddForce
never noticed an issue tho.. the engine pretty robust
It's a perfectly fair way to do things 🤷♂️
Is there a way to change scene index?
im not math savy enough to use AddForce
AddForce is basically just a utility function for changing the velocity 😄
Yeah. In the build settings
multiplying by fixedDeltaTime is correct in that example, when manipulating rb.velocity. what's not correct is multiplying by rb.mass. since in this context we're getting the acceleration of gravity, not the force.
ya, but when u use AddForce.. and u want things proper its difficult for someone thats not math savy.. using equations to get the right speed/vel
or atleast for me it is
No, you should never multiply velocity by timescale in unity, neither fixed nor normal timescale
Unity already multiplies the velocity value by timescale, by multiplying it with timescale again you cause timescale to have an exponential effect on the distance your object travels
i know its simple.. but sometimes i get hung up on it
Thank 🙂
You have to just reorder the scenes btw
drag and drop
Hi, I'm new to Unity and I would like to know what you would recommend to me to progress quickly (tutorial, project, etc.) for my final project, a multiplayer card game.
say i want something to move X meters per second
float requiredForce = rb.mass * targetSpeed / Time.fixedDeltaTime;
rb.AddForce(transform.forward * requiredForce, ForceMode.Force);```
wouldn't this be the right way to do that?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Cut your project into tasks and solve these tasks one by one in a playground, in the end the last task is bringing it all together
start simple.. do something, build on that something.. rinse and repeat
Vector3 velocityDiff = desiredVelocity - rb.velocity;
rb.AddForce(velocityDiff, ForceMode.VelocityChange);```
of course you can also just do rb.velocity = desiredVelocity;
i wish i'd payed more attention in school
thx
so theres no need to use the mass?
if you want a fixed speed no
if you want to calculate how hard an object bouncing into yours affects the speed then yes
VelocityChange accounts for that
okay cool.. i need to start doing stuff like this.. w/ math in mind.. soo far in physics i just tinker and change values until i get wat i want..
thats not the proper way to really learn anything
rb.velocity = transform.forward * targetSpeed; would also do the trick
what math subject do physics calulations fall under? in school i took Physics 1 and 2 but isn't it included in some other branch of math?
calculus maybe?
isnt that algebra? not sure tbh
yea, u may be right.
all i remember in physics we had these "train problems" and it would take a whole 2 pages of college ruled worth of work..
(you had to show u work or u'd flunk)
vector arithmetic?
a train leaves station a, heading towards station b at 10:00 travelling..
that type of junk ☝️ lol
that would be algebra but depending on the nature of the equation that results you might need calculus to solve it
alrighty.. sounds legit. i need a refresher on that stuff for sure imma go hunt down some tutor type sites and see how rusty i am
it depends, you need calculus (specifically understand, integrals, and derivatives). for calculations that involve change over time (like if acc isn't constant). but for most use cases just learning the kinematic equations for constant acceleration is more than enough. and that's just simple algebra
these would make EPIC examples to recreate in unity
all the exam questions i can remember all involved cars, trains, planes, rockets, and balls
not sure where to find a sk at..
im having a bit of a problem , i dont really know how i can make a smooth dash ability like daves dash tutorial since im using a character controller and he uses a rigidbody , how can i make it like his but character controller?
FULL 3D DASH ABILITY in 11 MINUTES - Unity Tutorial
In this video I'm going to show you how to code a full 3D Dash ability in Unity. Including dashing in multiple directions based on player input, keeping the momentum after dashing and adding camera effects to make the dash feel more alive.
If this tutorial has helped you in any way, I would r...
just like ur doing there.. all u need to do is flip that canDash bool to true... and set it back to false in the coroutine
Was watching a video that was telling people to use [SerializeField] instead of public to declare variables. Is there a reason behind this preference?
yes, w/ serializedfield u can keep the variable private
private is better than public..
less chance to f*ck up ur code
Mostly because you don't want public fields all over the place
In most cases you need close to none public fields
only use public variables when u need access to them outside the class theyre within
ah
It looks pretty bad ngl , I watched Dave's dash tutorial and I want it like that but I'm using a character controller and he uses rigid body so idek how to do it with a character controller
Understood, will be following this henseforth then
1 sec i have a dash mechanic on one of my CC projects, let me find it and i'll show u some example code
serialized field FTW
ignore the [ReadOnly] thats something else
Ooo , thank you! Appreciate it
its a hefty boi
sound to me like you just want the movement to be a bit smoother, I think an animation curve is the easies thing to use here.
public float dashDuration = 5.0f;
public float dashSpeed = 10.0f;
public AnimationCurve accelerationCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 1));
IEnumerator Dash()
{
float elapsedTime = 0.0f;
while (elapsedTime < dashDuration)
{
float normalizedTime = elapsedTime / dashDuration;
float speedMultiplier = accelerationCurve.Evaluate(normalizedTime);
transform.Translate(Vector3.forward * dashSpeed * speedMultiplier * Time.deltaTime, Space.World);
elapsedTime += Time.deltaTime;
yield return null;
}
}
then you change the accelerationCurve in the editor to match the 'smoothness' you want
Thank you, I will fix this when I get the chance.
Oh! That makes sense, thank you.
this is how i did it.. (for input I just set isDashing to true) then the coroutine sets it back to false..
the dash vector is just added into the Move function.. and at the end of it im slowly lerping it back to zero..
so when i hit the button it adds the dash value i have assigned.. and then it takes care of itself..
Oh boy , what project were you making for this?
I will try yours and spawns code and see which one fits my game , thank you!
a pirate game i abandoned @cinder crag
you can see the dash towards the end (its a little subtle) but i didnt want it to be a big dash
Let's gooo RGB pirate ship
Looks cool
Npnp
i might return to it sometime
Would be cool if you finish it ,
i bit off more than i can chew
that actually looks pretty sick 😄
scoped too big
if i had a team i'd probably try to finish it
lol BOOM
oh i forgot dash += Camera.main.transform.forward * (playerSettings.dashForce * 1f); i do this when i get the input for dash... then the move function calls the coroutine because the dash force is now greater than the magnitude i assigned cs if (dash.magnitude > dashMagnitude) { finalVelocity += dash; StartCoroutine(Dash()); }
i wrote it a long time ago.. sooo its not the best code tbh
but it works..
lol
Hi I have this code that I assign to gameobject which I then put on my two buttons, one is SAVE and one is LOAD. When I click SAVE it will save my data(player and cam position and amount of deaths) and when I click LOAD it will load all that data. Problem is that I have SAVE and LOAD button in my game scene and I want SAVE button in my game scene and LOAD button in my main menu scene but then I dont know how can I implement same method to just load game data and load game scene.
check dms when u can
make the save manager a DDOL singleton
like this
but also my SaveServiceSystem script is on gameobject inside game scene and menumanager is in main menu scene
that's just a static instance property
Which is only one part of making a DDOL singleton
you would need it to exist either in both scenes or dynamically load it in on demand
and enforce its singletonness
which method is easier
is there a quick way to make this change the instance of the script rather than the script itself?
Yes, like that
but it is changing the script for all instances
unless you made your variables static it won't
This code will be changing the values of the BallistaScript on the selectedTower object
and why do I need to make DDOL singleton cause that script is in scene that will be loaded after being in menu
oh nvm
i thought it was changing it for all of them but it isnt changing it for any lol
mb
turns out im an idiot and forgot to actually use the function anywhere
If you want to load data in one scene and have it accessible in another you're going to need to have a way to move data between scenes. A DDOL singleton is one good way of doing that.
like this?
no
that doesn't enforce it being a singleton, nor does it assign the instance property anywhere.
just look up Unity DDOL singleton for examples
if im not crazy, at 2 base attack speed this should give 0.4 attack speed at first and then 0.8 attack speed after right? making it 3.2?
ok so im trying to make an fps i managed to make a camera that renders the world and another that renders the weapons. how do i render the weapon cam on top of the world cam?
something like that yes
Will that work like that or should I add something more so it becomes ddol singleton
depends on your render pipeline but you want either camera stacking or camera composition / overlay and base cameras
im using URP
Try logging the values before you do the math, they probably aren't what you think they are
i think i just figured it out
And I still dont understand how will I get that data saved from my game scene and when I again start to play game and im in main menu, then I click load game how will it load my data that was saved when I clicked on save button
i was increasing the upgradeCount before calling the function
Hello
object.DontDestroyOnLoad for some reason creates a copy of an object it is refered to everytime a different scene loads:
void Update()
{
Object.DontDestroyOnLoad(this);
}
you need to simply load it into a POCO and read it from the save manager when needed
what is POCO?
i.e:
- Press load in main menu to call the load function
- Load simply loads the data into a plain object and stores it on the save amanger
- You load the game scene
- Game scene script reads the loaded data from the save manager
plain old C# object
Why are you doing it in Update you monster
But it doesnt work in Start too 😦
anyway it doesn't make a copy it simply moves it into the DDOL scene