i cannot seem to have ScriptB talk to ScriptA without linking them however i cannot drag and drop in inspecter as ScriptB is attached to a prefab…
should i be u sing an event? how? im still haveing trubble trying to trial and error learn this stuff…
delegate? ive tryed dident work… maybe i did it wrong?
scriptable object that ScriptA inheartis from? for exp??
the reason im using a PreFab for the Enemy is it can be respawned as well as when the scene loads it randomly places enemys around of a random amount between 10-15…
am i doing this wrong? yes im new please help… ive been youtubing and reading about everything i could for feels like a week now about ready to stick the exp in my targeting script mixed with attack but that wont work right… mnight actualy delay the response of the game
so i want Enemy to
public int expBase = 10;
public ScriptA player;
private void Start()
{
player = GetComponent<ScriptA>();
Debug.Log(GetComponent<ScriptA>()); ///returns null
}
public void TakeDamage(int damage)
{
enemyHealth-= damage;
if (enemyHealth <= 0)
{
AddExp();
Destroy(this.gameObject);
}
}
public void AddExp()
{
player.playerCurrentExp += oreNodeExp;
}
}
One way you could do this is by storing the Instantiated prefab in a list:
GameObject prefab;
List<GameObject> prefabList = new List<GameObject>(); //or any script/class
void Start()
{
prefabList.Add(Instantiate(prefab, transform.position, transform.rotation));
//you could also do: scriptList.Add(Instantiate(prefab, transform.position, transform.rotation).GetComponent<Script>());
}
I also think you’re looking in the wrong place for your player script however, I don’t know how your scene looks like.
I think this is what you’re trying to do:
Usually I get a reference to another GameObject’s components based on the interaction itself. How does your player cause damage to the enemy? For example, if that is done via a physics system collision, you get the reference during the collision.
You can also use things like FindWithTag to get a reference without any direct interaction. If there is just 1 player object, you can also have it store a public static reference to itself that any other script can access.
By the way, naming your scripts things like ScriptA makes it extremely difficult to maintain your project down the road, and makes it difficult to get other people to help since you need to explain what things like this are, instead of the name of the script being self explanatory.
Depending on lifetime and expectations of interoperation between these things, it might be appropriate to make a GameManager object that everybody uses, basically a singleton-ish object.
Each object would come alive and register itself with the GameManager, and tolerate the other one not being ready for a frame or two as well.
In Unity, you can do singletons that are MonoBehaviors and get Update() calls, which is even cooler for a lot of GameManager type of applications.
Here are some super-simple Singleton examples to take and modify:
These are pure-code solutions, do not put anything into any scene, just access it via .Instance!
If it is a GameManager, when the game is over, make a function in that singleton that Destroys itself so the next time you access it you get a fresh one, something like:
public void DestroyThyself()
{
Destroy(gameObject);
Instance = null; // because destroy doesn't happen until end of frame
}
i have the instantiated object added to a list on creation, thats actualy how my targeting works for ScriptA… it finds objects in the list within a sertain range then i push a button to cycle threw them setting each one at a time to my setTarget Variable…
thinking from responses i should learn more… allways learn more…
i changed it to make it simpler for people to understand instead of pasteing my entire script… im really sorry
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class PlayCon : MonoBehaviour
{
public float charSpeed = 5f;
[field: SerializeField] private Rigidbody2D rb2d;
[field: SerializeField] private GameObject playPosition;
[field: SerializeField] private LayerMask oreLayers;
[Space] //attacking
[field: SerializeField] private Transform attackPos;
[field: SerializeField] private float attackRange;
public int damage;
public float timeBetweenAttacks;
public float startTimeOfAttack = 5;
private bool canAttack = false;
Vector2 moveDir;
[SerializeField] Camera cam;
[Space]//targeting crosshair
[SerializeField] private GameObject targetCrossHair;
[SerializeField] private float targetingRange;
public OreNodeStats setTarget;
[SerializeField] private int indexing;
[SerializeField] private Inventory inventory;
[Space]// target frame
[SerializeField] private Slider castingBar;
[SerializeField] private GameObject castingBarFrame;
[SerializeField] private GameObject targetFrame;
[SerializeField] private GameObject targetNameFrame;
[SerializeField] private GameObject targetHealthFrame;
[SerializeField] private Slider targetSliderFrame;
private bool setTargetoff = false;
/// <summary>
/// stats player
/// Dwarf +2 Con, +2int
/// Base Stats 16 14 13 12 11
/// </summary>
private int playerBaseDex;
private int playerBaseInt;
private int playerBaseStr;
private int playerBaseCon;
private int playerBaseChar;
private int playerBasexp;
[Space]
public int playerCurrentExp;
private int playerCurrentDex;
private int playerCurrentInt;
private int playerCurrentStr;
private int playerCurrentCon;
private int playerCurrentChar;
[SerializeField] private TextMeshProUGUI playerDisplayDex;
[SerializeField] private TextMeshProUGUI playerDisplayInt;
[SerializeField] private TextMeshProUGUI playerDisplayStr;
[SerializeField] private TextMeshProUGUI playerDisplayCon;
[SerializeField] private TextMeshProUGUI playerDisplayChar;
[SerializeField] private Slider playerDisplayExp;
private void Awake()
{
playerBaseDex = 12;
playerBaseInt = 13;
playerBaseStr = 14;
playerBaseCon = 16;
playerBaseChar = 11;
playerBasexp = 0;
}
private void OnTriggerEnter2D(Collider2D other)
{
var groundItem = other.GetComponent<GroundItem>();
if (groundItem)
{
inventory.AddItemAmount(groundItem._item.GetCopy(),groundItem._amount);
if (inventory.AddItemAmount(groundItem._item.GetCopy(), groundItem._amount) == true)
{
Destroy(other.gameObject);
}
else
{
Debug.Log("inventory full");
}
}
}
/// <summary>
/// the update function run every frame
/// attack delay timer
/// target crosshair location activation deactivation
/// </summary>
void Update()
{
MoveInput();
if (timeBetweenAttacks <= 0)
{
canAttack = true;
castingBarFrame.SetActive(false);
}
else
{
castingBarFrame.SetActive(true);
timeBetweenAttacks -= Time.deltaTime;
Casting(timeBetweenAttacks);
canAttack = false;
}
if (setTarget != null)
{
Targeting();
}
else
{
RemoveTarget();
}
}
private void RemoveTarget()
{
targetCrossHair.SetActive(false);
targetFrame.transform.GetChild(0).GetComponentInChildren<Image>().sprite = null;
targetNameFrame.transform.GetChild(0).GetComponentInChildren<TextMeshProUGUI>().text = "no Target";
}
private void Targeting()
{
targetCrossHair.transform.position = setTarget.transform.position;
targetCrossHair.SetActive(true);
targetFrame.transform.GetChild(0).GetComponentInChildren<Image>().sprite = setTarget.uiDisplay;
targetNameFrame.transform.GetChild(0).GetComponentInChildren<TextMeshProUGUI>().text = setTarget.oreName;
targetSliderFrame.value = setTarget.oreHealth;
targetHealthFrame.transform.GetChild(0).GetComponentInChildren<TextMeshProUGUI>().text = setTarget.oreHealth.ToString("n0");
}
/// <summary>
/// casting bar
/// </summary>
/// <param name="castingValue"></param>
public void Casting(float castingValue)
{
castingBar.value = castingValue;
}
void FixedUpdate()
{
rb2d.velocity = moveDir * charSpeed;
}
void MoveInput()
{
float mx =SimpleInput.GetAxisRaw("Horizontal");
float my = SimpleInput.GetAxisRaw("Vertical");
moveDir = new Vector2(mx, my).normalized;
}
/// <summary>
/// setting the target so one can attack it
/// </summary>
private void TargetSet()
{
if (Vector2.Distance(transform.position, EnemyController.oreList[indexing].transform.position) <= targetingRange)
{
if (setTarget == null)
{
indexing = 0;
Target();
}
else if (indexing >= EnemyController.oreList.Count)
{
indexing = 0;
Target();
}
else
{
indexing++;
Target();
}
}
else
{
indexing = 0;
Debug.Log("target to far");
}
}
private void Target()
{
setTarget = EnemyController.oreList[indexing];
//targetCrossHair.transform.position = setTarget.transform.position;
//targetCrossHair.SetActive(true);
//targetFrame.transform.GetChild(0).GetComponentInChildren<Image>().sprite = setTarget.uiDisplay;
}
public void Attack()
{
if (setTarget == null)
{
Debug.Log("noTarget");
}
if (Vector2.Distance(this.transform.position, setTarget.transform.position) <= attackRange)
{
if (canAttack == true)
{
setTarget.TakeDamage(damage);
timeBetweenAttacks = startTimeOfAttack;
}
else
Debug.Log(setTarget + "to Far");
}
}
/// <summary>
/// Player Display updates for Stats
/// </summary>
public void UpdatePlayerDex()
{
playerDisplayDex.GetComponent<TextMeshProUGUI>().text = playerCurrentDex.ToString("n0");
}
public void UpdatePlayerStr()
{
playerDisplayStr.GetComponent<TextMeshProUGUI>().text = playerCurrentStr.ToString("n0");
}
public void UpdatePlayerCon()
{
playerDisplayCon.GetComponent<TextMeshProUGUI>().text = playerCurrentCon.ToString("n0");
}
public void UpdatePlayerInt()
{
playerDisplayInt.GetComponent<TextMeshProUGUI>().text = playerCurrentInt.ToString("n0");
}
public void UpdatePlayerChar()
{
playerDisplayChar.GetComponent<TextMeshProUGUI>().text = playerCurrentChar.ToString("n0");
}
public void UpdatePlayerExp()
{
playerDisplayExp.value = playerCurrentExp;
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(attackPos.position, targetingRange);
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class OreNodeStats : MonoBehaviour
{
public int oreHealth;
public GameObject oreItemDroppable;
public Sprite uiDisplay;
public String oreName;
public int oreNodeExp = 10;
public PlayCon player;
private void Start()
{
EnemyController.oreList.Add(this);
oreHealth = 100;
player = GetComponent<PlayCon>();
Debug.Log(GetComponent<PlayCon>());
}
public void TakeDamage(int damage)
{
oreHealth -= damage;
if (oreHealth <= 0)
{
Instantiate(oreItemDroppable, transform.position, Quaternion.identity);
EnemyController.oreList.Remove(this);
AddExp();
Destroy(this.gameObject);
}
}
public void AddExp()
{
player.playerCurrentExp += oreNodeExp;
}
}
i tryed Gameobject.find but it said nothing for player could be find as well as with find tag… probably doing it wrong. feels like this past week ive done everything wrong i could…
what a wonderfull response thank you… i will look more into Gamemanagers and singletons tomorow when im more awake… my ScriptA is more of a playercontroller/game manager script i think… check above if your up for reading code