- Home /
What is wrong with my C# script?
Hello,
While translating a script from Unityscript to C# I received compiler errors when trying to start the game. The source of errors came from the "CharacterDamage" script. This is the content of the script:
using UnityEngine;
using System.Collections;
public class CharacterDamage : MonoBehaviour
{
public Transform deadReplacement;
public AudioClip dieSound;
public float hitPoints = 100f;
public void ApplyDamage(float damage)
{
if (hitPoints > 0f)
{
hitPoints -= damage;
if (hitPoints <= 0f)
{
Detonate();
}
}
}
public static void CopyTransformsRecurse(Transform src, Transform dst)
{
dst.position = src.position;
dst.rotation = src.rotation;
foreach (Transform child in transform) {
Transform curSrc = src.Find(child.name);
if (curSrc)
CopyTransformsRecurse(curSrc, child);
}
}
public void Detonate()
{
Object.Destroy(gameObject);
if (dieSound != null)
{
AudioSource.PlayClipAtPoint(dieSound, transform.position);
}
if (deadReplacement != null)
{
Transform dst = Object.Instantiate(deadReplacement, transform.position, transform.rotation);
CopyTransformsRecurse(transform, dst);
}
}
}
The following errors I got are:
CharacterDamage.cs(27,45): error CS0120: An object reference is required to access non-static member
UnityEngine.Component.transform' > CharacterDamage.cs(43,23): error CS0266: Cannot implicitly convert type
UnityEngine.Object' to `UnityEngine.Transform'. An explicit conversion exists (are you missing a cast?)
Please, what are the reasons why I am getting the errors? And how do I solve the problem?
Thank you,
Xarlexus1
I can't add the script to a game object when it can't compile. I have tried removing Object at line 43, but I still am getting the same errors.
Answer by Bunny83 · Sep 16, 2013 at 07:37 AM
Line 27 should be:
foreach (Transform child in src.transform) {
and Line 43 should be:
Transform dst = (Transform)Object.Instantiate(deadReplacement, transform.position, transform.rotation);
Answer by blackcoper · Sep 16, 2013 at 07:54 AM
first : cannot access non-static member
Transform allChildren = GameObject.Find("GameObject").transform;
foreach (Transform child in allChildren) {
Transform curSrc = src.Find(child.name);
if (curSrc)
CopyTransformsRecurse(curSrc, child);
}
second : missing casting
Transform dst = Object.Instantiate(deadReplacement, transform.position, transform.rotation) as Transform;